<?php
include 'php/db_connection.php';

// শুধুমাত্র লগইন করা ইউজার পেজ দেখতে পারবে
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userName = $_SESSION['user_name'];
$role = $_SESSION['role'];
$userId = $_SESSION['user_id'];
$isAdmin = ($_SESSION['role'] == 'admin');

?>

<?php
require('pdf/fpdf.php');
require 'vendor-barcode/autoload.php';

use Picqer\Barcode\BarcodeGeneratorPNG;

// কানেকশন
$con->set_charset("utf8mb4");

$id = $_GET['id'] ?? 0;

// সেলস ইনফো
$sales = $con->query("SELECT * FROM sales WHERE id = $id")->fetch_assoc();
if (!$sales) die("Invalid Sales ID");

// কাস্টমার ইনফো
$customer = $con->query("SELECT * FROM customer WHERE id = {$sales['customer_id']}")->fetch_assoc();

// আইটেম চেক করা
$items = $con->query("SELECT * FROM sales_items WHERE sales_id = $id");
$hasItems = ($items->num_rows > 0);

// PDF শুরু — 100mm width for 4-inch printer
$pdf = new FPDF('P','mm',[100,150]);
$pdf->AddPage();
$pdf->SetMargins(5, 5, 5);

// 🔹 বারকোড যোগ করা (Invoice ID দিয়ে)
$generator = new BarcodeGeneratorPNG();
$barcodeData = $generator->getBarcode($sales['id'], $generator::TYPE_CODE_128);

// ইমেজ সেভ টেম্পোরারি ফাইল আকারে
$tempBarcode = tempnam(sys_get_temp_dir(), 'barcode') . '.png';
file_put_contents($tempBarcode, $barcodeData);

// ইমেজ PDF এ বসানো
$pdf->Image($tempBarcode, 30, $pdf->GetY()+5, 40, 12); 
$pdf->Ln(20);

// টেম্প ফাইল মুছে ফেলা
unlink($tempBarcode);

// Shop Info
$pdf->SetFont('Arial','B',10);
$pdf->Cell(0,5,'SHOP NAME HERE',0,1,'C');
$pdf->SetFont('Arial','',9);
$pdf->Cell(0,5,'Address line here',0,1,'C');
$pdf->Cell(0,5,'Phone: 01XXXXXXXXX',0,1,'C');
$pdf->Ln(2);

// Customer & Invoice Info
$pdf->SetFont('Arial','',9);
$pdf->Cell(50,5,"Customer: " . $customer['Customer_name'],0,0);
$pdf->Cell(0,5,"Invoice: #" . $sales['id'],0,1);
$pdf->Cell(50,5,"Phone: " . $customer['Customer_phone'],0,0);
$pdf->Cell(0,5,"Date: " . date("d-m-Y h:i A", strtotime($sales['created_at'])),0,1);
$pdf->Cell(0,5,"Address: " . $customer['Customer_address'],0,1);
$pdf->Ln(2);

// যদি প্রোডাক্ট থাকে
if ($hasItems) {
    // হেডার
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(5,6,'#',1);
    $pdf->Cell(40,6,'Product',1);
    $pdf->Cell(10,6,'Qty',1,0,'C');
    $pdf->Cell(18,6,'Price',1,0,'R');
    $pdf->Cell(18,6,'Total',1,1,'R');

    // আইটেম
    $pdf->SetFont('Arial','',9);
    $i = 1;
    while ($item = $items->fetch_assoc()) {
        $pdf->Cell(5,6,$i++,1);
        $pdf->Cell(40,6,substr($item['product_description'],0,18),1);
        $pdf->Cell(10,6,$item['quantity'],1,0,'C');
        $pdf->Cell(18,6,number_format($item['price'],2),1,0,'R');
        $pdf->Cell(18,6,number_format($item['total'],2),1,1,'R');
    }

    // সারাংশ
    $pdf->Ln(1);
    $pdf->SetFont('Arial','',9);

    function addSummaryRow($pdf, $label, $amount) {
        $pdf->Cell(70,5,$label,0,0,'R');
        $pdf->Cell(20,5,number_format($amount, 2),0,1,'R');
    }

    // Database থেকে সঠিক মান নেওয়া
    $sub_total = floatval($sales['grand_total']);
    $discount = floatval($sales['discount']);
    $collected = floatval($sales['collected_one']);
    $final_due = floatval($sales['final_due']);
    $change = floatval($sales['change']);

    addSummaryRow($pdf, 'Sub Total:', $sub_total);
    
    if ($discount > 0) {
        addSummaryRow($pdf, 'Discount:', $discount);
    }
    
    // Grand Total = Sub Total - Discount
    $grand_total = $sub_total - $discount;
    if ($grand_total != $sub_total) {
        addSummaryRow($pdf, 'Grand Total:', $grand_total);
    }
    
    addSummaryRow($pdf, 'Collected:', $collected);
    
    if ($final_due > 0) {
        addSummaryRow($pdf, 'Due:', $final_due);
    }
    
    if ($change > 0) {
        addSummaryRow($pdf, 'Change:', $change);
    }

    $pdf->Ln(4);
    $pdf->SetFont('Arial','I',9);
    $pdf->Cell(0,5,'Thank you for your purchase!',0,1,'C');
    
} else {
    // সব প্রোডাক্ট রিটার্ন হয়ে গেছে
    $pdf->SetFont('Arial','B',11);
    $pdf->SetTextColor(220, 53, 69); // Red color
    $pdf->Cell(0,8,'ALL PRODUCTS RETURNED',0,1,'C');
    $pdf->SetTextColor(0, 0, 0); // Reset to black
    
    $pdf->Ln(3);
    $pdf->SetFont('Arial','',9);
    
    $collected = floatval($sales['collected_one']);
    $refund = floatval($sales['change']);
    
    // Summary box
    $pdf->SetFillColor(240, 240, 240);
    $pdf->Cell(0,5,'REFUND SUMMARY',0,1,'C',true);
    $pdf->Ln(1);
    
    $pdf->Cell(65,5,'Original Amount Paid:',0,0,'R');
    $pdf->Cell(25,5,number_format($collected, 2),0,1,'R');
    
    $pdf->Cell(65,5,'Refund Amount:',0,0,'R');
    $pdf->SetFont('Arial','B',9);
    $pdf->Cell(25,5,number_format($refund, 2),0,1,'R');
    
    $pdf->Ln(4);
    $pdf->SetFont('Arial','I',8);
    $pdf->Cell(0,5,'Invoice Cancelled - Full Refund Issued',0,1,'C');
}

$pdf->Output();
?>