<?php

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

use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;

require_once "../../controllers/sales.controller.php";
require_once "../../models/sales.model.php";
require_once "../../controllers/customers.controller.php";
require_once "../../models/customers.model.php";
require_once "../../controllers/users.controller.php";
require_once "../../models/users.model.php";

// Get sale code
$code = $_GET['code'] ?? '';
if (!$code) exit("❌ No sale code provided.");

$sale = ControllerSales::ctrShowSales("code", $code);
if (!$sale) exit("❌ Sale not found.");

$products = json_decode($sale["products"], true);
$customer = ControllerCustomers::ctrShowCustomers("id", $sale["idCustomer"]);
$seller   = ControllerUsers::ctrShowUsers("id", $sale["idSeller"]);

$date  = substr($sale["saledate"], 0, -8);
$net   = floatval($sale["netPrice"]);
$tax   = floatval($sale["tax"]);
$total = floatval($sale["totalPrice"]);

try {
    $printerName = "smb://DESKTOP-DU9GAPM/XP-58"; // Your printer name
    $connector = new WindowsPrintConnector($printerName);
    $printer = new Printer($connector);

    // Header
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->setEmphasis(true);
    $printer->text("HIS MERCY COVENANT\n");
    $printer->setEmphasis(false);
    $printer->text("Mikoriola Shopping Complex\n");
    $printer->text("Onireke Road, Owo\n");
    $printer->text("Tel: 0803 080 3276\n");
    $printer->text("-------------------------------\n");

    // Sale Info
    $printer->setJustification(Printer::JUSTIFY_LEFT);
    $printer->text("Date: $date\n");
    $printer->text("Invoice: $code\n");
    $printer->text("Customer: " . ($customer["name"] ?? "N/A") . "\n");
    $printer->text("Seller: " . ($seller["name"] ?? "N/A") . "\n\n");

    // Column titles
    $printer->text("Item           Qty/U   Total\n");
    $printer->text("-------------------------------\n");

    foreach ($products as $item) {
        $desc = $item["description"];
        $qty  = $item["quantity"];
        $unitPrice = floatval($item["price"]);
        $totalPrice = $qty * $unitPrice;

        // Format and wrap item name if needed
        $descLines = str_split($desc, 12);
        foreach ($descLines as $i => $line) {
            if ($i == 0) {
                $line = str_pad($line, 12); // Item name
                $qtyUnit = number_format($qty, 0) . "  @" . number_format($unitPrice, 0);
                $qtyUnit = str_pad($qtyUnit, 8);
                $totalStr = number_format($totalPrice, 2);
                $totalStr = str_pad($totalStr, 8, " ", STR_PAD_LEFT);
                $printer->text("$line$qtyUnit$totalStr\n");
            } else {
                $printer->text(str_pad($line, 32) . "\n");
            }
        }
    }

    // Totals
    $printer->text("-------------------------------\n");
    $printer->text("Net:       N" . number_format($net, 2) . "\n");
    $printer->text("Tax:       N" . number_format($tax, 2) . "\n");
    $printer->setEmphasis(true);
    $printer->text("TOTAL:     N" . number_format($total, 2) . "\n");
    $printer->setEmphasis(false);

    // Footer
    $printer->feed(2);
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->text("Thank you for your purchase!\n");
    $printer->text("Powered by RemTech\n");
    $printer->feed(3);
    $printer->cut();
    $printer->close();

} catch (Exception $e) {
    exit("🛑 Printer error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<script>
    window.onload = function () {
        // Automatically trigger print (optional)
        window.print();

        // Show confirmation then redirect
        setTimeout(function () {
            Swal.fire({
                icon: 'success',
                title: 'Receipt Printed',
                text: 'Redirecting to Sales...',
                timer: 2000,
                showConfirmButton: false
            });

            setTimeout(function () {
                window.location.href = "C:/xampp/htdocs/POS-PHP/POS-PHP/views/modules/sales.php";
            }, 2000);
        }, 1000);
    };
</script>
</body>
</html>
