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

require '../../vendor/autoload.php';
// require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8',
    'format' => 'Letter',
    'orientation' => 'P',
    'margin_left' => 15,
    'margin_right' => 15,
    'margin_top' => 12,
    'margin_bottom' => 20,
    'margin_header' => 10,
    'margin_footer' => 10
]);

$ent_id = isset($_GET["ent"]) ? $_GET["ent"] : "";
$pos_id = isset($_GET["pos"]) ? $_GET["pos"] : "";
$fromDateGet = isset($_GET["from"]) ? $_GET["from"] : "";
$toDateGet = isset($_GET["to"]) ? $_GET["to"] : "";
$pay_det_sale_type = isset($_GET["saleType"]) ? $_GET["saleType"] : "";
$pay_det_payment_type = isset($_GET["payType"]) ? $_GET["payType"] : "";
$pay_det_created_by = isset($_GET["cashier"]) ? $_GET["cashier"] : "";
$group_by_period = isset($_GET["groupBy"]) ? $_GET["groupBy"] : "";
$purpose = isset($_GET["purpose"]) ? $_GET["purpose"] : "view";

if (empty(intval($pos_id))) exit();

$posInfo = getBranchData($pos_id);
$entInfo = getEnterpriseData($posInfo['pos_ent_id']);

$DayStartTime = $posInfo["pos_day_start_time"] ?? "07:00:00";
$DayEndTime = $posInfo["pos_day_end_time"] ?? "06:59:59";

$whereEnterprise = "WHERE pay_det_ent_id = '$ent_id'";
$wherePos = "AND pay_det_pos_id = '$pos_id'";

$fromDate = date("{$fromDateGet} {$DayStartTime}");
$toDate = date("Y-m-d", strtotime("{$toDateGet} +1 day")) . " {$DayEndTime}";
$whereDate = "AND pay_det_date BETWEEN '{$fromDate}' AND '{$toDate}'";

$whereSaleType = "";
if (!empty($pay_det_sale_type)) $whereSaleType = "AND pay_det_sale_type = '$pay_det_sale_type'";

$wherePaymentType = "AND pay_det_payment_type != 'CASHBACK'";
if (!empty($pay_det_payment_type)) $wherePaymentType = "AND pay_det_payment_type = '$pay_det_payment_type'";

$whereEmployee = "";
if (!empty($pay_det_created_by)) $whereEmployee = "AND pay_det_created_by = '$pay_det_created_by'";

$datePeriodSelected = "DATE_FORMAT(DATE_ADD(pay_det_date, INTERVAL -8 HOUR), '%d-%b-%Y') AS pay_det_period";
if ($group_by_period == "month") $datePeriodSelected = "DATE_FORMAT(DATE_ADD(pay_det_date, INTERVAL -8 HOUR), '%M %Y') AS pay_det_period";
if ($group_by_period == "year") $datePeriodSelected = "DATE_FORMAT(DATE_ADD(pay_det_date, INTERVAL -8 HOUR), '%Y') AS pay_det_period";

$sql = "SELECT
$datePeriodSelected
,pay_det_sale_type
,pay_det_payment_type
,(select pos_name FROM tb_pos WHERE pos_id = pay_det_pos_id) AS pos_name
,IFNULL(SUM(CASE WHEN pay_det_date <= pay_det_sale_close THEN pay_det_income ELSE 0 END), 0) AS pay_det_income
,IFNULL(SUM(CASE WHEN pay_det_date > pay_det_sale_close THEN pay_det_income ELSE 0 END), 0) AS pay_det_debt_collect
,IFNULL(SUM(pay_det_income),0) AS total_pay_det_income
FROM tb_payments_details
$whereEnterprise
$wherePos
$whereDate
$whereSaleType
$wherePaymentType
$whereEmployee
AND pay_det_status = 'Enabled'
GROUP BY pay_det_period,pay_det_payment_type
ORDER BY pay_det_id ASC;";

$paymentDetails = executePDOFetchAllAPI($sql);

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

$currentDateTimeByZone = mdlGetDateTimeByZone($timeZone);
$currentDateTimeByZone = date("d-M-Y H:i:s", strtotime($currentDateTimeByZone));

$start = date_create($fromDateGet);
$end = date_create($toDateGet);
$start_date_format = date_format($start, 'd-M-Y');
$end_date_format = date_format($end, 'd-M-Y');

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


// SHOW CASHIER NAME
$cashierInfo = strtoupper($posTranslate['cashier_all']);
if (!empty($pay_det_created_by)) {

    $sqlEmployeeInfo = "SELECT CONCAT(user_firstname,' ',user_lastname) AS cashier_full_name FROM tb_users WHERE user_id = {$pay_det_created_by}";

    $response = executePDOFetchOne($sqlEmployeeInfo);
    $cashierfullName = getShortName($response["cashier_full_name"]);

    $cashierInfo = mb_strtoupper($posTranslate['cashier']) . ': ' . strtoupper($cashierfullName);
}

$saleTypeInfo = strtoupper($posTranslate['sale_type_all']);
if (!empty($pay_det_sale_type)) {
    $saleTypeInfo = strtoupper($posTranslate['sale_type']) . ": " . strtoupper($pay_det_sale_type);
}

$paymentTypeInfo = mb_strtoupper($posTranslate['payment_method_all']);
if (!empty($pay_det_payment_type)) {
    $paymentTypeInfo = mb_strtoupper($posTranslate['payment_method_all']) . ": " . strtoupper($pay_det_payment_type);
}

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


$mpdf->SetProtection(array('print'));
$mpdf->SetTitle("{$posInfo['pos_name']}-sales-report-{$start_date_format}-to-{$end_date_format}");
$mpdf->SetAuthor("EVOSYS POS LLC");
$mpdf->SetWatermarkText("");
$mpdf->showWatermarkText = true;
$mpdf->watermark_font = 'DejaVuSansCondensed';
$mpdf->watermarkTextAlpha = 0.1;
$mpdf->SetDisplayMode('fullpage');

$mpdf->WriteHTML($html);

if ($purpose == "view") {
    $mpdf->Output("{$posInfo['pos_name']}-sales_report.pdf", 'I');
}

if ($purpose == "download") {
    $mpdf->Output("{$posInfo['pos_name']}-sales_report.pdf", 'D');
}

if ($purpose == "email") {

    // Output PDF as STRING (no file saved)
    $pdfString = $mpdf->Output("{$posInfo['pos_name']}-sales_report.pdf", \Mpdf\Output\Destination::STRING_RETURN);
    // Base64 encode for Resend attachment
    $pdfBase64 = base64_encode($pdfString);
    // Echo email data
    echo json_encode([
        "filename" => "{$posInfo['pos_name']}-sales_report.pdf",
        "content" => $pdfBase64,
        "type" => "application/pdf"
    ]);

    exit;
}
