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

// var_dump($post); exit;

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

$readonlyID = 1;

if ($data['cod'] == $readonlyID) {
    $data['success'] = false; 
    $data['field_id'] = "action";
    $data['message'] = message('warning', 'Ooops!', TRANS('MSG_UNABLE_TO_EDIT_INVOICE_MODEL'),'');
    echo json_encode($data);
    return false;
}

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


$data['field_id'] = "";

$data['model_name'] = (isset($post['model_name']) && !empty($post['model_name']) ? noHtml($post['model_name']) : "");
$data['description'] = (isset($post['description']) && !empty($post['description']) ? noHtml($post['description']) : "");
$data['html_content'] = (isset($post['html_content']) && !empty($post['html_content']) ? noHtml($post['html_content']) : "");


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

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

    if (empty($data['html_content'])) {
        $data['success'] = false; 
        $data['field_id'] = "html_content";
        $data['message'] = message('warning', 'Ooops!', TRANS('MSG_EMPTY_DATA'),'');
        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;
    }


    /* Checa se já existe um modelo de fatura com o mesmo nome */
    $sql = "SELECT id FROM invoice_models WHERE name = '" . $data['model_name'] . "' ";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $data['success'] = false; 
        $data['field_id'] = "model_name";
        $data['message'] = message('warning', '', TRANS('MSG_RECORD_EXISTS'), '');
        echo json_encode($data);
        return false;
    }


    $sql = "INSERT INTO
            invoice_models (
                name,
                description,
                html_content
            ) VALUES (
                :model_name,
                :description,
                :html_content
            )";


    try {
        $res = $conn->prepare($sql);
        $res->bindParam(':model_name', $data['model_name'], PDO::PARAM_STR);
        $res->bindParam(':description', $data['description'], PDO::PARAM_STR);
        $res->bindParam(':html_content', $data['html_content'], PDO::PARAM_STR);
        $res->execute();

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

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

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

    if (empty($data['html_content'])) {
        $data['success'] = false; 
        $data['field_id'] = "html_content";
        $data['message'] = message('warning', 'Ooops!', TRANS('MSG_EMPTY_DATA'),'');
        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;
    }


    /* Checa se já existe um modelo de fatura com o mesmo nome */
    $sql = "SELECT id FROM invoice_models WHERE name = '" . $data['model_name'] . "' AND id != '" . $data['cod'] . "' ";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $data['success'] = false; 
        $data['field_id'] = "model_name";
        $data['message'] = message('warning', '', TRANS('MSG_RECORD_EXISTS'), '');
        echo json_encode($data);
        return false;
    }


    $sql = "UPDATE invoice_models SET 
                name = :model_name,
                description = :description,
                html_content = :html_content
            WHERE id = {$data['cod']}";

    try {
        $res = $conn->prepare($sql);
        $res->bindParam(':model_name', $data['model_name'], PDO::PARAM_STR);
        $res->bindParam(':description', $data['description'], PDO::PARAM_STR);
        $res->bindParam(':html_content', $data['html_content'], PDO::PARAM_STR);
        $res->execute();
        
        $data['success'] = true; 
        $data['message'] = TRANS('MSG_SUCCESS_EDIT');
        $_SESSION['flash'] = message('success', '', $data['message'], '');
        echo json_encode($data);
        return false;
    } catch (Exception $e) {
        $exception .= "<hr>" . $e->getMessage();
        $data['success'] = false; 
        $data['message'] = TRANS('MSG_ERR_DATA_UPDATE') . $exception;
        $_SESSION['flash'] = message('danger', '', $data['message'], '');
        echo json_encode($data);
        return false;
    }

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

    /* Confere se não é formulário padrão do sistema */
    // if (in_array($data['cod'], $system_defaults_ids)) {
    //     $data['success'] = false; 
    //     $data['message'] = TRANS('MSG_CANT_DEL_SYSTEM_REGISTER');
    //     $_SESSION['flash'] = message('danger', '', $data['message'] . $exception, '');
    //     echo json_encode($data);
    //     return false;
    // }


    $sql = "DELETE FROM invoice_models WHERE id = '" . $data['cod'] . "'";
    try {
        $conn->exec($sql);
        $data['success'] = true; 
        $data['message'] = TRANS('OK_DEL');
        $_SESSION['flash'] = message('success', '', $data['message'], '');
        echo json_encode($data);
        return false;
    } catch (Exception $e) {
        $exception .= "<hr>" . $e->getMessage();
        $data['success'] = false; 
        $data['message'] = TRANS('MSG_ERR_DATA_REMOVE') . $exception;
        $_SESSION['flash'] = message('danger', '', $data['message'], '');
        echo json_encode($data);
        return false;
    }

}

echo json_encode($data);