<?php
require_once "../../models/Operations.php";

$sale_id = isset($_POST["sale_id"]) ? $_POST["sale_id"] : "";

if (empty(intval($sale_id))) {
    exit();
}

$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;";

$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(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 = 'Available' ORDER BY pay_det_id DESC 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);

?>

<!-- <style>
    .table_summary {
        font-family: sans-serif;
        /* font-family: "Courier New", monospace; */
        margin: 0px 5px 0px 5px;
    }

    table thead td {
        text-align: left;
        border-top: 1.5px dashed;
        border-bottom: 1.5px dashed;
    }
</style> -->

<div style="width: auto !important; background-color: white; color: black; margin:auto;">

    <div style="margin: 0px 15px 0px 15px; font-weight:500;">
        <div>&nbsp;</div>
        <table width="100%">
            <tr>
                <td style="text-align: center">
                    <div style="font-size: 21px; font-weight: bold; text-transform: uppercase"><?= $entInfo['ent_name']; ?></div>
                    <div style="font-size: 14px;"><?= $posInfo['pos_address']; ?>.</div>
                    <div style="font-size: 14px;"><?= "{$posInfo['pos_city']}, {$posInfo['pos_country']}"; ?>.</div>
                    <div style="font-size: 14px;"><?= "{$posInfo['pos_phone']}" ?>
                        <?php if (!empty($posInfo['pos_phone2'])) {
                            echo " / {$posInfo['pos_phone2']}";
                        } ?></div>
                    <div style="font-size: 14px;"><?= $ent_document; ?></div>
                </td>
            </tr>
        </table>

        <div style="border-bottom: 1.2px dashed; margin-bottom: 5px; margin-top: 5px"></div>

        <?php if (!empty($sale_ncf_type)) { ?>
            <table width="100%">
                <tr>
                    <td style="text-align: center;">
                        <div style="font-size: 14px;"><?= "{$fiscal_entry_description}: {$sale_ncf_type}{$sale_ncf_number}"; ?></div>
                        <div style="font-size: 14px;"><?= $posTranslate['valid_until']; ?>: <?= $fiscal_entry_expire_date; ?></div>
                    </td>
                </tr>
            </table>
            <div style="border-bottom: 1.2px dashed; margin-bottom: 5px; margin-top: 5px"></div>
        <?php } ?>

        <table width="100%">
            <tr>
                <td style="text-align: left;">
                    <div style="font-size: 14px;" style="text-transform: uppercase;">POS: <?= $posInfo['pos_name']; ?></div>
                    <div style="font-size: 14px;"><?= "{$posTranslate['sale_date']}: {$sale_date}"; ?></div>

                    <?php
                    if ($posInfo["pos_business_category"] == "Restaurant" || $posInfo["pos_business_category"] == "Nightclub") { ?>

                        <div style="font-size: 14px;"><?= "{$posTranslate['sale_number']}: {$saleInfo['sale_id']}"; ?> - <?= "{$posTranslate['type']}: {$saleInfo['sale_type']}"; ?>
                            <?php if ($saleInfo['sale_type'] == "Local") {
                                echo " / {$posTranslate['table']}: {$saleInfo['sale_table_id']}";
                            } ?></div>

                    <?php } else { ?>

                        <div style="font-size: 14px;"><?= "{$posTranslate['sale_number']}: {$saleInfo['sale_id']} - {$posTranslate['type']}: {$saleInfo['sale_type']}"; ?></div>

                    <?php } ?>

                    <div style="font-size: 14px;"><?= "{$posTranslate['attended_by']}: {$waiterShortName}"; ?>
                        <?php if (!empty($cashierShortName)) {
                            echo " - {$posTranslate['cashier']}: {$cashierShortName}";
                        } ?>
                    </div>

                    <div style="font-size: 14px;"><?= "{$posTranslate['customer']}: {$cusInfo['cus_full_name']}"; ?></div>
                    <?php if (!empty($sale_ncf_type) && $sale_ncf_type == "B01") { ?>
                        <div style="font-size: 14px;"><?= "{$posTranslate['customer_document']}: {$cusInfo['cus_fiscal_number']}"; ?></div>
                    <?php } ?>

                    <?php if ($saleInfo['sale_type'] == "Delivery") { ?>
                        <div style="font-size: 14px;"><?= $posTranslate['address']; ?>: <?= $cusInfo['cus_address']; ?></div>
                    <?php } ?>

                    <?php
                    if ($saleInfo['sale_status'] == "Disabled") { ?>
                        <div style="margin-top: 10px; font-size: 19px; font-weight: bold; text-align: center; text-transform: uppercase;"><?= "** {$posTranslate['canceled']} **"; ?></div>
                    <?php } ?>
                </td>
            </tr>
        </table>

        <div style="margin-bottom: 10px"></div>

        <div style="border-bottom: 1.2px dashed;"></div>

        <table width="100%">
            <thead>
                <tr>
                    <td width="50%" style="text-align: left; font-size: 14px; font-weight:600; text-transform:uppercase; height: 30px;"><?= $posTranslate['product']; ?></td>
                    <td width="25%" style="text-align: left; font-size: 14px; font-weight:600; text-transform:uppercase; height: 30px;"><?= $posTranslate['price']; ?></td>
                    <td width="25%" style="text-align: right; font-size: 14px; font-weight:600; text-transform:uppercase; height: 30px;"><?= $posTranslate['total']; ?></td>
                </tr>
            </thead>
        </table>

        <div style="border-bottom: 1.2px dashed;"></div>

        <?php
        $final_total = 0;
        $subtotal = 0;
        $grandSubTotal = 0;
        $sale_tax_value = 0;
        $sale_tax_law_value = 0;
        ?>

        <table width="100%">
            <tbody>
                <!-- LOOP ITEMS HERE -->
                <?php foreach ($saleDetInfo as $key => $get_value) {

                    $pro_description = getProductsData($get_value['sale_det_pro_id'])['pro_description'];
                    $sale_det_pro_qty = $get_value['sale_det_pro_qty'];
                    $sale_det_pro_price = $get_value['sale_det_pro_price'];
                    $subtotal = $sale_det_pro_qty * $sale_det_pro_price;
                    $grandSubTotal += $subtotal;
                ?>
                    <tr>
                        <td style="font-size: 14px;text-align: left;" width="50%"><?= "{$sale_det_pro_qty} {$pro_description}"; ?></td>
                        <td style="font-size: 14px;text-align: left;" width="25%"><?= number_format($sale_det_pro_price, 2); ?></td>
                        <td style="font-size: 14px;text-align: right;" width="25%"><?= number_format($subtotal, 2); ?></td>
                    </tr>
                <?php } ?>

                <!-- END LOOP ITEMS HERE -->
            </tbody>
        </table>

        <div style="border-bottom: 1.2px dashed; margin-bottom: 15px"></div>

        <table width="100%">
            <tbody>
                <tr>
                    <td style="font-size: 14px; text-transform:uppercase;text-align: right;">Subtotal:</td>
                    <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= number_format($grandSubTotal, 2); ?></td>
                </tr>

                <?php if ($saleInfo['sale_discount_value'] > 0) { ?>
                    <tr>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;">Discount:</td>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= number_format($saleInfo['sale_discount_value'], 2); ?></td>
                    </tr>
                <?php } ?>

                <?php if ($saleInfo['sale_tax_value'] > 0) { ?>
                    <tr>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= $posTranslate['tax']; ?> (<?= number_format($saleInfo['sale_tax_percent'], 2); ?>%):</td>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= number_format($saleInfo['sale_tax_value'], 2); ?></td>
                    </tr>
                <?php } ?>

                <?php if ($saleInfo['sale_tax_law_value'] > 0) { ?>
                    <tr>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= $posTranslate['tipping']; ?> (<?= number_format($saleInfo['sale_tax_law_percent'], 2); ?>%):</td>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= number_format($saleInfo['sale_tax_law_value'], 2); ?></td>
                    </tr>
                <?php } ?>

                <?php if ($saleInfo['sale_type'] == "Delivery") { ?>
                    <tr>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= $posTranslate['delivery']; ?>:</td>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= number_format($saleInfo['sale_cost_delivery'], 2); ?></td>
                    </tr>
                <?php }

                $final_total = ($grandSubTotal + $saleInfo['sale_tax_value'] + $saleInfo['sale_tax_law_value'] + $saleInfo['sale_cost_delivery']) - ($saleInfo['sale_discount_value']);

                $final_total_usd = 0;

                if ($posInfo['pos_currency'] != "USD" && $posInfo['pos_usd_exchange_rate'] > 0) {
                    $final_total_usd = $final_total / $posInfo['pos_usd_exchange_rate'];
                }

                // $debtChange = round($totalIncome - $final_total, 2);
                $debtChange = round($totalPaid - $final_total, 2);

                if ($debtChange < 0) {
                    $debtChangeText = $posTranslate['debt'];
                    $sale_debtValue = $debtChange * (-1);
                    $sale_debtValue = number_format($sale_debtValue, 2, '.', ',');
                } else {
                    $debtChangeText = $posTranslate['change'];
                    $sale_debtValue = $debtChange;
                    $sale_debtValue = number_format($sale_debtValue, 2, '.', ',');
                }

                ?>

                <tr>
                    <td style="font-size: 14px; font-weight: bold; text-transform:uppercase;text-align: right;"><?= $posTranslate['total'] . " " . $posInfo["pos_currency"]; ?>:</td>
                    <td style="font-size: 14px; font-weight: bold; text-transform:uppercase;text-align: right;"><?= number_format($final_total, 2); ?></td>
                </tr>

                <?php
                if ($final_total_usd > 0) { ?>
                    <tr>
                        <td style="font-size: 14px; font-weight: bold; text-transform:uppercase;text-align: right;"><?= $posTranslate['total'] . " USD"; ?>:</td>
                        <td style="font-size: 14px; font-weight: bold; text-transform:uppercase;text-align: right;"><?= number_format($final_total_usd, 2); ?></td>
                    </tr>
                <?php } ?>

                <tr>
                    <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= $posTranslate['paid']; ?>:</td>
                    <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= number_format($totalPaid, 2); ?></td>
                </tr>

                <tr>
                    <td class="summary_total" style="text-transform:uppercase;text-align: right;"><?= $debtChangeText; ?>:</td>
                    <td class="summary_total" style="text-transform:uppercase;text-align: right;"><?= $sale_debtValue; ?></td>
                </tr>

                <!-- <?php if ($debtChange < 0) { ?>
                    <tr>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= $debtChangeText; ?>:</td>
                        <td style="font-size: 14px; text-transform:uppercase;text-align: right;"><?= $sale_debtValue; ?></td>
                    </tr>
                <?php } ?> -->

            </tbody>
        </table>
        <div>&nbsp;</div>

    </div>

</div>