<?php
session_start();
require 'config/db.php';
require_once 'includes/functions.php';
include 'includes/header.php';

$order = null;
$error = "";

if (isset($_POST['track_order'])) {
    $order_id = trim($_POST['order_id']);
    $email = trim($_POST['email']);

    // Fetch Order (Must match ID and Email for security)
    // We join users table to check email if it was a registered user, 
    // OR check the order's stored email (if you saved it directly in orders table, which we should have)
    // In your current DB, email is in 'users' table, so we join.
    
    $stmt = $pdo->prepare("
        SELECT o.*, u.name, u.email, u.phone 
        FROM orders o 
        JOIN users u ON o.user_id = u.id 
        WHERE o.id = ? AND u.email = ?
    ");
    $stmt->execute([$order_id, $email]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($order) {
        // Fetch Items
        $iStmt = $pdo->prepare("
            SELECT p.name, v.name as variant 
            FROM order_items oi 
            JOIN products p ON oi.product_id = p.id 
            JOIN product_variants v ON oi.variant_id = v.id 
            WHERE oi.order_id = ?
        ");
        $iStmt->execute([$order_id]);
        $items = $iStmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $error = "Order not found or email does not match.";
    }
}
?>

<style>
    .track-container { max-width: 600px; margin: 50px auto; background: white; padding: 40px; border-radius: 12px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); border: 1px solid #eee; }
    .track-header { text-align: center; margin-bottom: 30px; }
    .track-header i { font-size: 50px; color: #3498db; margin-bottom: 10px; }
    .input-group { margin-bottom: 20px; }
    .input-group label { display: block; font-weight: bold; margin-bottom: 8px; color: #555; }
    .form-control { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; }
    
    /* Result Box */
    .result-box { background: #f9f9f9; border-radius: 8px; padding: 20px; border-left: 5px solid #ccc; margin-top: 20px; }
    .result-box.completed { border-left-color: #2ecc71; background: #f0f9eb; }
    .result-box.processing { border-left-color: #3498db; background: #f0f8ff; }
    .result-box.pending { border-left-color: #f1c40f; background: #fffcf5; }
    
    .key-area { background: #333; color: #0f0; font-family: monospace; padding: 15px; border-radius: 5px; margin-top: 15px; word-break: break-all; }
</style>

<div class="container" style="min-height: 70vh;">
    
    <?php if(!$order): ?>
    <div class="track-container">
        <div class="track-header">
            <i class="fas fa-search-location"></i>
            <h1>Track Your Order</h1>
            <p style="color: #777;">Enter your order details to get instant status and license keys.</p>
        </div>

        <?php if($error): ?>
            <div style="background: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin-bottom: 20px; text-align: center;">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <form method="POST">
            <div class="input-group">
                <label>Order ID</label>
                <input type="text" name="order_id" placeholder="e.g. 105" required class="form-control">
            </div>
            <div class="input-group">
                <label>Email Address</label>
                <input type="email" name="email" placeholder="Email used at checkout" required class="form-control">
            </div>
            <button type="submit" name="track_order" class="btn btn-primary" style="width: 100%; padding: 12px; font-size: 16px;">Track Now</button>
        </form>
    </div>

    <?php else: ?>
    <div class="track-container" style="max-width: 800px;">
        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #eee; padding-bottom: 20px; margin-bottom: 20px;">
            <h2 style="margin: 0;">Order #<?php echo $order['id']; ?></h2>
            <a href="track.php" style="color: #777; text-decoration: none;">&times; Close</a>
        </div>

        <div class="result-box <?php echo $order['status']; ?>">
            <div style="display: flex; justify-content: space-between;">
                <div>
                    <strong>Status:</strong> 
                    <span style="text-transform: uppercase; font-weight: bold; color: <?php echo ($order['status']=='completed'?'#27ae60':($order['status']=='pending'?'#f39c12':'#3498db')); ?>">
                        <?php echo $order['status']; ?>
                    </span>
                </div>
                <div>
                    <strong>Total:</strong> <?php echo convertPrice($order['total_amount']); ?>
                </div>
            </div>
            <p style="margin-top: 10px; color: #555;">Date: <?php echo date('d M Y', strtotime($order['created_at'])); ?></p>
        </div>

        <h3 style="margin-top: 30px;">Items</h3>
        <ul style="padding-left: 20px; color: #555;">
            <?php foreach($items as $item): ?>
                <li><?php echo htmlspecialchars($item['name']) . " (" . htmlspecialchars($item['variant']) . ")"; ?></li>
            <?php endforeach; ?>
        </ul>

        <?php if($order['status'] == 'completed' && !empty($order['user_note'])): ?>
            <h3 style="margin-top: 30px;">Access Details / License Key</h3>
            <div class="key-area">
                <?php echo nl2br(htmlspecialchars($order['user_note'])); ?>
            </div>
        <?php endif; ?>

        <?php if($order['status'] == 'completed'): ?>
            <div style="margin-top: 30px; text-align: center;">
                <a href="invoice.php?id=<?php echo $order['id']; ?>" target="_blank" class="btn btn-buy" style="background: #27ae60; display: inline-block; width: auto; padding: 10px 30px;">
                    <i class="fas fa-download"></i> Download Invoice
                </a>
            </div>
        <?php endif; ?>

    </div>
    <?php endif; ?>

</div>

<?php include 'includes/footer.php'; ?>