<?php
session_start();

require_once '../../vendor/autoload.php';
require_once '../../config/database.php';
require_once '../../includes/auth.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$db = (new Database())->connect();

$orderId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($orderId <= 0) {
    die('Invalid order ID.');
}

/*
    SETTINGS
*/
$stmt = $db->prepare("
    SELECT *
    FROM settings
    LIMIT 1
");
$stmt->execute();

$settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

/*
    ORDER
*/
$stmt = $db->prepare("
    SELECT
        o.*,
        '' as table_name
    FROM orders o
    WHERE o.id = ?
");
$stmt->execute([$orderId]);

$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    die('Order not found.');
}

/*
    ITEMS
*/
$stmt = $db->prepare("
    SELECT
        oi.*,
        i.name AS item_name
    FROM order_items oi
    INNER JOIN items i ON oi.item_id = i.id
    WHERE oi.order_id = ?
");
$stmt->execute([$orderId]);

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

$subtotal = (float)$order['total'] - (float)$order['gst'];

$itemRows = '';
$rowIndex = 0;

foreach ($items as $item) {

    $lineTotal = $item['quantity'] * $item['price'];

    $rowColor = ($rowIndex % 2 === 0)
        ? '#f8fafc'
        : '#ffffff';

    $itemRows .= '
    <tr style="background:' . $rowColor . ';">
        <td>' . htmlspecialchars($item['item_name']) . '</td>
        <td class="right">' . number_format($item['quantity'], 2) . '</td>
        <td class="right">₹ ' . number_format($item['price'], 2) . '</td>
        <td class="right">₹ ' . number_format($item['gst'], 2) . '</td>
        <td class="right">₹ ' . number_format($lineTotal, 2) . '</td>
    </tr>';

    $rowIndex++;
}

$html = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<style>
body {
    font-family: DejaVu Sans;
    font-size: 12px;
    color: #1f2937;
    margin: 25px;
}

.header {
    background: #111827;
    color: white;
    padding: 20px;
    border-radius: 10px;
}

.business-name {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 8px;
}

.business-info {
    font-size: 11px;
    line-height: 1.6;
}

.invoice-top {
    margin-top: 20px;
    width: 100%;
}

.meta-box {
    width: 48%;
    display: inline-block;
    vertical-align: top;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    padding: 12px;
    box-sizing: border-box;
}

.meta-title {
    font-size: 11px;
    color: #6b7280;
    margin-bottom: 8px;
}

.meta-value {
    font-size: 13px;
    font-weight: bold;
}

.invoice-badge {
    text-align: right;
}

.invoice-number {
    font-size: 20px;
    font-weight: bold;
    color: #111827;
}

.section-title {
    margin-top: 25px;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th {
    background: #111827;
    color: white;
    padding: 10px;
    font-size: 11px;
    text-align: left;
}

td {
    padding: 10px;
    border-bottom: 1px solid #e5e7eb;
    font-size: 11px;
}

.right {
    text-align: right;
}

.summary-box {
    margin-top: 25px;
    width: 40%;
    margin-left: auto;
    border: 1px solid #d1d5db;
    border-radius: 10px;
    overflow: hidden;
}

.summary-table td {
    padding: 10px;
    font-size: 12px;
}

.grand-total {
    background: #111827;
    color: white;
    font-weight: bold;
    font-size: 14px;
}

.footer {
    margin-top: 50px;
    text-align: center;
    color: #6b7280;
    font-size: 11px;
}
</style>
</head>

<body>

<div class="header">
    <div class="business-name">
        ' . htmlspecialchars($settings['business_name'] ?? 'Restaurant') . '
    </div>

    <div class="business-info">
        ' . htmlspecialchars($settings['address'] ?? '') . '<br>
        Phone: ' . htmlspecialchars($settings['phone'] ?? '') . '<br>
        Email: ' . htmlspecialchars($settings['email'] ?? '') . '
    </div>
</div>

<table class="invoice-top">
<tr>
<td style="width:60%; padding-right:10px; vertical-align:top;">
    <div class="meta-box">
        <div class="meta-title">ORDER DETAILS</div>
        <div><strong>Table:</strong> ' . htmlspecialchars($order['table_name'] ?? 'N/A') . '</div>
        <div><strong>Status:</strong> ' . htmlspecialchars($order['status']) . '</div>
        <div><strong>Date:</strong> ' . date('d-m-Y h:i A', strtotime($order['order_date'])) . '</div>
    </div>
</td>

<td style="width:40%; vertical-align:top;">
    <div class="meta-box invoice-badge">
        <div class="meta-title">INVOICE</div>
        <div class="invoice-number">#' . $order['id'] . '</div>
    </div>
</td>
</tr>
</table>

<div class="section-title">Invoice Items</div>

<table>
<thead>
<tr>
    <th>Item</th>
    <th class="right">Qty</th>
    <th class="right">Rate</th>
    <th class="right">GST</th>
    <th class="right">Total</th>
</tr>
</thead>

<tbody>
' . $itemRows . '
</tbody>
</table>

<div class="summary-box">
    <table class="summary-table">
        <tr>
            <td>Subtotal</td>
            <td class="right">₹ ' . number_format($subtotal, 2) . '</td>
        </tr>

        <tr>
            <td>GST</td>
            <td class="right">₹ ' . number_format($order['gst'], 2) . '</td>
        </tr>

        <tr class="grand-total">
            <td>GRAND TOTAL</td>
            <td class="right">₹ ' . number_format($order['total'], 2) . '</td>
        </tr>
    </table>
</div>

<div class="footer">
    Thank you for dining with us.<br>
    We look forward to serving you again.
</div>

</body>
</html>
';

$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);

$dompdf->loadHtml($html);

$dompdf->setPaper('A4', 'portrait');

$dompdf->render();

$dompdf->stream(
    'invoice_' . $order['id'] . '.pdf',
    ['Attachment' => true]
);

exit;
?>