<?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
*/
require_once (__DIR__ . "/" . "../../includes/include_basics_only.php");
require_once (__DIR__ . "/" . "../../includes/classes/ConnectPDO.php");
use includes\classes\ConnectPDO;
use OcomonApi\Support\Email;


if ($_SESSION['s_logado'] != 1 || ($_SESSION['s_nivel'] != 1)) {
    return;
}

$conn = ConnectPDO::getInstance();

$post = $_POST;
$data = [];
$data['success'] = true;
$data['message'] = "";
$disabledUser = false;
$timestampKey = null;
$actionFlag = null;
$mailErrorNotification = '';
$mailSuccessNotification = '';
$successAddresses = [];
$failedAddresses = [];
$successDisabledUsers = [];
$failedDisabledUsers = [];
$dataVars = [];
$dataFiles = [];
$hasTableOfAssets = false;
$mailTableTdStyle = 'align="center" bgcolor="#dcdcdc" width="300" height="35" style="font-family:Arial;"
';

$data['action'] = $post['action'];

$data['csrf_session_key'] = (isset($post['csrf_session_key']) ? $post['csrf_session_key'] : "");

$defaultVars = [
    '%tabela_de_ativos%',
    '%nome_usuario%'
];


$data['template'] = (isset($post['selected_template']) && !empty($post['selected_template']) ? (int)$post['selected_template'] : "");
$data['users'] = (isset($post['user']) && !empty($post['user']) ? $post['user'] : []);
$data['business_emails'] = (isset($post['business_email']) && !empty($post['business_email']) ? $post['business_email'] : []);
$data['personal_emails'] = (isset($post['personal_email']) && !empty($post['personal_email']) ? $post['personal_email'] : []);
$data['disable_users'] = (isset($post['disable_users_value']) ? ($post['disable_users_value'] == "yes" ? true : false) : false);
$data['replies_open_ticket'] = (isset($post['replies_open_ticket_value']) ? ($post['replies_open_ticket_value'] == "yes" ? true : false) : false);


/* Validação dos endereços de e-mail */
foreach ($data['business_emails'] as $key => $businessEmail) {
    if (empty($businessEmail) && empty($data['personal_emails'][$key])) {
        $data['success'] = false;
        $data['field_id'] = "business_email_" . $key;
        $data['message'] = message('warning', '', TRANS('MSG_AT_LEAST_FILL_ONE_EMAIL'), '');
        echo json_encode($data);
        return false;
    }

    if (!empty($businessEmail) && !filter_var($businessEmail, FILTER_VALIDATE_EMAIL)) {
        $data['success'] = false;
        $data['field_id'] = "business_email_" . $key;
        $data['message'] = message('warning', '', TRANS('INVALID_EMAIL_FORMAT'), '');
        echo json_encode($data);
        return false;
    }

    if (!empty($data['personal_emails'][$key]) && !filter_var($data['personal_emails'][$key], FILTER_VALIDATE_EMAIL)) {
        $data['success'] = false;
        $data['field_id'] = "personal_email_" . $key;
        $data['message'] = message('warning', '', TRANS('INVALID_EMAIL_FORMAT'), '');
        echo json_encode($data);
        return false;
    }
}

/* Validação da variável 'nome_usuario' pois é obrigatória caso exista no template */
if (isset($post['nome_usuario'])) {
    foreach ($post['nome_usuario'] as $key => $value) {
        if (empty($value)) {
            $data['success'] = false;
            $data['field_id'] = 'nome_usuario_' . $key;
            $data['message'] = message('warning', '', TRANS('MSG_VAR_USERNAME_EMPTY'), '');
            echo json_encode($data);
            return false;
        }
    }
}

/* Endereços para cópia */
$copy_addresses = [];
if (isset($post['copy_to']) && !empty($post['copy_to'])) {

    foreach ($post['copy_to'] as $key => $value) {
        
        if (!empty($value)) {
            $copy_addresses[$key] = explode(',', $value);

            if (!empty($copy_addresses[$key])) {
                foreach ($copy_addresses[$key] as $keyCopy => $valueCopy) {
                    
                    if (!filter_var(trim($valueCopy), FILTER_VALIDATE_EMAIL)) {
                        $data['success'] = false;
                        $data['field_id'] = 'copy_to_' . $key;
                        $data['message'] = message('warning', '', TRANS('INVALID_EMAIL_FORMAT'), '');
                        echo json_encode($data);
                        return false;
                    }
                    
                    $copy_addresses[$key][$keyCopy] = trim($valueCopy);
                }
            }
        } 
    }
}


$templateInfo = getMailTemplates($conn, $data['template']);
if (empty($templateInfo)) {
    echo message('warning', 'Ooops!', TRANS('MSG_SELECT_TEMPLATE'), '');
    return false;
}
$htmlToParse = $templateInfo['tpl_msg_html'];
// Expressão regular para encontrar todas as variáveis (sem espaço) entre "%"
preg_match_all('/%([^%\s]+)%/', $htmlToParse, $matches);
// O array com as variáveis encontradas
$templateVars = array_unique($matches[1]);


foreach ($templateVars as $key => $field) {

    if ($field == 'tabela_de_ativos') {
        $hasTableOfAssets = true;
    }
    
    if (isset($post[$field])) {

        foreach ($post[$field] as $keyField => $valueField) {
            $dataVars[$keyField]['%'.$field . '%'] = $valueField;
        }
    }
}


$mailConfig = getMailConfig($conn);

/* Por ora, não será utilizada fila de e-mails */
$mailSendMethod = 'send';
// if ($mailConfig['mail_queue']) {
//     $mailSendMethod = 'queue';
// }



if (!csrf_verify($post, $data['csrf_session_key'])) {
    $data['success'] = false; 
    $data['message'] = message('warning', 'Ooops!', TRANS('FORM_ALREADY_SENT'),'');

    echo json_encode($data);
    return false;
}


$bodyMessage = '';
/* Processo montagem e envio dos e-mails */
foreach ($dataVars as $key => $value) {


    if ($data['replies_open_ticket']) {
        $timestampKey = time() . '_' . $key;
        $actionFlag = 'FIRST_REPLY_OPEN_TICKET';
    }


    if (!empty($data['users'][$key]) && $hasTableOfAssets) {

        $value['%tabela_de_ativos%'] = "";
        $user_assets = getAssetsFromUser($conn, $data['users'][$key]);
        $assets_info = [];
        if (!empty($user_assets)) {
            foreach ($user_assets as $asset) {
                $assets_info[] = getAssetBasicInfo($conn, $asset['asset_id']);
            }
            
            $mailTable = "";
            $mailTable .= '<table border="1" style="border-collapse:collapse;">';
            $mailTable .= '<thead>';
            $mailTable .= '<tr>';
            $mailTable .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('ASSET_TYPE') . '</b></td>';
            $mailTable .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('ASSET_TAG_TAG') . '</b></td>';
            $mailTable .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('COL_UNIT') . '</b></td>';
            $mailTable .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('CLIENT') . '</b></td>';
            $mailTable .= '<td ' . $mailTableTdStyle . '><b>' . TRANS('DEPARTMENT') . '</b></td>';
            $mailTable .= '</tr>';
            $mailTable .= '</thead>';

            $assets_info = arraySortByColumn($assets_info, 'tipo_nome', SORT_ASC);
        
            foreach ($assets_info as $asset) {
        
                $asset_description = $asset['tipo_nome'] . '&nbsp;' . $asset['fab_nome'] . '&nbsp;' . $asset['marc_nome'];
                /** Formatação para o email */
                $mailTable .= '<tr>';
                $mailTable .= '<td ' . $mailTableTdStyle . '>' . $asset_description . '</td>';
                $mailTable .= '<td ' . $mailTableTdStyle . '>' . $asset['comp_inv'] . '</td>';
                $mailTable .= '<td ' . $mailTableTdStyle . '>' . $asset['inst_nome'] . '</td>';
                $mailTable .= '<td ' . $mailTableTdStyle . '>' . $asset['cliente'] . '</td>';
                $mailTable .= '<td ' . $mailTableTdStyle . '>' . $asset['local'] . '</td>';
                $mailTable .= '</tr>';
            }
            $mailTable .= '</table>';

            $value['%tabela_de_ativos%'] = $mailTable;
        }
    }
    
    $addressTo_1 = $data['business_emails'][$key];
    $addressTo_2 = $data['personal_emails'][$key];
    
    $bodyMessage = str_replace(array_keys($value), array_values($value), $htmlToParse);

    /* Disparo do e-mail */
    if (!empty($addressTo_1)) {
        $mail = (new Email())->bootstrap(
            $templateInfo['tpl_subject'],
            $bodyMessage,
            $addressTo_1,
            $value['%nome_usuario%'],
            null,
            $actionFlag,
            $timestampKey
        );
        

        if (!empty($post['copy_to'][$key])) {
            $mail->addCCAddresses($post['copy_to'][$key]);
        }


        foreach ($_FILES['anexo_' . $key]['name'] as $keyFile => $valueFile) {

            if ($_FILES['anexo_' . $key]['name'][$keyFile] ) {
                $mail->attach($_FILES['anexo_' . $key]['tmp_name'][$keyFile], $_FILES['anexo_' . $key]['name'][$keyFile]);
            }
        }


        if (!$mail->{$mailSendMethod}()) {
            $failedAddresses[] = $addressTo_1;
            $mailErrorNotification .= "<hr>" . TRANS('EMAIL_NOT_SENT') . "<hr>" . $addressTo_1 . "<hr>" . $mail->message()->getText();
        } else {
            $successAddresses[] = $addressTo_1;
            /**
             * Desabilitar usuário;
             * Remover vínculos de ativos com o usuário;
             * Realocar ativos para o departamento definido em configuração
             */
            // if ($data['disable_users'] && !empty($data['users'][$key]) && !$disabledUser) {
            if ($data['disable_users'] && !empty($data['users'][$key])) {
                if (setUserDisabled($conn, $data['users'][$key], $_SESSION['s_uid'])) {
                    $successDisabledUsers[] = $data['users'][$key];
                } else {
                    $failedDisabledUsers[] = $data['users'][$key];
                }
            }

        }
    }

    if (!empty($addressTo_2)) {
        $mail = (new Email())->bootstrap(
            $templateInfo['tpl_subject'],
            $bodyMessage,
            $addressTo_2,
            $value['%nome_usuario%'],
            null,
            $actionFlag,
            $timestampKey
        );

        if (!empty($post['copy_to'][$key])) {
            $mail->addCCAddresses($post['copy_to'][$key]);
        }

        foreach ($_FILES['anexo_' . $key]['name'] as $keyFile => $valueFile) {

            if ($_FILES['anexo_' . $key]['name'][$keyFile] ) {
                $mail->attach($_FILES['anexo_' . $key]['tmp_name'][$keyFile], $_FILES['anexo_' . $key]['name'][$keyFile]);
            }
            
        }

        if (!$mail->{$mailSendMethod}()) {
            $failedAddresses[] = $addressTo_1;
            $mailErrorNotification .= "<hr>" . TRANS('EMAIL_NOT_SENT') . "<hr>" . $addressTo_2 . "<hr>" . $mail->message()->getText();
        } else {
            $successAddresses[] = $addressTo_2;

            /* Pode acontecer do usuário estar selecionado mas o e-mail só ser enviado para o endereço pessoal */
            if ($data['disable_users'] && !empty($data['users'][$key])) {
                if (setUserDisabled($conn, $data['users'][$key], $_SESSION['s_uid'])) {
                    $successDisabledUsers[] = $data['users'][$key];
                } else {
                    $failedDisabledUsers[] = $data['users'][$key];
                }
            }
        }
    }
} /* Fim do loop de envio de e-mails */


if (!empty($failedAddresses)) {
    $data['success'] = false;
    $data['message'] = message('warning', 'Ooops!', TRANS('MSG_SOMETHING_WENT_WRONG') . $mailErrorNotification, '');
    echo json_encode($data);
    return false;
}

$data['success'] = true;
$msgAffectedAddresses = "<hr/>" . TRANS('MSG_AFFECTED_ADDRESSES') .":";
$sentAddressesList = "<hr/>" . implode('<hr/>', $successAddresses);
$data['message'] = message('success', 'Yeah!', TRANS('MSG_ALL_MESSAGES_SENT') . $msgAffectedAddresses . $sentAddressesList, '', '', true);
echo json_encode($data);
return true;

