<!-- <?php
// 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";

// require_once "../../../controllers/products.controller.php";
// require_once "../../../models/products.model.php";

// class printBill {

//     public $code;                   // Sale code passed in query string
//     private $isReceipt = true;      // true  = 80 mm receipt; false = A4 invoice

//     public function getBillPrinting() {

//         /* ─────────────────────────
//            1. FETCH DATABASE DATA
//            ───────────────────────── */

//         $itemSale  = "code";
//         $valueSale = $this->code;
//         $sale      = ControllerSales::ctrShowSales($itemSale, $valueSale);

//         if (!$sale) {
//             exit("Sale not found.");
//         }

//         $saleDate   = substr($sale["saledate"], 0, -8);
//         $products   = json_decode($sale["products"], true);

//         // Raw amounts (keep them as numbers for calculations if needed later)
//         $netRaw     = $sale["netPrice"];
//         $taxRaw     = $sale["tax"];
//         $totalRaw   = $sale["totalPrice"];

//         // Formatted strings for display
//         $netFmt     = number_format($netRaw, 2);
//         $taxFmt     = number_format($taxRaw, 2);
//         $totalFmt   = number_format($totalRaw, 2);

//         // Customer data
//         $customer   = ControllerCustomers::ctrShowCustomers("id", $sale["idCustomer"]);
//         // Seller data
//         $seller     = ControllerUsers::ctrShowUsers("id", $sale["idSeller"]);

//         /* ─────────────────────────
//            2.  INITIALISE TCPDF
//            ───────────────────────── */

//         require_once('tcpdf_include.php');

//         $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//         $pdf->setPrintHeader(false);
//         $pdf->setPrintFooter(false);

//         // Margins: left, top, right (4 mm, 2 mm, 4 mm)
//         $pdf->SetMargins(4, 2, 4);
//         $pdf->SetAutoPageBreak(true, 2);   // 2 mm bottom margin on overflow
//         $pdf->SetFont('helvetica', '', 7);

//         if ($this->isReceipt) {

//             // 80 mm receipt – width in points (mm × 2.8346), generous height
//             $widthPt  = 80 * 2.8346;
//             $heightPt = 300;               // extend automatically if content spills over
//             $pdf->AddPage('P', [$widthPt, $heightPt]);

//         } else {

//             // Full A4 portrait invoice
//             $pdf->AddPage('P', 'A4');
//             $pdf->SetFontSize(10);         // bump text size for big page
//         }

//         /* ─────────────────────────
//            3.  HEADER BLOCK
//            ───────────────────────── */

//         $headerHTML = <<<HTML
// <table width="100%" style="text-align:center;">
//   <tr><td>
//       Date: $saleDate<br><br>
//       His Mercy Covenant<br>
//       Address: Mikoriola Shopping Complex, Onireke Road, Owo<br>
//       Contact: 0803 080 3276<br>
//       Invoice #: $valueSale<br><br>
//       Customer: {$customer["name"]}<br>
//       Seller: {$seller["name"]}<br>
//   </td></tr>
// </table>
// HTML;

//         $pdf->writeHTML($headerHTML, false, false, false, false, '');

//         /* ─────────────────────────
//            4.  LINE ITEMS
//            ───────────────────────── */

//         foreach ($products as $item) {

//             $unitFmt   = number_format($item["price"], 2);
//             $lineTotal = number_format($item["totalPrice"], 2);

//             $itemHTML = <<<HTML
// <table width="100%">
//   <tr>
//     <td width="70%">{$item['description']}</td>
//     <td width="30%" align="right">\$&nbsp;$unitFmt&nbsp;×&nbsp;{$item['quantity']}</td>
//   </tr>
//   <tr>
//     <td></td>
//     <td align="right">\$&nbsp;$lineTotal</td>
//   </tr>
// </table>
// HTML;

//             $pdf->writeHTML($itemHTML, false, false, false, false, '');
//         }

//         /* ─────────────────────────
//            5.  TOTALS BLOCK
//            ───────────────────────── */

//         $totalsHTML = <<<HTML
// <table width="100%" style="text-align:right;">
//   <tr><td width="50%">NET:</td><td width="50%">\$ $netFmt</td></tr>
//   <tr><td>TAX:</td><td>\$ $taxFmt</td></tr>
//   <tr><td colspan="2">------------------------------</td></tr>
//   <tr><td>TOTAL:</td><td>\$ $totalFmt</td></tr>
//   <tr><td colspan="2"><br><br>Thank you for your purchase!</td></tr>
// </table>
// HTML;

//         $pdf->writeHTML($totalsHTML, false, false, false, false, '');

//         /* ─────────────────────────
//            6.  OUTPUT
//            ───────────────────────── */

//         // Inline display; switch to 'D' for forced download
//         $pdf->Output('bill.pdf', 'I');
//     }
// }

// /* ─────────────────────────
//    7.  RUN
//    ───────────────────────── */

// $bill       = new printBill();
// $bill->code = $_GET["code"] ?? '';
// $bill->getBillPrinting();



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

// 1. Get the sale code from the query
$code = $_GET['code'] ?? '';
if (!$code) {
    exit("No sale code provided.");
}

// 2. Fetch the sale
$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 {
    // 3. Open connection to the printer
    $printerName = "XP-58IINT"; // Change if your printer name is different
    $connector = new WindowsPrintConnector($printerName);
    $printer = new Printer($connector);

    // 4. 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");

    // 5. 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");

    // 6. Line Items
    foreach ($products as $item) {
        $desc = mb_strimwidth($item["description"], 0, 20, "...");
        $qty = $item["quantity"];
        $price = number_format($item["price"], 2);
        $lineTotal = number_format($item["totalPrice"], 2);

        $printer->text(str_pad($desc, 16));
        $printer->text(str_pad("{$qty}x", 4, " ", STR_PAD_LEFT));
        $printer->text(str_pad($price, 6, " ", STR_PAD_LEFT));
        $printer->text(str_pad($lineTotal, 7, " ", STR_PAD_LEFT) . "\n");
    }

    $printer->text("\n-----------------------------\n");

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

    // 8. Footer
    $printer->feed(2);
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->text("Thanks for your purchase!\n");
    $printer->feed(3);
    $printer->cut();
    $printer->close();

    echo "Printed successfully.";
} catch (Exception $e) {
    echo "Print failed: " . $e->getMessage();
}

?> 
