<?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();
$exception = "";
$criteria = [];
$criteriaText = "";
$data = [];
$data['success'] = true;
$data['message'] = "";
$data['total'] = 0;
$terms = "";
$termsTotal = "";



$post = $_POST;


$data['contractor'] = (isset($post['contractor']) && !empty($post['contractor']) ? (int)$post['contractor'] : "");
$data['start_issuance_date'] = (isset($post['start_issuance_date']) && !empty($post['start_issuance_date']) && isValidDate($post['start_issuance_date']) ? dateDB($post['start_issuance_date']) : '');
$data['end_issuance_date'] = (isset($post['end_issuance_date']) && !empty($post['end_issuance_date']) && isValidDate($post['end_issuance_date']) ? dateDB($post['end_issuance_date']) : '');
$data['start_due_date'] = (isset($post['start_due_date']) && !empty($post['start_due_date']) && isValidDate($post['start_due_date']) ? dateDB($post['start_due_date']) : '');
$data['end_due_date'] = (isset($post['end_due_date']) && !empty($post['end_due_date']) && isValidDate($post['end_due_date']) ? dateDB($post['end_due_date']) : '');

// var_dump($post);
// var_dump($data);

$search_keys = [
    'contractor',
    'start_issuance_date',
    'end_issuance_date',
    'start_due_date',
    'end_due_date'
];


$at_least_one = false;
foreach ($search_keys as $key) {
    if (!empty($data[$key])) {
        $at_least_one = true;
        break;
    }
}

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

$terms = "";

if (!empty($data['contractor'])) {
    $terms .= " AND i.contractor_id = :contractor";
}

if (!empty($data['start_issuance_date'])) {
    $terms .= " AND i.issuance_date >= :start_issuance_date";
}

if (!empty($data['end_issuance_date'])) {
    $terms .= " AND i.issuance_date <= :end_issuance_date";
}

if (!empty($data['start_due_date'])) {
    $terms .= " AND i.due_date >= :start_due_date";
}

if (!empty($data['end_due_date'])) {
    $terms .= " AND i.due_date <= :end_due_date";
}

$sql = "SELECT 

    i.id as invoice_id,
    i.invoice_number,
    i.issuance_date,
    i.due_date,
    i.contractor_id,
    i.total_price,

    f.id as file_id,
    f.filename, f.mime_type, f.file_size, 
    c.company_name 
FROM 
    invoices i, 
    invoice_files f,
    contractors c
WHERE
    i.id = f.invoice_id AND
    i.contractor_id = c.id
    {$terms}
    ";

try {
    $res = $conn->prepare($sql);

    if (!empty($data['contractor'])) {
        $res->bindParam(':contractor', $data['contractor'], PDO::PARAM_INT);
    }

    if (!empty($data['start_issuance_date'])) {
        $res->bindParam(':start_issuance_date', $data['start_issuance_date'], PDO::PARAM_STR);
    }

    if (!empty($data['end_issuance_date'])) {
        $res->bindParam(':end_issuance_date', $data['end_issuance_date'], PDO::PARAM_STR);
    }

    if (!empty($data['start_due_date'])) {
        $res->bindParam(':start_due_date', $data['start_due_date'], PDO::PARAM_STR);
    }

    if (!empty($data['end_due_date'])) {
        $res->bindParam(':end_due_date', $data['end_due_date'], PDO::PARAM_STR);
    }
    
    $res->execute();
    if ($res->rowCount()) {
        $data['invoices'] = $res->fetchAll();
    }
    $data['success'] = true;

} catch (PDOException $e) {
    $data['success'] = false;
    $data['message'] = message('warning', 'Ooops!', $e->getMessage(), '', '');
    echo json_encode($data);
    return false;
}


foreach ($data['invoices'] as $key => $invoice) {

    $contractor_info = getContractors($conn, $invoice['contractor_id']);

    $data['invoices'][$key]['contractor_company_name'] = $contractor_info['company_name'];

    $data['invoices'][$key]['issuance_date_br'] = dateScreen($invoice['issuance_date'], 1);
    $data['invoices'][$key]['due_date_br'] = dateScreen($invoice['due_date'], 1);
    $data['invoices'][$key]['total_price_br'] = number_format($invoice['total_price'], 2, ',', '.');
}



// var_dump($data['invoices']);

echo json_encode($data);

return true;
