<?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'];

$defaultSunEditorEmpty = '<p><br></p>';


$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']);

$data['start_due_date'] = (isset($post['start_due_date_hidden']) && !empty($post['start_due_date_hidden']) ? $post['start_due_date_hidden'] : '');
$data['end_due_date'] = (isset($post['end_due_date_hidden']) && !empty($post['end_due_date_hidden']) ? $post['end_due_date_hidden'] : '');

$data['extra_text'] = (isset($post['extra_text']) && !empty($post['extra_text']) && ($post['extra_text'] != $defaultSunEditorEmpty) ? $post['extra_text'] : '');


$data['mailing_list'] = (isset($post['mailing_list']) && !empty($post['mailing_list']) ? (int)$post['mailing_list'] : '');

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

if (empty($data['start_due_date']) || empty($data['end_due_date'])) {
    $data['success'] = false;
    $data['message'] = message('warning', 'Ooops!', TRANS('MSG_PERIOD_NEED_TO_SEND_TO_PAYMENT'),'');
    echo json_encode($data);
    return false;
    
}

if (empty($data['mailing_list'])) {
    $data['success'] = false;
    $data['field_id'] = 'mailing_list';
    $data['message'] = message('warning', 'Ooops!', TRANS('MSG_EMPTY_DATA'),'');
    echo json_encode($data);
    return false;
    
}
// var_dump($post); exit;


$mailingInfo = getMailingLists($conn, $data['mailing_list']);
if (empty($mailingInfo)) {
    $data['success'] = false;
    $data['message'] = message('warning', 'Ooops!', TRANS('SOME_ERROR_DONT_PROCEED') . $exception,'');
    echo json_encode($data);
    return false;
}

$textAddressTo = $mailingInfo['ml_addr_to'];
$textAddressCC = $mailingInfo['ml_addr_cc'];


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


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

$data['cant_be_send'] = [];
$data['reason'] = [];
$VARS = [];


$mailTableTdStyle = 'align="center" bgcolor="#dcdcdc" width="300" height="35" style="font-family:Arial;"
';
$defaultVars = [
    '%tabelas_para_pagamento%'
];





$allInvoicesData = [];

/* Realizar o envio dos documentos de cada fatura/solicitação de pagamento ao respectivo prestador */
foreach ($data['invoices_to_send'] as $invoice) {
    
    /* Separar as tabelas de acordo com o demandante */
    

    $invoiceData = getInvoiceById($conn, $invoice);
    if (empty($invoiceData)) {
        $data['cant_be_send'][] = $invoice;
        continue;
    }
    unset($invoiceData['file']);

    $allInvoicesData[] = $invoiceData;

    
}

// var_dump($allInvoicesData);


// Passo 1: Separar o array por contractor_organization
$separatedArrays = [];

foreach ($allInvoicesData as $item) {
    
    /* Se não tiver contratante definido, recebe 0 */
    $contractorOrganization = (!empty($item['contractor_organization']) ? $item['contractor_organization'] : 0);
    
    if (!isset($separatedArrays[$contractorOrganization])) {
        $separatedArrays[$contractorOrganization] = [];
    }
    
    $separatedArrays[$contractorOrganization][] = $item;
}

// Passo 2: Ordenar cada array resultante por company_name
foreach ($separatedArrays as &$array) {
    usort($array, function($a, $b) {
        return strcmp($a['company_name'], $b['company_name']);
    });
}


// var_dump($separatedArrays);

$totals = [];
$arrayTables = [];
foreach ($separatedArrays as $contractorOrganization => $arrayInvoices) {
    $table = '';
    // var_dump([
    //     'count organizations' => count($separatedArrays),
    //     'contractorOrganization' => $contractorOrganization,
    //     'dados' => $arrayInvoices
    // ]);

    $contractorOrganizationName = (!empty($contractorOrganization) && $contractorOrganization != 0 ? getContractorsOrganizations($conn, $contractorOrganization)['name'] : TRANS('MSG_NOT_DEFINED'));

    // $table = "<h3>{$contractorOrganizationName} - Total: %total_{$contractorOrganization}%</h3>";
    
    
    $table .= '<table border="1" style="border-collapse:collapse;">';
    $table .= '<thead>';
    $table .= '<tr>';
    $table .= '<td colspan="4" ' . $mailTableTdStyle . '><b>' . $contractorOrganizationName . ' - Total: %total_' . $contractorOrganization .'%</b></td>';
    $table .= '</tr>';
    $table .= '<tr>';
    $table .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('PIX_KEY') . '</b></td>';
    $table .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('DEMAND') . '</b></td>';
    $table .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('CONTRACTOR') . '</b></td>';
    $table .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('TOTAL') . ' (' . TRANS('CURRENCY') . ')</b></td>';
    $table .= '</tr>';
    $table .= '</thead>';
    
    $table .= '<tbody>';

    $organizationTotal = 0;
    
    foreach ($arrayInvoices as $invoiceData) {

        $organizationTotal += $invoiceData['total_price'];
        $totals[$contractorOrganization] = $organizationTotal;
        
        $serviceTypeName = (!empty($invoiceData['service_type']) && $invoiceData['service_type'] != 0 ? getContractorsServicesTypes($conn, $invoiceData['service_type'])['name'] : TRANS('MSG_NOT_DEFINED'));

        $table .= '<tr>';
        $table .= '<td ' . $mailTableTdStyle . '>' . mb_strtoupper($invoiceData['document_type']) . ' ' . $invoiceData['document_value'] . '</td>';
        $table .= '<td ' . $mailTableTdStyle . '>' . $serviceTypeName . '</td>';
        $table .= '<td ' . $mailTableTdStyle . '>' . $invoiceData['company_name'] . '</td>';
        $table .= '<td ' . $mailTableTdStyle . '>' . priceScreen($invoiceData['total_price']) . '</td>';
        $table .= '</tr>';
    }

    $table .= '<tr>';
    $table .= '<td colspan="3" ' . $mailTableTdStyle . '><b>' . TRANS('TOTAL') . ' (' . TRANS('CURRENCY') . ')</b></td>';
    $table .= '<td ' . $mailTableTdStyle . '>%total_' . $contractorOrganization .'%</td>';
    $table .= '</tr>';
    
    $table .= '</tbody>';
    $table .= "</table>";
    $arrayTables[] = $table;
}

// dump($arrayTables);
// var_dump($totals);


/* Variáveis com os totais para serem injetadas no título de cada tabela */
$VARS_TOTAIS = [];
$total_price = 0;
foreach ($totals as $contractorOrganization => $total) {
    $total_price += $total;
    $VARS_TOTAIS['%total_' . $contractorOrganization . '%'] = priceScreen($total);
}

$tables = implode('<br />', $arrayTables);


$VARS['%periodo_inicio_vencimento%'] = $data['start_due_date'];
$VARS['%periodo_fim_vencimento%'] = $data['end_due_date'];
$VARS['%total_geral%'] = priceScreen($total_price);
$VARS['%tabelas_para_pagamento%'] = transvars($tables, $VARS_TOTAIS);

// dump($VARS['%tabelas_para_pagamento%']); exit;

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


if (!empty($textAddressCC)) {
    $CCs = explode(',', $textAddressCC);
    foreach ($CCs as $CC) {
        $mail->addCCAddresses($CC);
    }
}


/* 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();
}

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

/* Marcar a fatura como enviada */
foreach ($data['invoices_to_send'] as $invoice) {
    setInvoiceSentToPaying($conn, $invoice);
}

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