<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/fpdf.php';
// require_once __DIR__ . '/../model/users.php'; // Not strictly needed if all data comes via POST

// --- Retrieve data from POST ---
$cartItemsJson = isset($_POST['cart_items_json']) ? $_POST['cart_items_json'] : '[]';
$queueNumberFromPost = isset($_POST['queue_number']) ? htmlspecialchars($_POST['queue_number']) : 'N/A';
$userNameFromPost = isset($_POST['user_name']) ? htmlspecialchars($_POST['user_name']) : 'N/A';

$cartItemsData = json_decode($cartItemsJson, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    // Handle JSON decode error, maybe log it or output a simpler error PDF/message
    die("Error decoding cart items. Invalid data received from generate.php.");
}

if (empty($cartItemsData)) {
    // Handle empty cart, maybe log it or output a simpler error PDF/message
    die('No items in cart to generate a receipt. Data received may be empty.');
}

// Transform $cartItemsData from localStorage format to the format expected by OrderTable
// localStorage format: { title: '...', quantity: N, price: '₱X.XX', ... }
// OrderTable expects: { name: '...', quantity: N, price_each: X.XX, sub_total: Y.YY }
$formattedCartItems = [];
foreach ($cartItemsData as $item) {
    $price = isset($item['price']) ? floatval(str_replace('₱', '', $item['price'])) : 0.0;
    $quantity = isset($item['quantity']) ? intval($item['quantity']) : 0;
    $formattedCartItems[] = [
        'name' => isset($item['name']) ? $item['name'] : (isset($item['title']) ? $item['title'] : 'Unknown Item'),
        'quantity' => $quantity,
        'price_each' => $price,
        'sub_total' => $price * $quantity
    ];
}
// --- End data retrieval and formatting ---

class PDF extends FPDF {
    public $queueNumberDisplay = 'N/A'; // Default value
    public $userNameDisplay = 'N/A';    // Default value

    // Page header
    function Header() {
        $this->Image('pdflogo.png', 10, 10, 30); // Logo
        $this->SetXY(35, 15); // Position for company name
        $this->SetFont('Arial', 'B', 18);
        $this->Cell(0, 10, 'PharmaEase', 0, 0, 'L');
        
        $this->SetXY(35, 25); // Position for receipt title
        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 10, 'Order Receipt', 0, 1, 'L');
        
        $this->Ln(5); // Space before details

        $this->SetFont('Arial', '', 10);
        $this->Cell(0, 6, 'Queue Number: ' . $this->queueNumberDisplay, 0, 1, 'L');
        $this->Cell(0, 6, 'Customer Name: ' . $this->userNameDisplay, 0, 1, 'L');
        $this->Cell(0, 6, 'Date: ' . date('Y-m-d H:i:s'), 0, 1, 'L');
        $this->Ln(10); // Space after details before table
    }

    // Page footer
    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
        $this->Ln();
        $this->Cell(0,10,'Thank you for your purchase!',0,0,'C');
    }

    // Order items table
    function OrderTable($header, $data) {
        // Column widths
        $w = array(95, 25, 35, 35); // Name, Qty, Price Each, Subtotal
        // Header
        $this->SetFont('Arial', 'B', 10);
        $this->SetFillColor(224, 235, 255);
        $this->SetTextColor(0);
        for ($i = 0; $i < count($header); $i++)
            $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', true);
        $this->Ln();
        // Data
        $this->SetFont('Arial', '', 10);
        $grandTotal = 0;
        foreach ($data as $row) {
            $this->Cell($w[0], 6, $row['name'], 'LR');
            $this->Cell($w[1], 6, $row['quantity'], 'LR', 0, 'C');
            $this->Cell($w[2], 6, number_format($row['price_each'], 2), 'LR', 0, 'R');
            $this->Cell($w[3], 6, number_format($row['sub_total'], 2), 'LR', 0, 'R');
            $this->Ln();
            $grandTotal += $row['sub_total'];
        }
        // Closing line
        $this->Cell(array_sum($w), 0, '', 'T');
        $this->Ln(2);

        // Grand Total
        $this->SetFont('Arial', 'B', 12);
        $this->Cell($w[0] + $w[1] + $w[2], 8, 'Grand Total:', 0, 0, 'R');
        $this->Cell($w[3], 8, number_format($grandTotal, 2), 1, 1, 'R', true);
    }
}

// PDF Generation
$pdf = new PDF();
// Set the dynamic properties before calling AddPage (which calls Header)
$pdf->queueNumberDisplay = $queueNumberFromPost;
$pdf->userNameDisplay = $userNameFromPost;

$pdf->AliasNbPages();
$pdf->AddPage();

// Font for table content is set in OrderTable method

// Table Header
$header = array('Item Name', 'Qty', 'Price', 'Total');

// Populate table with formatted cart items
$pdf->OrderTable($header, $formattedCartItems);

// Output PDF
$pdf->Output('I', 'PharmaEase_Receipt_' . date('Ymd_His') . '.pdf'); // 'D' forces download

?>