<?php
session_start();
require_once __DIR__ . '/includes/config.php';

// Redirect if cart is empty
if (empty($_SESSION['cart'])) {
    header("Location: cart.php");
    exit();
}

// Process checkout form
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate and sanitize input
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $notes = trim($_POST['notes']);
    
    // Calculate total
    $total = 0;
    foreach ($_SESSION['cart'] as $item) {
        // Get price from database (should be cached in real implementation)
        $price = $item['variant_id'] 
            ? getVariantPrice($conn, $item['variant_id'])
            : getProductPrice($conn, $item['product_id']);
        $total += $price * $item['quantity'];
    }
    
    // Insert customer
    $customer_sql = "INSERT INTO customers (name, email, phone, address) 
                    VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($customer_sql);
    $stmt->bind_param("ssss", $name, $email, $phone, $address);
    $stmt->execute();
    $customer_id = $stmt->insert_id;
    
    // Insert order
    $order_sql = "INSERT INTO orders (customer_id, total_amount, delivery_address, notes)
                 VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($order_sql);
    $stmt->bind_param("idss", $customer_id, $total, $address, $notes);
    $stmt->execute();
    $order_id = $stmt->insert_id;
    
    // Insert order items
    foreach ($_SESSION['cart'] as $item) {
        $price = $item['variant_id'] 
            ? getVariantPrice($conn, $item['variant_id'])
            : getProductPrice($conn, $item['product_id']);
        
        $item_sql = "INSERT INTO order_items (order_id, product_id, variant_id, quantity, price)
                    VALUES (?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($item_sql);
        $stmt->bind_param("iiiid", $order_id, $item['product_id'], $item['variant_id'], 
                         $item['quantity'], $price);
        $stmt->execute();
    }
    
    // Clear cart
    unset($_SESSION['cart']);
    
    // Redirect to thank you page
    header("Location: thank_you.php?order_id=$order_id");
    exit();
}

// Helper functions
function getProductPrice($conn, $product_id) {
    $sql = "SELECT base_price FROM products WHERE product_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $product_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $product = $result->fetch_assoc();
    return $product['base_price'];
}

function getVariantPrice($conn, $variant_id) {
    $sql = "SELECT price FROM product_variants WHERE variant_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $variant_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $variant = $result->fetch_assoc();
    return $variant['price'];
}

$pageTitle = 'Checkout';
require_once __DIR__ . '/includes/header.php';
?>

<main class="checkout-page">
    <div class="container">
        <div class="checkout-grid">
            <div class="checkout-form">
                <h2>Customer Information</h2>
                <form action="checkout.php" method="post">
                    <div class="form-group">
                        <label for="name">Full Name</label>
                        <input type="text" id="name" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" id="email" name="email" required>
                    </div>
                    <div class="form-group">
                        <label for="phone">Phone Number</label>
                        <input type="tel" id="phone" name="phone" required>
                    </div>
                    <div class="form-group">
                        <label for="address">Delivery Address</label>
                        <textarea id="address" name="address" rows="3" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="notes">Order Notes (Optional)</label>
                        <textarea id="notes" name="notes" rows="3"></textarea>
                    </div>
                    <button type="submit" class="btn btn-large">Complete Order</button>
                </form>
            </div>
            
            <div class="order-summary">
                <h2>Your Order</h2>
                <div class="summary-items">
                    <?php 
                    $total = 0;
                    foreach ($_SESSION['cart'] as $item): 
                        // Get product details (should be cached in real implementation)
                        $product_sql = "SELECT name, base_price FROM products WHERE product_id = ?";
                        $stmt = $conn->prepare($product_sql);
                        $stmt->bind_param("i", $item['product_id']);
                        $stmt->execute();
                        $product_result = $stmt->get_result();
                        $product = $product_result->fetch_assoc();
                        
                        // Get variant details if exists
                        $variant_name = '';
                        $price = $product['base_price'];
                        
                        if ($item['variant_id']) {
                            $variant_sql = "SELECT variant_name, price FROM product_variants WHERE variant_id = ?";
                            $stmt = $conn->prepare($variant_sql);
                            $stmt->bind_param("i", $item['variant_id']);
                            $stmt->execute();
                            $variant_result = $stmt->get_result();
                            $variant = $variant_result->fetch_assoc();
                            
                            if ($variant) {
                                $variant_name = $variant['variant_name'];
                                $price = $variant['price'];
                            }
                        }
                        
                        $subtotal = $price * $item['quantity'];
                        $total += $subtotal;
                    ?>
                    <div class="summary-item">
                        <div class="item-name">
                            <?php echo htmlspecialchars($product['name']); ?>
                            <?php if ($variant_name): ?>
                                <span>(<?php echo htmlspecialchars($variant_name); ?>)</span>
                            <?php endif; ?>
                            <span class="item-qty">× <?php echo $item['quantity']; ?></span>
                        </div>
                        <div class="item-price">KShs <?php echo number_format($subtotal, 2); ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="summary-total">
                    <div class="total-row">
                        <span>Subtotal</span>
                        <span>KShs <?php echo number_format($total, 2); ?></span>
                    </div>
                    <div class="total-row">
                        <span>Delivery</span>
                        <span>FREE</span>
                    </div>
                    <div class="total-row grand-total">
                        <span>Total</span>
                        <span>KShs <?php echo number_format($total, 2); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

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