<?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']) : '');

$data['sent_to_contractor'] = (isset($post['sent_to_contractor']) && !empty($post['sent_to_contractor']) && $post['sent_to_contractor'] != 0 ? $post['sent_to_contractor'] : "");
$data['sent_to_paying'] = (isset($post['sent_to_paying']) && !empty($post['sent_to_paying']) && $post['sent_to_paying'] != 0 ? $post['sent_to_paying'] : "");
/**
 * "0" => QUALQUER,
 * "1" => ENVIADA,
 * "2" => NÃO ENVIADA,
 */

$data['contractor_organization'] = (isset($post['contractor_organization']) && !empty($post['contractor_organization']) ? (int)$post['contractor_organization'] : "");


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

$search_keys = [
    'contractor',
    'contractor_organization',
    '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";
}

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

if (!empty($data['sent_to_contractor'])) {
    
    switch ($data['sent_to_contractor']) {
        case "1":
            $terms .= " AND i.sent_to_contractor IS NOT NULL ";
            break;
        case "2":
            $terms .= " AND i.sent_to_contractor is NULL";
            break;
    }
}

if (!empty($data['sent_to_paying'])) {
    
    switch ($data['sent_to_paying']) {
        case "1":
            $terms .= " AND i.sent_to_paying IS NOT NULL ";
            break;
        case "2":
            $terms .= " AND i.sent_to_paying is NULL";
            break;
    }
}



$sql = "SELECT 

    i.id as invoice_id,
    i.invoice_number,
    i.issuance_date,
    i.due_date,
    i.contractor_id,
    i.contractor_organization,
    i.total_price,
    i.sent_to_contractor,
    i.sent_to_paying,

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

    if (!empty($data['contractor_organization'])) {
        $res->bindParam(':contractor_organization', $data['contractor_organization'], PDO::PARAM_INT);
    }
    
    $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;
}


if (empty($data['invoices'])) {
    $data['success'] = false;
    $data['message'] = message('warning', 'Ooops!', TRANS('NO_RECORDS_FOUND'), '', '');
    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]['contractor_organization_name'] = (!empty($data['invoices'][$key]['contractor_organization']) ? getContractorsOrganizations($conn, $data['invoices'][$key]['contractor_organization'])['name'] : '');
    
    $data['invoices'][$key]['sent_to_contractor'] = (!empty($invoice['sent_to_contractor']) ? '<span class="text-success"><i class="fas fa-check"></i></span>' : '');
    $data['invoices'][$key]['sent_to_paying'] = (!empty($invoice['sent_to_paying']) ? '<span class="text-success"><i class="fas fa-check"></i></span>' : '');

    $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, ',', '.');
}


$data['start_due_date_criteria'] = dateScreen($data['start_due_date'], 1);
$data['end_due_date_criteria'] = dateScreen($data['end_due_date'], 1);


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

echo json_encode($data);

return true;
