<?php
require_once __DIR__ . "/config.inc.php";

$orderId = (int)($_GET['order_id'] ?? 0);

if ($orderId <= 0) {
    header("Location: index.php");
    exit;
}

$db = db();

/*
|--------------------------------------------------------------------------
| 1. Fetch Order Details (+ User info if available)
|--------------------------------------------------------------------------
*/
$stmtOrder = $db->prepare("
    SELECT 
        o.id AS order_id,
        o.total_amount,
        o.status,
        o.created_at,
        u.full_name,
        u.email,
        u.phone,
        u.address
    FROM orders o
    LEFT JOIN users u ON u.id = o.user_id
    WHERE o.id = ?
");

$stmtOrder->bind_param("i", $orderId);
$stmtOrder->execute();
$order = $stmtOrder->get_result()->fetch_assoc();
$stmtOrder->close();

if (!$order) {
    require_once __DIR__ . "/partials/header.php";
    echo '
    <div class="container py-5 text-center">
        <div class="alert alert-danger d-inline-block px-4 py-3">
            <h4 class="alert-heading">Order Not Found</h4> 
            <p class="mb-0">The requested order ID does not exist or has been removed.</p>
        </div>
        <div class="mt-3">
            <a href="index.php" class="btn btn-primary">Back to Search</a>
        </div>
    </div>';
    require_once __DIR__ . "/partials/footer.php";
    exit;
}

/*
|--------------------------------------------------------------------------
| 2. Fetch Order Items
|--------------------------------------------------------------------------
*/
$stmtItems = $db->prepare("
    SELECT 
        oi.quantity,
        oi.unit_price,
        oi.subtotal,
        oi.phone_model,
        p.display_model,
        p.image_path,
        pb.name AS product_brand_name,
        dt.name AS display_type_name,
        sb.name AS searched_brand_name
    FROM order_items oi
    JOIN products p ON p.id = oi.product_id
    JOIN brands pb ON pb.id = p.brand_id
    JOIN display_types dt ON dt.id = oi.display_type_id
    LEFT JOIN brands sb ON sb.id = oi.phone_brand_id
    WHERE oi.order_id = ?
");

$stmtItems->bind_param("i", $orderId);
$stmtItems->execute();
$resItems = $stmtItems->get_result();

$items = [];
while ($row = $resItems->fetch_assoc()) {
    $items[] = $row;
}
$stmtItems->close();

require_once __DIR__ . "/partials/header.php";
?>

<div class="container py-4">

    <!-- Action Bar (Print & Return) -->
    <div class="d-flex justify-content-between align-items-center mb-4 d-print-none">
        <a href="index.php" class="btn btn-outline-secondary">
            &larr; Back to Display Search 
        </a>
        <button onclick="window.print()" class="btn btn-dark">
            🖨️ Print Receipt
        </button>
    </div>

    <div class="card shadow-sm border-0">
        
        <!-- Header Banner -->
        <div class="card-header bg-success text-white text-center py-4">
            <div class="display-6 fw-bold mb-1">
                ✓ Order Confirmed!
            </div>
            <p class="mb-0 fs-6 opacity-75">
                Thank you for your order. Your transaction was processed successfully.
            </p>
        </div>

        <div class="card-body p-4">

            <!-- Order & Customer Summary -->
            <div class="row g-3 mb-4">
                
                <div class="col-md-6">
                    <div class="p-3 bg-light rounded border h-100">
                        <h6 class="fw-bold text-uppercase text-muted small mb-2">Order Information</h6>
                        <div><strong>Order ID:</strong> #<?= sprintf('%06d', $order['order_id']) ?></div>
                        <div><strong>Date & Time:</strong> <?= date("F j, Y - g:i A", strtotime($order['created_at'])) ?></div>
                        <div>
                            <strong>Status:</strong> 
                            <span class="badge bg-warning text-dark text-capitalize"><?= e($order['status']) ?></span>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="p-3 bg-light rounded border h-100">
                        <h6 class="fw-bold text-uppercase text-muted small mb-2">Customer Details</h6>
                        <?php if (!empty($order['full_name'])): ?>
                            <div><strong>Name:</strong> <?= e($order['full_name']) ?></div>
                            <div><strong>Phone:</strong> <?= e($order['phone']) ?></div>
                            <div><strong>Email:</strong> <?= e($order['email']) ?></div>
                            <div><strong>Address:</strong> <?= e($order['address']) ?></div>
                        <?php else: ?>
                            <div class="text-muted small">Guest Order / Walk-in Customer</div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <!-- Items Table -->
            <h5 class="fw-bold mb-3">Order Summary</h5>

            <div class="table-responsive mb-4">
                <table class="table table-bordered align-middle">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 60px;" class="text-center">#</th>
                            <th>Item Description</th>
                            <th>Display Quality</th>
                            <th class="text-center" style="width: 100px;">Qty</th>
                            <th class="text-end" style="width: 140px;">Unit Price</th>
                            <th class="text-end" style="width: 140px;">Subtotal</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($items as $idx => $item): ?>
                            <tr>
                                <td class="text-center text-muted"><?= $idx + 1 ?></td>
                                <td>
                                    <div class="fw-bold">
                                        <?= e($item['product_brand_name']) ?> - <?= e($item['display_model']) ?>
                                    </div>
                                    <?php if (!empty($item['phone_model'])): ?>
                                        <div class="text-muted small">
                                            Model: <?= e($item['searched_brand_name'] ?? '') ?> <?= e($item['phone_model']) ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-info text-dark">
                                        <?= e($item['display_type_name']) ?>
                                    </span>
                                </td>
                                <td class="text-center fw-semibold">
                                    <?= (int)$item['quantity'] ?>
                                </td>
                                <td class="text-end">
                                    Rs. <?= number_format((float)$item['unit_price'], 2) ?>
                                </td>
                                <td class="text-end fw-semibold">
                                    Rs. <?= number_format((float)$item['subtotal'], 2) ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot class="table-group-divider">
                        <tr>
                            <td colspan="5" class="text-end fw-bold fs-5">Grand Total:</td>
                            <td class="text-end fw-bold fs-5 text-success">
                                Rs. <?= number_format((float)$order['total_amount'], 2) ?>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <!-- Info Alert -->
            <div class="alert alert-info d-flex align-items-center mb-0 d-print-none" role="alert">
                <div class="fs-4 me-3">ℹ️</div>
                <div>
                    An admin confirmation email has been dispatched for processing. Please retain order reference <strong>#<?= sprintf('%06d', $order['order_id']) ?></strong> for inquiries.
                </div>
            </div>

        </div>

    </div>

</div>

<!-- CSS Adjustments for Printing -->
<style>
@media print {
    .navbar, footer, .d-print-none {
        display: none !important;
    }
    .card {
        border: none !important;
        box-shadow: none !important;
    }
    body {
        background: #fff !important;
    }
}
</style>

<?php
require_once __DIR__ . "/partials/footer.php";
?>