<?php
require_once __DIR__ . "/../../config.php";
require __DIR__ . '/../../vendor/autoload.php'; // FPDF must be installed

header("Content-Type: application/json");

$id = $_GET['id'] ?? null;
if (!$id) {
    http_response_code(400);
    echo json_encode(["error" => "Missing reservation ID"]);
    exit;
}

// Ensure invoices directory exists
$invoiceDir = __DIR__ . "/../../invoices";
if (!is_dir($invoiceDir)) {
    mkdir($invoiceDir, 0777, true);
}

// Get reservation + customer info
$sql = "SELECT r.reservation_id, r.date, r.time, r.num_of_persons, r.message, r.created_at, 
               u.fullname AS customer_name
        FROM reservations r
        JOIN user u ON r.user_id = u.user_id
        WHERE r.reservation_id = ?";

if ($stmt = mysqli_prepare($link, $sql)) {
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if ($row = mysqli_fetch_assoc($result)) {
        // Invoice number
        $row['invoice_number'] = "INV-" . str_pad($row['reservation_id'], 6, "0", STR_PAD_LEFT);

        // Get items
        $items_sql = "SELECT o.food_id, m.food_name AS name, m.price, m.img
                      FROM orders o
                      JOIN menu m ON o.food_id = m.food_id
                      WHERE o.reservation_id = ?";
        $items_stmt = mysqli_prepare($link, $items_sql);
        mysqli_stmt_bind_param($items_stmt, "i", $id);
        mysqli_stmt_execute($items_stmt);
        $items_result = mysqli_stmt_get_result($items_stmt);

        $items = [];
        while ($item = mysqli_fetch_assoc($items_result)) {
            $item['price'] = (float)$item['price'];
            $items[] = $item;
        }
        mysqli_stmt_close($items_stmt);

        $row['items'] = $items;

        // Generate PDF invoice
        $pdf = new FPDF();
        $pdf->AddPage();

        // Title
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 10, "Invoice " . $row['invoice_number'], 0, 1, 'C');

        // Customer info
        $pdf->SetFont('Arial', '', 12);
        $pdf->Cell(0, 8, "Customer: " . $row['customer_name'], 0, 1);
        $pdf->Cell(0, 8, "Date: " . $row['date'], 0, 1);
        $pdf->Ln(5);

        // Table header
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(80, 8, "Item Name", 1);
        $pdf->Cell(40, 8, "Price", 1);
        $pdf->Ln();

        // Table data
        $pdf->SetFont('Arial', '', 12);
        foreach ($items as $item) {
            $pdf->Cell(80, 8, $item['name'], 1);
            $pdf->Cell(40, 8, '$' . number_format($item['price'], 2), 1);
            $pdf->Ln();
        }

        // Save PDF
        $pdf_file = $invoiceDir . "/invoice_" . $row['reservation_id'] . ".pdf";
        $pdf->Output('F', $pdf_file);

        $row['pdf_link'] = "http://localhost/restaurant_server/invoices/invoice_" . $row['reservation_id'] . ".pdf";

        echo json_encode($row);
    } else {
        http_response_code(404);
        echo json_encode(["error" => "Reservation not found"]);
    }

    mysqli_stmt_close($stmt);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to prepare SQL statement"]);
}

mysqli_close($link);
