<?php

class CustomerAcceptance{
    /**
     * get info for customer acceptance
     * @param  INT $idOrder    id for the order
     * @param  INT $idPackage  id for the package
     * @return Array           custoemr acceptance info
     */
    public function getCustomerAcceptance($idOrder){
        global $database;
        $idOrder = $database->escapeValue($idOrder);
        $data = [];
        $orderExtraActions = new orderExtraActions();

        $sql = "SELECT o.id AS idOrder,
                    o.customerAccepted,
                    o.customerDeclineReason,
                    DATE_FORMAT(o.acceptanceDueDate, '%D %b, %y') as acceptanceDueDate,
                    o.acceptanceDueDate as acceptanceDueDateNoFormat
                FROM ".TABLES['orders']." o
                WHERE o.id=$idOrder";

        $query = $database->query($sql);
        if($database->numRows($query) > 0){
            $row = $database->fetchArray($query);
            $dueDate = new DateTime($row['acceptanceDueDateNoFormat']);
            $now = time();
            $timeDiff = ($dueDate->getTimestamp() - $now ) / (3600 *24);
            $row['daysDiff'] = $timeDiff;
        }
        $data = $row;

        $sql = "SELECT
                   d.id AS idDocument,
                   d.documentName,
                   d.extension,
                   rod.idOrder
                FROM ".TABLES['documents']." d
                INNER JOIN ".TABLES['rel_order_documents']." rod
                    ON rod.idDocument=d.id
                WHERE rod.idOrder=$idOrder AND d.idDocumentType=".$orderExtraActions::DOCUMENT_TYPES['ID_ACCEPTANCE_DOC_TYPE'];

        $query = $database->query($sql);
        while($row = $database->fetchArray($query)) {
            $data['acceptanceDocuments'][] = $row;
        }

        return $data;
    }

    /**
     * get the number of acceptance documents uploaded
     * @param  INT $idOrder id for the order
     * @return INT          number of uploaded documents
     */
    private function getAcceptanceDocumentsCount($idOrder){
        global $database;
        $orderExtraActions = new orderExtraActions();

        $sql = "SELECT COUNT(idDocument) AS totalDocumentsUplaoded
                FROM ".TABLES['rel_order_documents']." rod
                INNER JOIN ".TABLES['documents']." d
                    ON d.id=rod.idDocument AND d.idDocumentType=".$orderExtraActions::DOCUMENT_TYPES['ID_ACCEPTANCE_DOC_TYPE']."
                WHERE rod.idOrder=$idOrder
                ";
        $query = $database->query($sql);
        $row = $database->fetchArray($query);

        return intval($row['totalDocumentsUplaoded']);
    }

    /**
     * customer change acceptance status for a package
     * @param  INT $idOrder   id for the order
     * @param  String $actionType accept or decline the installation
     * @param  String $declineReason the reason why the customer declined the installation
     * @return Array          update message
     */
    public function acceptDeclineInstallation($idOrder, $actionType, $declineReason){
        global $database;
        $idOrder = $database->escapeValue($idOrder);
        $actionType = trim($database->escapeValue($actionType));
        $declineReason = trim($database->escapeValue($declineReason));
        $data = [];
        $customerAcceptanceStatus = 1;
        $successMessage = 'INSTALLATION_ACCEPTED';

        if($actionType === 'decline') {
            if(!$declineReason) {
                $data['messages'][] = [
                    'code' => 'error',
                    'message' => 'DECLINE_REASON_EMPTY'
                ];

                return $data;
            }
            $customerAcceptanceStatus = -1;
            $successMessage = 'INSTALLATION_DECLINED';
        }else{
            $uploadedDocuments = $this->getAcceptanceDocumentsCount($idOrder);
            if($uploadedDocuments === 0){
                $data['messages'][] = [
                    'code' => 'error',
                    'message' => 'ACCEPTANCE_NOT_UPLOADED'
                ];

                return $data;
            }
        }

        $sql = "UPDATE ".TABLES['orders']."
                SET customerAccepted=$customerAcceptanceStatus,
                    customerDeclineReason='$declineReason'
                WHERE id=$idOrder";
        $query = $database->query($sql);

        if($database->affectedRows() > 0){
            $data['messages'][] = [
                'code' => 'success',
                'message' => $successMessage
            ];
        }else{
            $data['messages'][] = [
                'code' => 'warning',
                'message' => 'ACCEPTANCE_NOT_UPDATED'
            ];
        }

        return $data;
    }

    /**
     * upload customer acceptance document
     * @param  INT $idOrder   id for the order
     * @param  FILE $file     file to be uploaded
     * @return Array          upload status
     */
    public function uploadAcceptanceDocument($idOrder, $file){
        global $database, $user;
        $orderExtraActions = new orderExtraActions();
        $idOrder = $database->escapeValue($idOrder);

        $fileManager = new FileManager();

        $sql = "SELECT MAX(d.id)+1 AS maxIdDocument
                FROM ".TABLES['documents']." d";
        $maxId = $database->fetchResultArray($sql);
        $maxIdDocument = $maxId && $maxId[0] && $maxId[0]['maxIdDocument'] ? $maxId[0]['maxIdDocument'] : 1;

        $sql = "SELECT o.orderNumber
                FROM orders o
                WHERE id=$idOrder";
        $query = $database->query($sql);
        $row = $database->fetchArray($query);
        $documentName = 'customerAcceptance_'.$row['orderNumber'].'_' . $maxIdDocument;
        $uploadedBy = $user->getUserId();
        $data = $fileManager->uploadFile($file, $orderExtraActions::DOCUMENT_TYPES['ID_ACCEPTANCE_DOC_TYPE'], $documentName, $uploadedBy);

        if(isset($data['messages'])){
            return $data;
        }

        $idDocument = $data['idDocument'];
        $sql = "INSERT INTO ".TABLES['rel_order_documents']."
                (idOrder, idDocument, validation)
                VALUES($idOrder, $idDocument, 'not-validated')";
        $query = $database->query($sql);

        if($database->affectedRows() > 0){
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'FILE_UPLOADED'
            ];
        }else{
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'NOT_LINKED_TO_ORDER'
            ];
        }

        return $data;
    }
}
