<?php
session_start();
include 'php/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

require __DIR__ . '/pdf/fpdf.php';
require __DIR__ . '/vendor-barcode/autoload.php';

use Picqer\Barcode\BarcodeGeneratorPNG;

$con->set_charset("utf8mb4");

$id = intval($_GET['id'] ?? 0);

/* ---------- SALES ---------- */
$sales = $con->query("SELECT * FROM sales WHERE id = $id")->fetch_assoc();
if (!$sales) die("Invalid Sales ID");

/* ---------- CUSTOMER ---------- */
$customer = $con->query(
    "SELECT * FROM customer WHERE id = {$sales['customer_id']}"
)->fetch_assoc();

/* ---------- ITEMS ---------- */
$items = $con->query(
    "SELECT * FROM sales_items WHERE sales_id = $id"
);

/* =====================================================
   AUTO HEIGHT PERFECT CALCULATION (80mm Roll)
===================================================== */

$pageWidth  = 80; // mm
$margin     = 2;

$rowHeight  = 6;
$totalRows  = $items->num_rows;

// Barcode
$barcodeHeight = 16;

// Shop info
$shopHeight = 20;

// Invoice info dynamic for address
$lineChars = 30; // approx characters per line
$lines = ceil(mb_strlen($customer['Customer_address']) / $lineChars);
$invoiceHeight = 30 + ($lines * 5); // 5mm per line

// Table header
$tableHeaderHeight = 7;

// Table body
$tableBodyHeight = $totalRows * $rowHeight;

// Summary section
$summaryHeight = 35;

// Footer
$footerHeight = 15;

// Final page height
$pageHeight =
    $barcodeHeight +
    $shopHeight +
    $invoiceHeight +
    $tableHeaderHeight +
    $tableBodyHeight +
    $summaryHeight +
    $footerHeight +
    20; // extra padding

// FPDF safety limits
if($pageHeight < 150) $pageHeight = 150;
if($pageHeight > 2000) $pageHeight = 2000;

/* ===================================================== */
$pdf = new FPDF('P','mm',[$pageWidth,$pageHeight]);
$pdf->SetMargins($margin,$margin,$margin);
$pdf->SetAutoPageBreak(false);
$pdf->AddPage();

$pdf->SetFont('Arial','',9);

/* ---------- BARCODE ---------- */
$generator = new BarcodeGeneratorPNG();
$barcodeData = $generator->getBarcode(
    $sales['id'],
    $generator::TYPE_CODE_128
);

$tmp = sys_get_temp_dir().'/inv_'.$sales['id'].'.png';
file_put_contents($tmp,$barcodeData);

$barcodeW = 50;
$pdf->Image($tmp, ($pageWidth-$barcodeW)/2, $pdf->GetY(), $barcodeW, 14);
$pdf->Ln(16);
unlink($tmp);

/* ---------- SHOP INFO ---------- */
$pdf->SetFont('Arial','B',11);
$pdf->Cell(0,5,'SHOP NAME HERE',0,1,'C');

$pdf->SetFont('Arial','',9);
$pdf->Cell(0,4,'Address line here',0,1,'C');
$pdf->Cell(0,4,'Phone: 01XXXXXXXXX',0,1,'C');

$pdf->Ln(2);
$pdf->Cell(0,0,str_repeat('-',40),0,1,'C');
$pdf->Ln(2);

/* ---------- INVOICE INFO ---------- */
$pdf->Cell(0,5,'Invoice #: '.$sales['id'],0,1);
$pdf->Cell(0,5,'Date: '.date("d-m-Y h:i A",strtotime($sales['created_at'])),0,1);
$pdf->Cell(0,5,'Customer: '.$customer['Customer_name'],0,1);
$pdf->Cell(0,5,'Phone: '.$customer['Customer_phone'],0,1);
$pdf->MultiCell(0,5,'Address: '.$customer['Customer_address']);

$pdf->Ln(2);

/* ---------- TABLE HEADER WITH SL ---------- */
$pdf->SetFont('Arial','B',9);
$pdf->SetFillColor(230,230,230);

$pdf->Cell(8,7,'SL',1,0,'C',true);          // SL No.
$pdf->Cell(28,7,'Item',1,0,'L',true);
$pdf->Cell(10,7,'Qty',1,0,'C',true);
$pdf->Cell(14,7,'Price',1,0,'R',true);
$pdf->Cell(14,7,'Total',1,1,'R',true);

/* ---------- TABLE BODY ---------- */
$pdf->SetFont('Arial','',9);
$fill = false;
$sl = 1;

$items->data_seek(0);

while ($item = $items->fetch_assoc()) {

    $name = mb_strimwidth(
        $item['product_description'],
        0,
        26,
        '…'
    );

    // Add small padding by adjusting cell width or multi-cell (simple padding using space)
    $pdf->Cell(8,6,$sl,1,0,'C',$fill);
    $pdf->Cell(28,6,' '.$name,1,0,'L',$fill);
    $pdf->Cell(10,6,$item['quantity'],1,0,'C',$fill);
    $pdf->Cell(14,6,number_format($item['price'],2),1,0,'R',$fill);
    $pdf->Cell(14,6,number_format($item['total'],2),1,1,'R',$fill);

    $fill = !$fill;
    $sl++;
}

/* ---------- SUMMARY ---------- */
$pdf->Ln(3);
$pdf->SetFont('Arial','B',9);

function summaryRow($pdf,$label,$value){
    $pdf->Cell(55,6,$label,0,0,'R');
    $pdf->Cell(18,6,number_format($value,2),0,1,'R');
}

summaryRow($pdf,'Sub Total:', $sales['grand_total']);
summaryRow($pdf,'Discount:', $sales['discount']);
summaryRow($pdf,'Collected:', $sales['collected_one']);

/* --------------------------------------------------
summaryRow(
    $pdf,
    
    'Due:',
    $sales['grand_total'] - $sales['discount'] - $sales['collected_one']
);------------------------------  */
summaryRow($pdf,'Change:', $sales['change']);

$pdf->Ln(4);

/* ---------- FOOTER ---------- */
$pdf->SetFont('Arial','I',9);
$pdf->Cell(0,1,'Thank you for your purchase!',0,1,'C');

/* ---------- OUTPUT ---------- */
$pdf->Output('I','invoice_'.$sales['id'].'.pdf');
exit;