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

require_once __DIR__ . '/fpdf.php';
require_once __DIR__ . '/../model/users.php'; // Now needed to fetch order details

if (session_status() == PHP_SESSION_NONE) {
    session_start(); // Start session if not already started
}

// Get order_id from GET request
$orderId = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;

if ($orderId <= 0) {
    die("Invalid or missing Order ID.");
}

// Fetch order details from the database using the User model
$userModel = new User();
$orderDetails = $userModel->getOrderDetailsById($orderId);
$userModel->closeConnection();

if (!$orderDetails) {
    die("Could not retrieve order details for Order ID: " . htmlspecialchars($orderId));
}

// Extract data for the PDF
$formattedCartItems = $orderDetails['items']; // Already formatted by getOrderDetailsById
$queueNumberDisplay = $orderDetails['queue_number'] ?? 'N/A';
$userNameDisplay = $orderDetails['full_name'] ?? 'N/A';
$orderDate = $orderDetails['date'] ?? date('Y-m-d H:i:s');
// $grandTotalFromModel = $orderDetails['grand_total']; // Already calculated by model

// --- End data retrieval and formatting ---

class PDF extends FPDF {
    public $queueNumberDisplay = 'N/A';
    public $userNameDisplay = 'N/A';
    public $orderDateDisplay; // To store the order date
    public $orderIdDisplay = 'N/A'; // New public property for Order ID

    // Page header
    function Header() {
        $this->Image(__DIR__ . '/pdflogo.png', 10, 10, 30); // Logo, ensure path is correct
        $this->SetXY(45, 15); // Adjusted X position for company name
        $this->SetFont('Arial', 'B', 18);
        $this->Cell(0, 10, 'PharmaEase', 0, 0, 'L');
        
        $this->SetXY(45, 25); // Adjusted X 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, 'Order ID: ' . $this->orderIdDisplay, 0, 1, 'L'); // Use the new public property
        $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: ' . $this->orderDateDisplay, 0, 1, 'L');
        $this->Ln(10); // Space after details before table
    }

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

    // Order items table
    function OrderTable($header, $data, $grandTotal) {
        // 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);
        // $currentGrandTotal = 0; // grandTotal is now passed as parameter
        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();
            // $currentGrandTotal += $row['sub_total']; // Not needed if grandTotal passed
        }
        // 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();
$pdf->orderIdDisplay = $orderId; // Set the public property
$pdf->queueNumberDisplay = $queueNumberDisplay;
$pdf->userNameDisplay = $userNameDisplay;
$pdf->orderDateDisplay = date('Y-m-d H:i:s', strtotime($orderDate)); // Format date for display

$pdf->AliasNbPages();
$pdf->SetTitle("Order Receipt - ID: " . $orderId);
$pdf->AddPage();

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

// Populate table with formatted cart items
$pdf->OrderTable($header, $formattedCartItems, $orderDetails['grand_total']);

// Output PDF
$pdf->Output('I', 'PharmaEase_Receipt_Order' . $orderId . '_' . date('Ymd') . '.pdf');

?>