<?php
// checkout.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/facebook-pixel.php'; // Add this line

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: login.php?redirect=checkout.php');
    exit;
}

// Get cart items
$cart_items = getCartItems();

// If cart is empty, redirect to cart page
if (empty($cart_items)) {
    header('Location: cart.php');
    exit;
}

// ========================================
// TRACK INITIATE CHECKOUT EVENT
// ========================================
if (!empty(FACEBOOK_PIXEL_ID) && !empty($cart_items)) {
    $checkout_data = [
        'currency' => 'BDT',
        'value' => getCartTotal(),
        'num_items' => getCartCount(),
        'contents' => []
    ];
    
    foreach ($cart_items as $item) {
        $checkout_data['contents'][] = [
            'id' => $item['product_id'],
            'quantity' => $item['quantity'],
            'item_price' => $item['price']
        ];
    }
    
    $user_data = [
        'url' => (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
    ];
    
    trackFacebookEvent('InitiateCheckout', $checkout_data, $user_data);
}

// Calculate totals
$subtotal = getCartTotal();
$shipping_charge = floatval(getSetting($pdo, 'shipping_charge') ?: 70);
$discount = 0;
$total = $subtotal + $shipping_charge - $discount;

// Get user data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

// Get delivery charges
$delivery_charges = [
    ['id' => 1, 'name' => 'In Dhaka City', 'charge' => 70],
    ['id' => 2, 'name' => 'Saver, Keranigonj, Gazipur & Narayanganj', 'charge' => 100],
    ['id' => 3, 'name' => 'Other Districts', 'charge' => 120]
];

include __DIR__ . '/includes/header.php';
?>
<!-- Rest of checkout.php content -->

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="text-center">
                <div class="success-icon">
                    <i class="fa-solid fa-check"></i>
                </div>
                <h2 class="mt-3">Order Placed Successfully!</h2>
                <p class="text-muted">Thank you for your order. We'll process it soon.</p>
                
                <div class="order-details-card mt-4 text-start">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>Invoice No:</strong> <?php echo $order['invoice_no']; ?></p>
                            <p><strong>Date:</strong> <?php echo date('d M Y, h:i A', strtotime($order['created_at'])); ?></p>
                            <p><strong>Payment Method:</strong> <?php echo strtoupper($order['payment_method']); ?></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>Status:</strong> <span class="badge bg-warning"><?php echo ucfirst($order['order_status']); ?></span></p>
                            <p><strong>Total:</strong> <?php echo number_format($order['total']); ?> TK</p>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <h6>Order Items</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Qty</th>
                                    <th>Price</th>
                                    <th>Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($order_items as $item): ?>
                                <tr>
                                    <td><?php echo $item['product_name']; ?></td>
                                    <td><?php echo $item['quantity']; ?></td>
                                    <td><?php echo number_format($item['price']); ?> TK</td>
                                    <td><?php echo number_format($item['total']); ?> TK</td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="3" class="text-end"><strong>Total</strong></td>
                                    <td><strong><?php echo number_format($order['total']); ?> TK</strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    
                    <div class="mt-3">
                        <a href="profile.php" class="btn btn-primary">View My Orders</a>
                        <a href="index.php" class="btn btn-secondary">Continue Shopping</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.success-icon {
    width: 80px;
    height: 80px;
    background: #22c55e;
    color: #fff;
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
}

.order-details-card {
    background: #fff;
    padding: 30px;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
}
</style>

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