<?php
/**
 * Booking Confirmation Page - FIXED ORDER ID
 * File: booking-confirmation.php (ROOT)
 */

require_once 'app/Core/init.php';

// Must be logged in as customer
if (!Auth::check() || Auth::userType() !== 'customer') {
    redirect('auth/login.php');
}

$order_number = $_GET['order'] ?? '';

if (!$order_number) {
    redirect('index.php');
}

try {
    $db = Database::getInstance();
    
    // Get order details
    $sql = "SELECT o.*, 
            i.title as item_title, i.main_image as item_image, i.slug as item_slug,
            i.price_per_day as daily_rate,
            CONCAT(c.first_name, ' ', c.last_name) as customer_name,
            c.phone as customer_phone, u_c.email as customer_email,
            v.business_name as vendor_name, v.phone as vendor_phone,
            u_v.email as vendor_email,
            -- p.payment_gateway, p.transaction_reference, p.paid_at
            FROM orders o
            JOIN items i ON o.item_id = i.id
            JOIN customers c ON o.customer_id = c.id
            JOIN users u_c ON c.user_id = u_c.id
            JOIN vendors v ON o.vendor_id = v.id
            JOIN users u_v ON v.user_id = u_v.id
            -- LEFT JOIN payments p ON o.id = p.order_id
            WHERE o.order_number = ?
            AND o.customer_id = (SELECT id FROM customers WHERE user_id = ?)
            LIMIT 1";
    
    $order = $db->fetch($sql, [$order_number, Auth::user()['id']]);
    
    if (!$order) {
        redirect('index.php');
    }
    
    // Check if emails should be sent
    $shouldSendEmails = isset($_SESSION['send_order_emails']) 
                       && $_SESSION['send_order_emails']['order_id'] == $order['id'];
    
    if ($shouldSendEmails) {
        unset($_SESSION['send_order_emails']);
    }
    
    $page_title = 'Booking Confirmed - ' . APP_NAME;
    
} catch (Exception $e) {
    error_log("Booking confirmation error: " . $e->getMessage());
    redirect('index.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/plugins/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-10 col-lg-8">
                <!-- Success Message -->
                <div class="text-center mb-4">
                    <div class="bg-success bg-opacity-10 rounded-circle d-inline-flex p-4 mb-3">
                        <i class="fas fa-check-circle fa-4x text-success"></i>
                    </div>
                    <h1 class="display-5 fw-bold text-success mb-2">Booking Confirmed!</h1>
                    <p class="lead text-muted">Your order has been confirmed and payment received.</p>
                </div>
                
                <!-- Order Details Card -->
                <div class="card border-0 shadow-lg rounded-4 mb-4">
                    <div class="card-body p-4 p-md-5">
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <h4 class="mb-3"><u>ORDER DETAILS</u></h4>
                                <div class="mb-2">
                                    <strong>Order Number:</strong><br>
                                    <span class="fs-5 text-primary"><?= $order['order_number'] ?></span>
                                </div>
                                <div class="mb-2">
                                    <strong>Order Date:</strong><br>
                                    <?= date('F j, Y g:i A', strtotime($order['created_at'])) ?>
                                </div>
                                <div class="mb-2">
                                    <strong>Payment Status:</strong><br>
                                    <span class="badge bg-success">Paid</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h4 class="mb-3"><u>PAYMENT INFORMATION</u></h4>
                                <div class="mb-2">
                                    <strong>Payment Method:</strong><br>
                                    <?= ucfirst($order['payment_gateway']) ?>
                                </div>
                                <div class="mb-2">
                                    <strong>Transaction Ref:</strong><br>
                                    <small class="text-muted"><?= $order['transaction_reference'] ?></small>
                                </div>
                                <div class="mb-2">
                                    <strong>Paid At:</strong><br>
                                    <?= date('F j, Y g:i A', strtotime($order['paid_at'])) ?>
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <!-- Item Details -->
                        <h5 class="mb-3">Item Booked</h5>
                        <div class="row align-items-center mb-4">
                            <div class="col-md-3">
                                <img src="<?= upload('items/' . $order['item_image']); ?>" alt="<?= htmlspecialchars($order['item_title']) ?>" class="img-fluid rounded-3">
                            </div>
                            <div class="col-md-9">
                                <h6 class="mb-2"><?= htmlspecialchars($order['item_title']) ?></h6>
                                <div class="row">
                                    <div class="col-sm-6 mb-2">
                                        <small class="text-muted">Rental Period:</small><br>
                                        <strong><?= date('M j', strtotime($order['start_date'])) ?> - <?= date('M j, Y', strtotime($order['end_date'])) ?></strong>
                                    </div>
                                    <div class="col-sm-6 mb-2">
                                        <small class="text-muted">Duration:</small><br>
                                        <strong><?= $order['rental_days'] ?> day<?= $order['rental_days'] > 1 ? 's' : '' ?></strong>
                                    </div>
                                    <div class="col-sm-6 mb-2">
                                        <small class="text-muted">Quantity:</small><br>
                                        <strong><?= $order['quantity'] ?> item<?= $order['quantity'] > 1 ? 's' : '' ?></strong>
                                    </div>
                                    <div class="col-sm-6 mb-2">
                                        <small class="text-muted">Vendor:</small><br>
                                        <strong><?= htmlspecialchars($order['vendor_name']) ?></strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <!-- Price Breakdown -->
                        <h5 class="mb-3">Price Breakdown</h5>
                        <div class="bg-light rounded-3 p-3">
                            <div class="d-flex justify-content-between mb-2">
                                <span>Subtotal:</span>
                                <span>₦<?= number_format($order['subtotal'], 2) ?></span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span>Security Deposit:</span>
                                <span>₦<?= number_format($order['security_deposit'], 2) ?></span>
                            </div>
                            <hr class="my-2">
                            <div class="d-flex justify-content-between fs-5 fw-bold text-success">
                                <span>Total Paid:</span>
                                <span>₦<?= number_format($order['total_amount'], 2) ?></span>
                            </div>
                        </div>
                        
                        <div class="alert alert-info mt-3 mb-0">
                            <i class="fas fa-info-circle"></i> 
                            <strong>Security Deposit:</strong> ₦<?= number_format($order['security_deposit'], 2) ?> will be refunded after you return the item in good condition.
                        </div>
                    </div>
                </div>

                <!-- Next Steps -->
                <div class="card border-0 bg-light mt-4">
                    <div class="card-body p-4">
                        <h6 class="fw-bold mb-3"><i class="fas fa-clipboard-check me-2"></i>What's Next?</h6>
                        <ol class="mb-0">
                            <li class="mb-2">You will receive a confirmation email shortly</li>
                            <li class="mb-2">The vendor will contact you to arrange pickup/delivery</li>
                            <li class="mb-2">Pick up the item on <strong><?= date('F j, Y', strtotime($order['start_date'])) ?></strong></li>
                            <li class="mb-2">Return the item by <strong><?= date('F j, Y', strtotime($order['end_date'])) ?></strong></li>
                            <li>Your security deposit will be refunded within 1-3 days after return, if there's no issue.</li>
                        </ol>
                    </div>
                </div>

                <br>
                
                <!-- Action Buttons -->
                <div class="row g-3">
                    <div class="col-md-4">
                        <a href="customer/orders.php" class="btn btn-primary w-100">
                            <i class="fas fa-list me-2"></i>View All Bookings
                        </a>
                    </div>
                    <div class="col-md-4">
                        <a href="item-details.php?slug=<?= $order['item_slug'] ?>" class="btn btn-outline-primary w-100">
                            <i class="fas fa-eye me-2"></i>View Item
                        </a>
                    </div>
                    <div class="col-md-4">
                        <a href="items.php" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-home me-2"></i>Continue Shopping
                        </a>
                    </div>
                </div>
                
            </div>
        </div>
    </div>
    
    <?php if ($shouldSendEmails): ?>
    <!-- Send emails asynchronously AFTER page loads -->
    <script>
    // FIXED: Use numeric order ID, not order_number
    fetch('send-order-emails.php?order_id=<?= $order['id'] ?>')
        .then(response => response.json())
        .then(data => {
            console.log('Email results:', data);
            if (data.success) {
                console.log('✓ All emails processed');
            } else {
                console.error('✗ Email error:', data.message);
            }
        })
        .catch(error => console.error('✗ Email request failed:', error));
    </script>
    <?php endif; ?>
</body>
</html>