<?php
require '../../vendor/autoload.php';
require_once "../../models/Operations.php";

if (empty(intval($_GET["sale_id"]))) {
    exit();
} else {
    $sale_id = intval($_GET["sale_id"]);
}

$saleQuery = "SELECT * FROM tb_sales WHERE sale_id = {$sale_id};";
$saleInfo = executePDOFetchOneAPI($saleQuery);

if ($saleInfo['status'] == "error" || empty($saleInfo['data'])) {
    exit();
}

$saleInfo = $saleInfo['data'];

$entInfo = getEnterpriseData($saleInfo['sale_ent_id']);
$posInfo = getBranchData($saleInfo['sale_pos_id']);

//Establecemos los datos de la cabeza de la venta
$sale_id = $saleInfo['sale_id'];
$sale_ncf_type = $saleInfo['sale_ncf_type'];
$sale_ncf_number = $saleInfo['sale_ncf_number'];
$sale_date = date("d-M-Y H:i:s", strtotime($saleInfo['sale_date']));

$salePaymentDetail = "SELECT
IFNULL(SUM(pay_det_value),0) AS pay_det_value,
IFNULL(SUM(pay_det_income),0) AS pay_det_income,
pay_det_payment_type AS payment_type
FROM tb_payments_details
WHERE pay_det_sale_id = {$saleInfo['sale_id']}
GROUP BY pay_det_payment_type;";

// $sqlGetLastPaymentChange = "SELECT
// IFNULL(pay_det_change,0) AS pay_det_change
// FROM tb_payments_details
// WHERE pay_det_sale_id = {$saleInfo['sale_id']}
// ORDER BY pay_det_id ASC LIMIT 1;";
// $saleInfoLastPaymentChange = executePDOFetchOneAPI($sqlGetLastPaymentChange);

// if ($saleInfoLastPaymentChange['status'] == "error") {
//     exit();
// }

// $lastPaymentChange = $saleInfoLastPaymentChange['data']['pay_det_change'];

$totalPaid = 0;
$totalIncome = 0;
$paymentTypes = [];

$saleInfoPaymentDetail = executePDOFetchAll($salePaymentDetail);

if (is_array($saleInfoPaymentDetail)) {
    // Process the results
    foreach ($saleInfoPaymentDetail as $key => $value) {
        $totalPaid += $value['pay_det_value'];
        $totalIncome += $value['pay_det_income'];
        $paymentTypes[] = $value['payment_type'];
    }
} else {
    // Handle the error
    echo $saleInfoPaymentDetail;
}

//Obtenemos todos los detalles de la venta actual
$sql = "SELECT
sale_det_pro_id 
,IFNULL(sale_det_pro_price,0) AS sale_det_pro_price
,IFNULL(SUM(sale_det_pro_qty),0) AS sale_det_pro_qty
FROM tb_sales_details
LEFT JOIN tb_products ON pro_id = sale_det_pro_id 
WHERE sale_det_sale_id = {$sale_id} GROUP BY sale_det_pro_id,sale_det_pro_price;";
$saleDetInfo = executePDOFetchAll($sql);

//SALE TYPE INFORMATION
$sqlSaleTypeInfo = "SELECT * FROM tb_sale_type WHERE sale_type_ent_id = '{$saleInfo['sale_ent_id']}' AND sale_type_pos_id = '{$saleInfo['sale_pos_id']}' AND sale_type_name = '{$saleInfo['sale_type']}';";
$saleTypeInfo = executePDOFetchOne($sqlSaleTypeInfo, "Could not get sale type information");

$userQuery = "SELECT CONCAT(user_firstname,' ',user_lastname) AS waiter FROM tb_users WHERE user_id = {$saleInfo['sale_created_by']};";
$userInfo = executePDOFetchOne($userQuery);

$waiter = $userInfo["waiter"];
if (!empty(trim((string) $waiter))) {
    $waiterShortName = getShortName($waiter);
} else {
    $waiterShortName = "";
}

$sqlCashier = "SELECT
(select CONCAT(user_firstname,' ',user_lastname) AS cashier from tb_users WHERE user_id = pay_det_created_by) as cashier
FROM tb_sales
LEFT JOIN tb_payments_details ON pay_det_sale_id={$saleInfo['sale_id']}
WHERE sale_id = {$sale_id}
GROUP BY sale_id;";
$CashierResult = executePDOFetchOne($sqlCashier);

$cashier = $CashierResult["cashier"];
if (!empty($cashier)) {
    $cashierShortName = getShortName($cashier);
} else {
    $cashierShortName = "";
}

$cusQuery = "SELECT *
,IFNULL((SELECT SUM(CASE WHEN pay_det_cashback_status = 'Available' THEN pay_det_cashback ELSE 0 END) - 
SUM(CASE WHEN pay_det_cashback_status = 'Used' THEN pay_det_cashback ELSE 0 END)
FROM tb_payments_details WHERE pay_det_cus_id = cus_id AND pay_det_status = 'Enabled'),0) AS cus_available_cashback

,IFNULL((SELECT IFNULL(SUM(pay_det_cashback),0) FROM tb_payments_details WHERE pay_det_cus_id = cus_id AND pay_det_status = 'Enabled' AND pay_det_sale_id = {$saleInfo['sale_id']} AND pay_det_cashback_status = 'Pending' ORDER BY pay_det_id ASC LIMIT 1),0) AS cus_current_cashback

FROM tb_customers WHERE cus_id = {$saleInfo['sale_cus_id']};";
$cusInfo = executePDOFetchOne($cusQuery);

$fiscal_entry_expire_date = "";
$fiscal_entry_description = "";

if (!empty($sale_ncf_type)) {

    $fiscalQuery = "SELECT
    fiscal_entry_description
    ,DATE_FORMAT(fiscal_entry_expire_date, '%d-%b-%Y') AS fiscal_entry_expire_date
    FROM tb_fiscal_receipt_entry
    WHERE fiscal_entry_ent_id = {$entInfo['ent_id']} AND fiscal_entry_type = '{$sale_ncf_type}'
    ORDER BY fiscal_entry_id DESC LIMIT 1;";

    $fiscalInfo = executePDOFetchOne($fiscalQuery);
    $fiscal_entry_expire_date = $fiscalInfo['fiscal_entry_expire_date'];
    $fiscal_entry_description = $fiscalInfo['fiscal_entry_description'];
}

//Establecemos la fecha actual de la impresion
$timeZone = $posInfo['pos_time_zone'] ?? "America/New_York";
date_default_timezone_set($timeZone);

$currentDateTimeByZone = mdlGetDateTimeByZone($timeZone);

$ent_document = "";
if (in_array($entInfo['ent_document'], ['EIN', 'NIF', 'RNC', 'DNI']) && !empty($entInfo['ent_document_number'])) {
    $ent_document = "{$entInfo['ent_document']} : {$entInfo['ent_document_number']}";
}

//POS TRANSLATE
$posLang = $posInfo['pos_lang'];

if ($posLang == "es") {
    $getPosLanguage = file_get_contents("../../lang/pos_es.json");
} else if ($posLang == "fr") {
    $getPosLanguage = file_get_contents("../../lang/pos_fr.json");
} else {
    $getPosLanguage = file_get_contents("../../lang/pos_en.json");
}
$posTranslate = json_decode($getPosLanguage, true);


// $pdf = new PDF_Code128('P','mm',array(80,258));

$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8',
    'format' => [80, 258],
    'orientation' => 'P',
    'margin_left' => 3,
    'margin_right' => 3,
    'margin_top' => 1,
    'margin_bottom' => 25,
    'margin_header' => 1,
    'margin_footer' => 5
]);

$mpdf->SetProtection(array('print'));
$mpdf->SetTitle("EVOSYS POS - Ticket");
$mpdf->SetAuthor("EVOSYS POS LLC");
// $mpdf->SetWatermarkText("");
// $mpdf->showWatermarkText = true;
// $mpdf->watermark_font = 'DejaVuSansCondensed';
// $mpdf->watermarkTextAlpha = 0.1;
$mpdf->SetDisplayMode('fullpage');

ob_start();
include(dirname(__FILE__) . '/ticket-html.php');
$html = ob_get_clean();

$mpdf->WriteHTML($html);
$mpdf->Output("{$entInfo['ent_name']} - Sale Ticket - {$sale_id}.pdf", 'I');
// $mpdf->Output();
