<?php
session_start();
require_once 'config/db_config.php';

// Check if admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

$order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$print_type = in_array($_GET['print'] ?? '', ['bill', 'token']) ? $_GET['print'] : 'bill';
$branch_id = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : 0;

if ($order_id <= 0) {
    die("Invalid order ID.");
}

$errors = [];
$order = null;
$order_items = [];
$branch = [];

// === 1. Fetch Order with Branch Info ===
try {
    $stmt = $pdo->prepare("
        SELECT 
            o.*, 
            o.is_gst_active as gst_active,
            b.branch_name,
            b.address,
            b.city,
            b.state,
            b.country,
            b.logo,
            b.branch_id
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        WHERE o.order_id = ?
    ");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        die("Order not found.");
    }
    
    // Set branch_id from order
    $branch_id = $order['branch_id'];
} catch (Exception $e) {
    die("Order fetch failed: " . $e->getMessage());
}

// === 2. Printer Settings ===
$printer_type = 'Thermal';
$paper_size = 'A4';
$thermal_width = '3 inch';
try {
    $stmt = $pdo->prepare("SELECT default_printer_type, default_paper_size, default_thermal_paper_size FROM printer_settings WHERE branch_id = ?");
    $stmt->execute([$branch_id]);
    $settings = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($settings) {
        $printer_type = $settings['default_printer_type'] ?? 'Thermal';
        $paper_size = $settings['default_paper_size'] ?? 'A4';
        $thermal_width = $settings['default_thermal_paper_size'] ?? '3 inch';
    }
} catch (Exception $e) {
    // Use defaults if no settings found
}

// === 3. Fetch Order Items + GST Flag from branch_food_stock ===
try {
    $stmt = $pdo->prepare("
        SELECT 
            oi.quantity,
            oi.price_per_unit,
            oi.subtotal,
            oi.unit_display,
            f.food_name,
            bfs.is_gst,
            bfs.stock_unit
        FROM order_items oi
        JOIN foods f ON oi.food_id = f.food_id
        JOIN branch_foods bf ON f.food_id = bf.food_id AND bf.branch_id = ?
        LEFT JOIN branch_food_stock bfs ON bf.branch_food_id = bfs.branch_food_id
        WHERE oi.order_id = ?
        ORDER BY oi.item_id
    ");
    $stmt->execute([$branch_id, $order_id]);
    $order_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fix unit_display if missing
    foreach ($order_items as &$item) {
        if (empty($item['unit_display'])) {
            $qty = (float)$item['quantity'];
            $unit = $item['stock_unit'] ?? 'piece';

            if ($unit === 'kg') {
                $item['unit_display'] = $qty >= 1 ? number_format($qty, 3) . 'kg' : ($qty * 1000) . 'g';
            } elseif ($unit === 'gram') {
                $item['unit_display'] = $qty >= 1000 ? number_format($qty / 1000, 3) . 'kg' : number_format($qty, 0) . 'g';
            } else {
                $item['unit_display'] = number_format($qty, 0) . ' ' . $unit;
            }
        }
    }
    unset($item);
} catch (Exception $e) {
    $errors[] = "Items load error: " . $e->getMessage();
}

// === 4. Calculations ===
$subtotal = array_sum(array_column($order_items, 'subtotal'));
$gst_items_total = 0;
$non_gst_items_total = 0;

foreach ($order_items as $item) {
    if ($item['is_gst']) {
        $gst_items_total += $item['subtotal'];
    } else {
        $non_gst_items_total += $item['subtotal'];
    }
}

$total_gst = (float)($order['cgst_amount'] ?? 0) + (float)($order['sgst_amount'] ?? 0);
$taxable_amount = (float)($order['taxable_amount'] ?? 0);
$extra_charge = (float)($order['extra_charge'] ?? 0);
$grand_total = (float)($order['total_amount'] ?? 0);
$branch_name = htmlspecialchars($order['branch_name'] ?? '');
$branch_address = htmlspecialchars($order['address'] ?? '');
$branch_city = htmlspecialchars($order['city'] ?? '');
$branch_state = htmlspecialchars($order['state'] ?? '');
$branch_country = htmlspecialchars($order['country'] ?? '');
$branch_logo = $order['logo'] ?? '';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Order #<?= $order_id ?> - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @page { margin: 5mm; size: auto; }
        body {
            font-family: 'Courier New', Courier, monospace;
            background: #fff;
            color: #000;
            margin: 0;
            padding: 10px;
            font-size: 11px;
            line-height: 1.4;
        }

        <?php if ($printer_type === 'Thermal'): ?>
            <?php if ($thermal_width === '2 inch'): ?>
                body, .container { width: 52mm; max-width: 52mm; font-size: 10px; }
            <?php else: ?>
                body, .container { width: 78mm; max-width: 78mm; }
            <?php endif; ?>
            .table { font-size: 10px; }
            h2 { font-size: 14px; }
            .logo-img { max-height: 25px; }
        <?php else: ?>
            body { width: 190mm; margin: 10mm auto; }
        <?php endif; ?>

        .container {
            border: 1px dashed #333;
            padding: 10px;
            margin: 10px auto;
            page-break-after: always;
            position: relative;
        }
        .header { text-align: center; margin-bottom: 10px; }
        .header h2 { margin: 5px 0; font-size: 16px; font-weight: bold; }
        .header p { margin: 2px 0; font-size: 10px; }
        .divider { border-top: 1px dashed #000; margin: 8px 0; }
        .table { width: 100%; border-collapse: collapse; margin: 8px 0; }
        .table th, .table td { padding: 3px 0; border-bottom: 1px dashed #ccc; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .total-row { font-weight: bold; font-size: 13px; border-top: 2px solid #000; }
        .gst-badge { font-size: 8px; padding: 2px 5px; border-radius: 3px; margin-left: 3px; }
        .logo-img { max-height: 35px; margin-bottom: 8px; }
        .admin-watermark {
            position: absolute;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 40px;
            color: #ddd;
            font-weight: bold;
            opacity: 0.3;
            pointer-events: none;
        }
        .branch-badge {
            background: #007bff;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 9px;
            margin-left: 5px;
        }
        .admin-info {
            background: #f8f9fa;
            border-left:;
            padding: 5px;
            margin: 5px 0;
            font-size: 9px;
        }
        .no-print { display: none; }
        @media print {
            body { padding: 0; margin: 0; background: white; }
            .container { border: none; page-break-after: always; }
            .admin-watermark { display: block; }
            .no-print { display: none; }
        }
    </style>
</head>
<body onload="window.print()">

<div class="admin-watermark">Thank You </div>

<!-- BILL -->
<?php if ($print_type === 'bill'): ?>
<div class="container">
    <!-- Admin Info -->
    <div class="admin-info">
        
    
    <div class="header">
        <?php if (!empty($branch_logo)): ?>
            <img src="../<?= htmlspecialchars($branch_logo) ?>" alt="Logo" class="logo-img">
        <?php endif; ?>
        <h2><?= $branch_name ?>
            <span class="branch-badge">Branch</span>
        </h2>
        <p><?= $branch_address ?></p>
        <p><?= "$branch_city, $branch_state, $branch_country" ?></p>
        <p><strong>Order #<?= $order_id ?></strong> | <?= date('d-m-Y h:i A', strtotime($order['order_date'])) ?></p>
        <p>Customer: <?= htmlspecialchars($order['customer_name'] ?: 'Walk-in') ?></p>
        <p>Contact: <?= htmlspecialchars($order['customer_contact']) ?></p>
        <?php if ($order['order_type'] === 'Dine In' && $order['table_number']): ?>
            <p>Table: <?= htmlspecialchars($order['table_number']) ?></p>
        <?php endif; ?>
        <?php if (!empty($order['notes'])): ?>
            <p><strong>Notes:</strong> <?= htmlspecialchars($order['notes']) ?></p>
        <?php endif; ?>
        <p><strong>*** REPRINT ***</strong></p>
    </div>

    <div class="divider"></div>

    <table class="table">
        <thead>
            <tr>
                <th>Item</th>
                <th>Qty</th>
                <th class="text-right">Price</th>
                <th class="text-right">Amount</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($order_items as $item): ?>
            <tr>
                <td>
                    <?= htmlspecialchars($item['food_name']) ?>
                    <?php if ($item['is_gst']): ?>
                        <span class="badge bg-success gst-badge">GST</span>
                    <?php endif; ?>
                </td>
                <td><?= $item['unit_display'] ?></td>
                <td class="text-right">₹<?= number_format($item['price_per_unit'], 2) ?></td>
                <td class="text-right">₹<?= number_format($item['subtotal'], 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="divider"></div>

    <table class="table">
        <tbody>
            <tr>
                <td>Subtotal</td>
                <td class="text-right">₹<?= number_format($subtotal, 2) ?></td>
            </tr>

            <?php if ($order['gst_active'] === '1'): ?>
                <?php if ($taxable_amount > 0): ?>
                <tr>
                    <td>Taxable Amount</td>
                    <td class="text-right">₹<?= number_format($taxable_amount, 2) ?></td>
                </tr>
                <?php endif; ?>

                <?php if (($order['cgst_amount'] ?? 0) > 0): ?>
                <tr>
                    <td>CGST @ <?= $order['cgst_rate'] ?? 0 ?>%</td>
                    <td class="text-right">₹<?= number_format($order['cgst_amount'] ?? 0, 2) ?></td>
                </tr>
                <?php endif; ?>

                <?php if (($order['sgst_amount'] ?? 0) > 0): ?>
                <tr>
                    <td>SGST @ <?= $order['sgst_rate'] ?? 0 ?>%</td>
                    <td class="text-right">₹<?= number_format($order['sgst_amount'] ?? 0, 2) ?></td>
                </tr>
                <?php endif; ?>

                <?php if ($total_gst > 0): ?>
                <tr>
                    <td><strong>Total GST</strong></td>
                    <td class="text-right"><strong>₹<?= number_format($total_gst, 2) ?></strong></td>
                </tr>
                <?php endif; ?>
            <?php else: ?>
                <tr>
                    <td>GST</td>
                    <td class="text-right">Not Applicable</td>
                </tr>
            <?php endif; ?>

            <?php if ($extra_charge > 0): ?>
            <tr>
                <td>Extra Charge</td>
                <td class="text-right">₹<?= number_format($extra_charge, 2) ?></td>
            </tr>
            <?php endif; ?>

            <tr class="total-row">
                <td><strong>GRAND TOTAL</strong></td>
                <td class="text-right"><strong>₹<?= number_format($grand_total, 2) ?></strong></td>
            </tr>

            <tr>
                <td>Payment Method</td>
                <td class="text-right"><?= htmlspecialchars($order['payment_method'] ?: 'Cash') ?></td>
            </tr>
            <tr>
                <td>Order Status</td>
                <td class="text-right"><?= htmlspecialchars(ucfirst($order['status'] ?? 'pending')) ?></td>
            </tr>
        </tbody>
    </table>

    <?php if ($order['gst_active'] === '1'): ?>
    <div class="gst-details text-center">
        <small>
            GST Summary:<br>
            GST Items: ₹<?= number_format($gst_items_total, 2) ?><br>
            Non-GST Items: ₹<?= number_format($non_gst_items_total, 2) ?>
        </small>
    </div>
    <?php endif; ?>

    <div class="text-center mt-3">
        <p><strong>*** Thank You ***</strong></p>
        <small>Printed by : <?= date('d-m-Y h:i:s A') ?></small>
    </div>
</div>
<?php endif; ?>

<!-- TOKEN -->
<?php if ($print_type === 'token'): ?>
<div class="container">
    <!-- Admin Info -->
    <div class="admin-info">
        <strong></strong> | Branch: <?= $branch_name ?>
    </div>
    
    <div class="header">
        <h2>TOKEN</h2>
        <p><?= $branch_name ?></p>
        <p><strong>Order #<?= $order_id ?></strong></p>
        <p><?= date('d-m-Y h:i A', strtotime($order['order_date'])) ?></p>
        <p>Customer: <?= htmlspecialchars($order['customer_name'] ?: 'Walk-in') ?></p>
        <?php if ($order['order_type'] === 'Dine In' && $order['table_number']): ?>
            <p>Table: <?= htmlspecialchars($order['table_number']) ?></p>
        <?php endif; ?>
        <p><strong>*** Thank You ***</strong></p>
    </div>

    <div class="divider"></div>

    <table class="table">
        <thead>
            <tr>
                <th>Item</th>
                <th class="text-center">Qty</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($order_items as $item): ?>
            <tr>
                <td><strong><?= htmlspecialchars($item['food_name']) ?></strong></td>
                <td class="text-center"><?= $item['unit_display'] ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="text-center mt-3">
        <p><strong></strong></p>
        <small>Branch: <?= $branch_name ?></small><br>
        <small>Printed: <?= date('d-m-Y h:i:s A') ?></small>
    </div>
</div>
<?php endif; ?>

<!-- Print Button (Screen Only) -->
<div class="no-print text-center my-4">
    <button onclick="window.print()" class="btn btn-success btn-lg">
        Print Now
    </button>
    <a href="orders.php?branch_id=<?= $branch_id ?>" class="btn btn-secondary btn-lg ms-3">
        Back to Orders
    </a>
    <a href="index.php" class="btn btn-primary btn-lg ms-3">
        Dashboard
    </a>
</div>

<script>
    window.onload = () => setTimeout(() => window.print(), 1000);
    window.onafterprint = () => window.location.href = 'orders.php?branch_id=<?= $branch_id ?>';
    setTimeout(() => {
        if (document.hasFocus()) window.location.href = 'orders.php?branch_id=<?= $branch_id ?>';
    }, 6000);
</script>

</body>
</html>