<?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;
}

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

use includes\classes\ConnectPDO;

$conn = ConnectPDO::getInstance();

$post = $_POST;


$screenNotification = "";
$exception = "";
$data = [];
$data['success'] = true;
$data['message'] = "";
$data['cod'] = (isset($post['cod']) ? intval($post['cod']) : "");
$data['action'] = $post['action'];

$data['cep_mask'] = "^\d{5}-\d{3}$";

if (!isset($data['action']) || empty($data['action'])) {
    $data['success'] = false; 
    $data['message'] = message('warning', '', TRANS('SOME_ERROR_DONT_PROCEED'), '');
    echo json_encode($data);
    return false;
}


$data['field_id'] = "";


$data['company_name'] = (isset($post['company_name']) ? noHtml($post['company_name']) : "");
$data['contact_name'] = (isset($post['contact_name']) ? noHtml($post['contact_name']) : "");
$data['contact_email'] = (isset($post['contact_email']) ? noHtml($post['contact_email']) : "");
$data['contact_phone'] = (isset($post['contact_phone']) ? noHtml($post['contact_phone']) : "");
$data['doc_type'] = (isset($post['doc_type']) ? noHtml($post['doc_type']) : "");
$data['document_number'] = (isset($post['document_number']) ? noHtml($post['document_number']) : "");
$data['contract_number'] = (isset($post['contract_number']) ? noHtml($post['contract_number']) : "");

$data['city_registration'] = (isset($post['city_registration']) ? noHtml($post['city_registration']) : "");
$data['state_registration'] = (isset($post['state_registration']) ? noHtml($post['state_registration']) : "");

$data['addr_cep'] = (isset($post['unit_cep']) && !empty($post['unit_cep']) ? noHtml($post['unit_cep']) : "");
$data['addr_street'] = (isset($post['unit_street']) && !empty($post['unit_street']) ? noHtml($post['unit_street']) : "");
$data['addr_neighborhood'] = (isset($post['unit_neighborhood']) && !empty($post['unit_neighborhood']) ? noHtml($post['unit_neighborhood']) : "");
$data['addr_city'] = (isset($post['unit_city']) && !empty($post['unit_city']) ? noHtml($post['unit_city']) : "");
$data['addr_uf'] = (isset($post['unit_state']) && !empty($post['unit_state']) ? noHtml($post['unit_state']) : "");
$data['addr_number'] = (isset($post['unit_address_number']) && !empty($post['unit_address_number']) ? noHtml($post['unit_address_number']) : "");
$data['addr_complement'] = (isset($post['unit_address_complement']) && !empty($post['unit_address_complement']) ? noHtml($post['unit_address_complement']) : "");

$data['observation'] = (isset($post['observation']) && !empty($post['observation']) ? noHtml($post['observation']) : "");
$data['active'] = (isset($post['contractor_active']) ? ($post['contractor_active'] == "yes" ? 1 : 0) : 0);



/* Chaves Definidas na tipagem no banco de dados */
$maskTypes = array(
    'cnpj' => '\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}',
    'cpf' => '\d{3}\-\d{2}',
    'outro' => ''
);


/* Validações */
if ($data['action'] == "new" || $data['action'] == "edit") {

    
    if (empty($data['contact_name'])) {
        $data['success'] = false; 
        $data['field_id'] = "contact_name";
    } elseif (empty($data['company_name'])) {
        $data['success'] = false; 
        $data['field_id'] = "company_name";
    }
    
    if (!$data['success']) {
        $data['message'] = message('warning', 'Ooops!', TRANS('MSG_EMPTY_DATA'),'');
        echo json_encode($data);
        return false;
    }
    

    if (!empty($data['doc_type']) && !empty($data['document_number'])) {
        if (!preg_match('/' . $maskTypes[$data['doc_type']] . '/i', $data['document_number'])) {
            $data['success'] = false; 
            $data['field_id'] = 'document_number';
            $data['message'] = message('warning', '', TRANS('BAD_FIELD_FORMAT'), '');
            echo json_encode($data);
            return false;
        }
    }

    
    if (!filter_var($data['contact_email'], FILTER_VALIDATE_EMAIL)) {
        $data['success'] = false; 
        $data['field_id'] = "contact_email";
        $data['message'] = message('warning', '', TRANS('WRONG_FORMATTED_URL'), '');
        echo json_encode($data);
        return false;
    }

    if (!empty($data['addr_cep']) && !preg_match('/' . $data['cep_mask'] . '/i', (string)$data['addr_cep'])) {
        $data['success'] = false; 
        $data['field_id'] = "unit_cep";
    
        $data['message'] = message('warning', 'Ooops!', TRANS('BAD_FIELD_FORMAT'),'');
        echo json_encode($data);
        return false;
    }

}

$data['addr_cep'] = (!empty($data['addr_cep']) ? str_replace("-", "", $data['addr_cep']) : "");


if ($data['action'] == 'new') {

    $sql = "SELECT id FROM contractors WHERE company_name = '" . $data['company_name'] . "' ";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $data['success'] = false; 
        $data['field_id'] = "company_name";
        $data['message'] = message('warning', '', TRANS('MSG_RECORD_EXISTS'), '');
        echo json_encode($data);
        return false;
    }


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

    $sql = "INSERT INTO 
                contractors 
                (
                    company_name,
                    document_type, 
                    document_value, 
                    contact_name,
                    contact_email,
                    contact_phone, 
                    state_registration, 
                    city_registration, 
                    contract_number, 
                    addr_cep,
                    addr_street,
                    addr_neighborhood,
                    addr_city,
                    addr_uf,
                    addr_number,
                    addr_complement,
                    observation,
                    `active`
                ) 
                VALUES 
                (
                    :company_name,
                    :doc_type, 
                    :document_number, 
                    :contact_name,
                    :contact_email,
                    :contact_phone, 
                    :state_registration, 
                    :city_registration, 
                    :contract_number, 
                    :addr_cep,
                    :addr_street,
                    :addr_neighborhood,
                    :addr_city,
                    :addr_uf,
                    :addr_number,
                    :addr_complement,
                    :observation,
                    :active
                )";
    try {

        $res = $conn->prepare($sql);
        $res->bindParam(':company_name', $data['company_name'], PDO::PARAM_STR);
        $res->bindParam(':doc_type', $data['doc_type'], PDO::PARAM_STR);
        $res->bindParam(':document_number', $data['document_number'], PDO::PARAM_STR);
        $res->bindParam(':contact_name', $data['contact_name'], PDO::PARAM_STR);
        $res->bindParam(':contact_email', $data['contact_email'], PDO::PARAM_STR);
        $res->bindParam(':contact_phone', $data['contact_phone'], PDO::PARAM_STR);
        $res->bindParam(':state_registration', $data['state_registration'], PDO::PARAM_STR);
        $res->bindParam(':city_registration', $data['city_registration'], PDO::PARAM_STR);
        $res->bindParam(':contract_number', $data['contract_number'], PDO::PARAM_STR);
        $res->bindParam(':addr_cep', $data['addr_cep'], PDO::PARAM_STR);
        $res->bindParam(':addr_street', $data['addr_street'], PDO::PARAM_STR);
        $res->bindParam(':addr_neighborhood', $data['addr_neighborhood'], PDO::PARAM_STR);
        $res->bindParam(':addr_city', $data['addr_city'], PDO::PARAM_STR);
        $res->bindParam(':addr_uf', $data['addr_uf'], PDO::PARAM_STR);
        $res->bindParam(':addr_number', $data['addr_number'], PDO::PARAM_STR);
        $res->bindParam(':addr_complement', $data['addr_complement'], PDO::PARAM_STR);
        $res->bindParam(':observation', $data['observation'], PDO::PARAM_STR);
        $res->bindParam(':active', $data['active'], PDO::PARAM_INT);
        $res->execute();
        $data['cod'] = $conn->lastInsertId();

        $data['success'] = true; 
        $data['message'] = TRANS('MSG_SUCCESS_INSERT');

        $_SESSION['flash'] = message('success', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return false;
    } catch (Exception $e) {
        $exception .= "<hr>" . $e->getMessage() . "<hr>" . $sql;
        $data['success'] = false; 
        $data['message'] = TRANS('MSG_ERR_SAVE_RECORD');
        $_SESSION['flash'] = message('danger', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return false;
    }

} elseif ($data['action'] == 'edit') {


    $sql = "SELECT id FROM contractors WHERE company_name = '" . $data['company_name'] . "' AND id <> '" . $data['cod'] . "' ";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $data['success'] = false; 
        $data['field_id'] = "company_name";
        $data['message'] = message('warning', '', TRANS('MSG_RECORD_EXISTS'), '');
        echo json_encode($data);
        return false;
    }


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


    $sql = "UPDATE contractors SET 
                company_name = :company_name, 
                document_type = :doc_type, 
                document_value = :document_number, 
                contact_name = :contact_name, 
                contact_email = :contact_email, 
                contact_phone = :contact_phone, 
                state_registration = :state_registration, 
                city_registration = :city_registration, 
                contract_number = :contract_number, 
                addr_cep = :addr_cep, 
                addr_street = :addr_street, 
                addr_neighborhood = :addr_neighborhood, 
                addr_city = :addr_city,  
                addr_uf = :addr_uf, 
                addr_number = :addr_number, 
                addr_complement = :addr_complement, 
                observation = :observation, 
                active = :active
            WHERE id = {$data['cod']}";


    try {

        $res = $conn->prepare($sql);
        $res->bindParam(':company_name', $data['company_name'], PDO::PARAM_STR);
        $res->bindParam(':doc_type', $data['doc_type'], PDO::PARAM_STR);
        $res->bindParam(':document_number', $data['document_number'], PDO::PARAM_STR);
        $res->bindParam(':contact_name', $data['contact_name'], PDO::PARAM_STR);
        $res->bindParam(':contact_email', $data['contact_email'], PDO::PARAM_STR);
        $res->bindParam(':contact_phone', $data['contact_phone'], PDO::PARAM_STR);
        $res->bindParam(':state_registration', $data['state_registration'], PDO::PARAM_STR);
        $res->bindParam(':city_registration', $data['city_registration'], PDO::PARAM_STR);
        $res->bindParam(':contract_number', $data['contract_number'], PDO::PARAM_STR);
        $res->bindParam(':addr_cep', $data['addr_cep'], PDO::PARAM_STR);
        $res->bindParam(':addr_street', $data['addr_street'], PDO::PARAM_STR);
        $res->bindParam(':addr_neighborhood', $data['addr_neighborhood'], PDO::PARAM_STR);
        $res->bindParam(':addr_city', $data['addr_city'], PDO::PARAM_STR);
        $res->bindParam(':addr_uf', $data['addr_uf'], PDO::PARAM_STR);
        $res->bindParam(':addr_number', $data['addr_number'], PDO::PARAM_STR);
        $res->bindParam(':addr_complement', $data['addr_complement'], PDO::PARAM_STR);
        $res->bindParam(':observation', $data['observation'], PDO::PARAM_STR);
        $res->bindParam(':active', $data['active'], PDO::PARAM_INT);
        $res->execute();

        $data['success'] = true; 
        $data['message'] = TRANS('MSG_SUCCESS_EDIT');

        $_SESSION['flash'] = message('success', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return false;
    } catch (Exception $e) {
        $exception .= "<hr>" . $e->getMessage() . "<hr>" . $sql;
        $data['success'] = false; 
        $data['message'] = TRANS('MSG_ERR_DATA_UPDATE');
        $_SESSION['flash'] = message('danger', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return false;
    }

} elseif ($data['action'] == 'delete') {


    /* Verificar que tipos de restrições podem existir para a exclusão do registro */
    /* Por exemplo: a existência de faturas emitidas */


    $sql = "SELECT id FROM invoices WHERE contractor_id = '" . $data['cod'] . "' ";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $data['success'] = false; 
        $data['message'] = TRANS('MSG_CONTRACTOR_HAS_INVOICES');
        $_SESSION['flash'] = message('danger', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return false;
    }


    /* Sem restrições para excluir o cliente */
    $sql = "DELETE FROM contractors WHERE id = '" . $data['cod'] . "'";

    try {
        $conn->exec($sql);
        $data['success'] = true; 
        $data['message'] = TRANS('OK_DEL');


        $_SESSION['flash'] = message('success', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return true;
    } catch (Exception $e) {
        $exception .= "<hr>" . $e->getMessage() . "<hr>" . $sql;
        $data['success'] = false; 
        $data['message'] = TRANS('MSG_ERR_DATA_REMOVE');
        $_SESSION['flash'] = message('danger', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return false;
    }
    
}

echo json_encode($data);