<?php
require_once __DIR__ . '/includes/header.php';

$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

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

// Fetch order details
try {
    $stmt = $pdo->prepare("SELECT o.*, u.full_name, u.email, u.address 
                            FROM orders o 
                            LEFT JOIN users u ON o.user_id = u.id 
                            WHERE o.id = ?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();
} catch (Exception $e) {
    $order = null;
}

if (!$order) {
    header("Location: shop.php");
    exit;
}

// Fetch order items
try {
    $stmt = $pdo->prepare("SELECT oi.*, p.name, p.image 
                            FROM order_items oi 
                            LEFT JOIN products p ON oi.product_id = p.id 
                            WHERE oi.order_id = ?");
    $stmt->execute([$order_id]);
    $order_items = $stmt->fetchAll();
} catch (Exception $e) {
    $order_items = [];
}
?>

<!-- Banner -->
<section class="py-5 bg-black border-bottom border-dark text-center">
    <div class="container py-3">
        <div class="display-1 text-warning mb-3"><i class="fa-solid fa-circle-check"></i></div>
        <h1 class="text-white fw-bold">Order Confirmed</h1>
        <p class="text-warning small text-uppercase fw-bold mb-0 mt-1" style="letter-spacing: 2px;">Thank you for your patronage</p>
    </div>
</section>

<!-- Success Details Section -->
<section class="py-5" style="background-color: var(--bg-dark); min-height: 60vh;">
    <div class="container" style="max-width: 800px;">
        
        <div class="card bg-black border-secondary text-white p-5 rounded-4 shadow" style="border-color: rgba(255,255,255,0.08) !important;">
            
            <div class="text-center mb-5">
                <h3 class="fw-bold mb-2" style="font-family: var(--font-heading);">Masterpiece Receipt</h3>
                <span class="badge bg-warning text-black py-2 px-3 fw-bold rounded-pill">Order Reference: #MNDIRECT-<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></span>
            </div>

            <!-- Client Info Grid -->
            <div class="row g-4 mb-5 border border-secondary p-4 rounded bg-dark small">
                <div class="col-md-6">
                    <span class="text-muted d-block small text-uppercase">Patron Details:</span>
                    <strong class="text-white d-block mt-1"><?php echo htmlspecialchars($order['full_name']); ?></strong>
                    <span class="text-muted"><?php echo htmlspecialchars($order['email']); ?></span>
                </div>
                <div class="col-md-6">
                    <span class="text-muted d-block small text-uppercase">Atelier Destination:</span>
                    <strong class="text-white d-block mt-1"><?php echo htmlspecialchars($order['address']); ?></strong>
                    <span class="text-warning">White-Glove Priority Dispatch</span>
                </div>
                <div class="col-md-6 mt-3">
                    <span class="text-muted d-block small text-uppercase">Payment Gateway:</span>
                    <strong class="text-white"><?php echo htmlspecialchars($order['payment_method']); ?></strong>
                </div>
                <div class="col-md-6 mt-3">
                    <span class="text-muted d-block small text-uppercase">Fulfillment Status:</span>
                    <strong class="text-warning">Processing Order</strong>
                </div>
            </div>

            <!-- Items Table -->
            <h5 class="fw-bold mb-3" style="font-family: var(--font-heading); color: var(--accent-gold);">Curated Selections</h5>
            <div class="table-responsive mb-5">
                <table class="table table-dark align-middle border-secondary m-0">
                    <thead>
                        <tr class="text-uppercase small text-muted border-secondary" style="font-size: 0.75rem; letter-spacing: 1px;">
                            <th scope="col" style="background: transparent;">Item</th>
                            <th scope="col" class="text-center" style="background: transparent;">Quantity</th>
                            <th scope="col" class="text-end" style="background: transparent;">Price</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($order_items as $item): ?>
                            <tr class="border-secondary">
                                <td style="background: transparent;">
                                    <div class="d-flex align-items-center gap-3">
                                        <img src="assets/images/<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" class="rounded" style="width: 50px; height: 50px; object-fit: cover; border: 1px solid rgba(255,255,255,0.1);">
                                        <div>
                                            <strong class="text-white fs-7 d-block"><?php echo htmlspecialchars($item['name']); ?></strong>
                                            <?php if (!empty($item['size']) || !empty($item['color'])): ?>
                                                <span class="text-muted" style="font-size: 0.7rem;">
                                                    <?php if (!empty($item['size'])): ?>Size: <strong class="text-white"><?php echo htmlspecialchars($item['size']); ?></strong><?php endif; ?>
                                                    <?php if (!empty($item['size']) && !empty($item['color'])): ?> | <?php endif; ?>
                                                    <?php if (!empty($item['color'])): ?>Color: <strong class="text-white"><?php echo htmlspecialchars($item['color']); ?></strong><?php endif; ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-center" style="background: transparent;"><?php echo $item['quantity']; ?></td>
                                <td class="text-end" style="background: transparent;">LKR <?php echo number_format($item['price'] * $item['quantity'], 2); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        
                        <!-- Totals -->
                        <tr class="border-0">
                            <td colspan="2" class="text-end border-0 pt-4 text-muted small" style="background: transparent;">Grand Total Paid:</td>
                            <td class="text-end border-0 pt-4 text-warning fw-bold fs-5" style="background: transparent;">LKR <?php echo number_format($order['total_amount'], 2); ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <?php
            // Build WhatsApp message
            $wa_number = '94764146054'; // Store WhatsApp number
            $msg = "🛍 *New Order - MNDIRECT-" . str_pad($order['id'], 6, '0', STR_PAD_LEFT) . "*\n";
            $msg .= "─────────────────────\n";
            $msg .= "*Customer:* {$order['full_name']}\n";
            $msg .= "*Email:* {$order['email']}\n";
            
            $msg .= "*Address:* {$order['address']}\n";
            $msg .= "*Payment:* {$order['payment_method']}\n";
            $msg .= "─────────────────────\n";
            $msg .= "*Items:*\n";
            foreach ($order_items as $item) {
                $msg .= "• {$item['name']} x{$item['quantity']}";
                if (!empty($item['size']) || !empty($item['color'])) {
                    $parts = [];
                    if (!empty($item['size'])) $parts[] = "Size: {$item['size']}";
                    if (!empty($item['color'])) $parts[] = "Color: {$item['color']}";
                    $msg .= " (" . implode(', ', $parts) . ")";
                }
                $msg .= " = LKR " . number_format($item['price'] * $item['quantity'], 2) . "\n";
            }
            $msg .= "─────────────────────\n";
            $msg .= "*Total:* LKR " . number_format($order['total_amount'], 2) . "\n";
            $msg .= "─────────────────────\n";
            $msg .= "_Order placed via MARTLUX Atelier_";
            $wa_url = "https://wa.me/{$wa_number}?text=" . urlencode($msg);
            ?>

            <!-- WhatsApp Auto redirect -->
            <div class="alert alert-success text-center p-4 mb-4 rounded-4 border-success" style="background-color: rgba(37, 211, 102, 0.1);">
                <i class="fa-brands fa-whatsapp text-success display-6 mb-2 d-block"></i>
                <h5 class="text-white mb-1">Redirecting to WhatsApp...</h5>
                <p class="text-muted small mb-0">Please tap <strong class="text-white">Send</strong> on WhatsApp to confirm your order.<br>
                Redirecting in <strong id="wa-countdown" class="text-warning">3</strong> seconds.</p>
            </div>

            <!-- WhatsApp CTA fallback -->
            <div class="text-center mb-3">
                <a href="<?php echo $wa_url; ?>" target="_blank" class="btn btn-success rounded-pill px-5 py-3 fw-bold text-uppercase fs-7" style="letter-spacing: 1px; background-color: #25D366; border-color: #25D366;" id="wa-button">
                    <i class="fa-brands fa-whatsapp me-2"></i> Send Order to WhatsApp
                </a>
            </div>

            <script>
            // Auto-redirect to WhatsApp after 3 seconds
            var seconds = 3;
            var countdown = document.getElementById('wa-countdown');
            var timer = setInterval(function() {
                seconds--;
                if (countdown) countdown.textContent = seconds;
                if (seconds <= 0) {
                    clearInterval(timer);
                    window.location.href = '<?php echo $wa_url; ?>';
                }
            }, 1000);
            </script>

            <!-- Go back CTA -->
            <div class="text-center">
                <a href="shop.php" class="btn btn-warning rounded-pill px-5 py-3 fw-bold text-uppercase fs-7 text-black" style="letter-spacing: 1px;">
                    Return to Atelier Catalog
                </a>
            </div>

        </div>

    </div>
</section>

<?php
require_once __DIR__ . '/includes/footer.php';
?>
