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

$now = date('Y-m-d H:i:s');
$exception = "";
$screenNotification = "";
$data = [];
$data['success'] = true;
$data['message'] = "";
$data['cod'] = (isset($post['cod']) ? intval($post['cod']) : "");
$data['action'] = $post['action'];
$data['csrf_session_key'] = (isset($post['csrf_session_key']) ? $post['csrf_session_key'] : "");
$data['field_id'] = "";
// $data['currency_mask'] = "([1-9]\d{0,2}(\.\d{3})*(\,\d{2}))|(\0(\,\d{2}))";
$data['currency_mask'] = "([1-9]\d{0,2}(\.\d{3})*(\,\d{2}))|(\x00(\,\d{2}))";
$data['currency_mask'] = str_replace("\0", '', $data['currency_mask']);

$data['tech_level_name'] = (isset($post['tech_level_name']) ? noHtml($post['tech_level_name']) : "");
$data['tech_level_description'] = (isset($post['tech_level_description']) ? noHtml($post['tech_level_description']) : null);
$data['tech_base_price'] = (isset($post['tech_base_price']) ? noHtml($post['tech_base_price']) : 1);
$data['hour_price_divisor'] = (isset($post['hour_price_divisor']) ? (int)$post['hour_price_divisor'] : 1);
$data['unit_price_divisor'] = (isset($post['unit_price_divisor']) ? (int)$post['unit_price_divisor'] : 1);




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

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

    $data['tech_base_price'] = priceDB($data['tech_base_price']);

    if ($data['hour_price_divisor'] < 1) {
        $data['success'] = false; 
        $data['field_id'] = "hour_price_divisor";
        $data['message'] = message('warning', 'Ooops!', TRANS('MSG_WRONG_HOUR_PRICE_DIVISOR'),'');
        echo json_encode($data);
        return false;
    }
    if ($data['unit_price_divisor'] < 1) {
        $data['success'] = false; 
        $data['field_id'] = "unit_price_divisor";
        $data['message'] = message('warning', 'Ooops!', TRANS('MSG_WRONG_HOUR_PRICE_DIVISOR'),'');
        echo json_encode($data);
        return false;
    }
    
    if (empty($data['tech_base_price'])) {
        $data['success'] = false; 
        $data['field_id'] = "tech_base_price";
    }
    
    if (empty($data['tech_level_name'])) {
        $data['success'] = false; 
        $data['field_id'] = "tech_level_name";
    }


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

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

    /* verifica se um registro com esse nome já existe */
    $sql = "SELECT id FROM tech_levels WHERE name = '{$data['tech_level_name']}' ";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $data['success'] = false; 
        $data['field_id'] = "tech_level_name";
        $data['message'] = message('warning', '', TRANS('MSG_RECORD_EXISTS'), '');
        echo json_encode($data);
        return false;
    }


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

    $sql = "INSERT INTO tech_levels 
        (
            `name`, 
            `description`
        ) 
        VALUES 
        (
            :name,
            :description
        )";

    try {
        $res = $conn->prepare($sql);
        $res->bindValue(':name', $data['tech_level_name'], PDO::PARAM_STR);
        $res->bindValue(':description', $data['tech_level_description'], PDO::PARAM_STR);
        $res->execute();

        $data['cod'] = $conn->lastInsertId();

        $sql = "INSERT 
                INTO 
                    tech_prices
                (
                    `tech_level_id`, 
                    `base_price`, 
                    `hour_price_divisor`,
                    `unit_price_divisor`,
                    `author`
                ) 
                VALUES 
                (
                    :tech_level_id,
                    :base_price,
                    :hour_price_divisor,
                    :unit_price_divisor,
                    :author 
                )
        ";
        try {
            $res = $conn->prepare($sql);
            $res->bindValue(':tech_level_id', $data['cod'], PDO::PARAM_INT);
            $res->bindValue(':base_price', $data['tech_base_price'], PDO::PARAM_STR);
            $res->bindValue(':hour_price_divisor', $data['hour_price_divisor'], PDO::PARAM_INT);
            $res->bindValue(':unit_price_divisor', $data['unit_price_divisor'], PDO::PARAM_INT);
            $res->bindValue(':author', $_SESSION['s_uid'], PDO::PARAM_INT);
            $res->execute();
            
        } catch (Exception $e) {
            $exception .= "<hr>" . $e->getMessage();
        }


        $data['success'] = true; 
        $data['message'] = TRANS('MSG_SUCCESS_INSERT') . $exception;
        $_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_SAVE_RECORD') . $exception . "<hr>" . $sql;
        $_SESSION['flash'] = message('danger', '', $data['message'], '');
        echo json_encode($data);
        return false;
    }

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

    

    /* verifica se um registro com esse nome já existe para outro código do mesmo cliente */
    $sql = "SELECT id FROM tech_levels WHERE `name` = '{$data['tech_level_name']}' AND id <> {$data['cod']}";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $data['success'] = false; 
        $data['field_id'] = "tech_level_name";
        $data['message'] = message('warning', '', TRANS('MSG_RECORD_EXISTS'), '');
        echo json_encode($data);
        return false;
    }


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

    $oldBasePrice = $data['tech_base_price'];
    $oldHourPriceDivisor = $data['hour_price_divisor'];
    $oldUnitPriceDivisor = $data['unit_price_divisor'];
    $idToSetVigenceTo = '';
    $sql = "SELECT 
                id,
                base_price, 
                hour_price_divisor,
                unit_price_divisor 
            FROM 
                tech_prices 
            WHERE 
                tech_level_id = {$data['cod']} AND 
                id = (SELECT MAX(id) FROM tech_prices WHERE tech_level_id = {$data['cod']})
                ";
    $res = $conn->query($sql);
    if ($res->rowCount()) {
        $row = $res->fetch();
        $idToSetVigenceTo = $row['id'];
        $oldBasePrice = $row['base_price'];
        $oldHourPriceDivisor = $row['hour_price_divisor'];
        $oldUnitPriceDivisor = $row['unit_price_divisor'];
    }

    $sql = "UPDATE tech_levels SET 
				`name` = :name,
                `description` = :description
            WHERE id = {$data['cod']}";
    try {

        $res = $conn->prepare($sql);
        $res->bindValue(':name', $data['tech_level_name'], PDO::PARAM_STR);
        $res->bindValue(':description', $data['tech_level_description'], PDO::PARAM_STR);
        $res->execute();
        
        /* Caso exista alteração de valores de precos então atualizo campo vigence_until e insiro novo registro */
        if ($oldBasePrice != $data['tech_base_price'] || $oldHourPriceDivisor != $data['hour_price_divisor'] || $oldUnitPriceDivisor != $data['unit_price_divisor']) {
            
            $sql = "UPDATE tech_prices SET 
                        `vigence_until` = :vigence_until
                    WHERE id = {$idToSetVigenceTo}
                    ";
            try {
                $res = $conn->prepare($sql);
                $res->bindValue(':vigence_until', $now, PDO::PARAM_STR);
                $res->execute();
            } catch (Exception $e) {
                $exception .= "<hr>" . $e->getMessage();
            }
            
            
            $sql = "INSERT
                INTO
                    tech_prices
                (
                    `tech_level_id`, 
                    `base_price`, 
                    `hour_price_divisor`,
                    `unit_price_divisor`,
                    `author`
                )
                VALUES
                (
                    :tech_level_id,
                    :base_price,
                    :hour_price_divisor,
                    :unit_price_divisor,
                    :author
                )
            ";
            try {
                $res = $conn->prepare($sql);
                $res->bindValue(':tech_level_id', $data['cod'], PDO::PARAM_INT);
                $res->bindValue(':base_price', $data['tech_base_price'], PDO::PARAM_STR);
                $res->bindValue(':hour_price_divisor', $data['hour_price_divisor'], PDO::PARAM_INT);
                $res->bindValue(':unit_price_divisor', $data['unit_price_divisor'], PDO::PARAM_INT);
                $res->bindValue(':author', $_SESSION['s_uid'], PDO::PARAM_INT);
                $res->execute();
            } catch (Exception $e) {
                $exception .= "<hr>" . $e->getMessage();
            }
        }
        
        
        $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() . "<hr>" . $sql;
        $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') {


    $sqlFindPrevention = "SELECT prob_id FROM problemas WHERE tech_level = {$data['cod']} ";
    $resFindPrevention = $conn->query($sqlFindPrevention);
    $foundPrevention = $resFindPrevention->rowCount();

    if ($foundPrevention) {
        $data['success'] = false; 
        $data['message'] = TRANS('MSG_CANT_DEL');
        $data['message'] = message('danger', '', $data['message'], '');
        // $_SESSION['flash'] = message('danger', '', $data['message'], '');
        echo json_encode($data);
        return false;
    }


    $sql = "DELETE FROM tech_levels WHERE id = '" . $data['cod'] . "'";

    try {
        $conn->exec($sql);


        $sql = "DELETE FROM tech_prices WHERE tech_level_id = '" . $data['cod'] . "'";
        $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');
        $_SESSION['flash'] = message('danger', '', $data['message'] . $exception, '');
        echo json_encode($data);
        return false;
    }
    
}

echo json_encode($data);