<?php session_start();
/*      Copyright 2023 Flávio Ribeiro

        This file is part of OCOMON.

        OCOMON is free software; you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation; either version 3 of the License, or
        (at your option) any later version.
        OCOMON is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with Foobar; if not, write to the Free Software
        Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

if (!isset($_SESSION['s_logado']) || $_SESSION['s_logado'] == 0) {
    $_SESSION['session_expired'] = 1;
    echo "<script>top.window.location = '../../index.php'</script>";
    exit;
}

if ($_SESSION['s_nivel'] != 1) {
    exit;
}

require_once __DIR__ . "/" . "../../includes/include_basics_only.php";
require_once __DIR__ . "/" . "../../includes/classes/ConnectPDO.php";

use OcomonApi\Support\Email;
use includes\classes\ConnectPDO;

$conn = ConnectPDO::getInstance();

$post = $_POST;

// var_dump($post); exit;

$exception = "";
$now = date('Y-m-d H:i:s');
$data = [];
$data['success'] = true;
$data['message'] = "";
$data['author'] = $_SESSION['s_uid'];

$successMsg = TRANS('MSG_INVOICES_SENT_TO_CONTRACTORS_QUEUE');


/* Para os casos do envio do documento logo após a geração da solicitação de pagamento */
if (isset($post['action']) && $post['action'] == "send_to_sigle_contractor") {
    $post['invoices_to_send'] = [$post['invoice_id']];
    $successMsg = TRANS('MSG_INVOICE_CREATED_AND_SENT_TO_CONTRACTOR_QUEUE');
}

/* Para os casos do envio do documento diretamente a partir da tela de geração */
if (isset($post['action']) && $post['action'] == "send_to_sigle_contractor_from_invoices") {
    $post['invoices_to_send'] = [$post['invoice_id']];
    $successMsg = TRANS('MSG_INVOICE_SENT_TO_CONTRACTOR_QUEUE');
}


$data['invoices_to_send'] = (isset($post['invoices_to_send']) ? array_map('intval', $post['invoices_to_send']) : []);
$data['invoices_to_send'] = array_filter($data['invoices_to_send']);


if (empty($data['invoices_to_send'])) {
    $data['success'] = false;
    $data['message'] = message('warning', '', TRANS('MSG_SOMETHING_GOT_WRONG'), '');
    
    echo json_encode($data);
    return false;
}

$invoicesCount = count($data['invoices_to_send']);


$mailSendMethod = 'queue';
$event = "invoice-to-contractor";
$eventTemplate = getEventMailConfig($conn, $event);

$data['cant_be_send'] = [];
$data['reason'] = [];
$VARS = [];
/* Realizar o envio dos documentos de cada fatura/solicitação de pagamento ao respectivo prestador */
foreach ($data['invoices_to_send'] as $invoice) {
    
    

    $invoiceData = getInvoiceById($conn, $invoice);

    if (empty($invoiceData)) {
        $data['cant_be_send'][] = $invoice;
        continue;
    }

    $VARS['%numero_solicitacao%'] = $invoiceData['invoice_number'];
    $VARS['%empresa_nome%'] = $invoiceData['company_name'];
    $VARS['%contato_nome%'] = $invoiceData['contact_name'];
    $VARS['%data_emissao%'] = dateScreen($invoiceData['issuance_date'],1);
    $VARS['%data_vencimento%'] = dateScreen($invoiceData['due_date'],1);
    $VARS['%valor_total%'] = priceScreen($invoiceData['total_price']);

    /**
     * 1. inserir o registro na fila de envio de e-mail
     */
    // continue;
    $mail = (new Email())->bootstrap(
        transvars($eventTemplate['msg_subject'], $VARS),
        transvars($eventTemplate['msg_body'], $VARS),
        $invoiceData['contact_email'],
        $eventTemplate['msg_fromname']
    );

    /* 2. Pegar o ID da fila de envio de e-mail e gravar junto às informações do arquivo a ser anexado em 'mail_queue_files' */
    $queueID = $mail->queue();
    if (!$queueID) {
        $mailNotification .= "<hr>" . TRANS('EMAIL_NOT_SENT') . "<hr>" . $mail->message()->getText();
        continue;
    }

    $setFileToMailQueue = setFileToMailQueue($conn, $invoiceData['file_id'], $queueID, []);
    if (!$setFileToMailQueue) {
        $data['cant_be_send'][] = $invoice;
        continue;
    }

    /* Marcar a fatura como enviada */
    setInvoiceSentToContractor($conn, $invoice);

}


$data['message'] = $successMsg;
$_SESSION['flash'] = message('success', '', $data['message'] . $exception, '');
echo json_encode($data);
return false;
