<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include "config/db.php";

/* Login protection */
if (!isset($_SESSION['user_id'])) {
    header("Location: /shopnest/user/login.php");
    exit();
}

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

// Get user details
$user_id = $_SESSION['user_id'];

// Calculate totals
$subtotal = 0;
foreach ($_SESSION['cart'] as $item) {
    $item_total = $item['price'] * $item['qty'];
    $subtotal += $item_total;
}

// Add delivery charge and tax
$delivery_charge = 99;
$tax = $subtotal * 0.18;
$total_payable = $subtotal + $delivery_charge + $tax;

/* Place Order - SIMPLE VERSION */
if (isset($_POST['place_order'])) {
    // Simple insert without additional columns
    $order_query = "INSERT INTO orders (user_id, total_price) 
                    VALUES ('$user_id', '$total_payable')";
    
    if (mysqli_query($conn, $order_query)) {
        $order_id = mysqli_insert_id($conn);

        // Insert order items
        foreach ($_SESSION['cart'] as $item) {
            $product_id = $item['id'];
            $product_name = mysqli_real_escape_string($conn, $item['name']);
            $price = $item['price'];
            $quantity = $item['qty'];

            mysqli_query($conn,
                "INSERT INTO order_items (order_id, product_id, product_name, price, quantity) 
                 VALUES ('$order_id', '$product_id', '$product_name', '$price', '$quantity')"
            );
            
            // Update product stock
            mysqli_query($conn, "UPDATE products SET stock = stock - 1 WHERE id = '$product_id'");
        }

        // Clear cart
        unset($_SESSION['cart']);

        // Redirect to success page
        header("Location: order-success.php?order_id=$order_id");
        exit();
    } else {
        $error = "Error placing order: " . mysqli_error($conn);
    }
}
?>

<!-- Same HTML as above, but remove the form fields for shipping_address, special_instructions, etc. -->
<!-- Just keep the basic checkout form -->
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout - ShopNest Rentals</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        .checkout-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            position: relative;
        }
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 10%;
            right: 10%;
            height: 2px;
            background: #e0e0e0;
            z-index: 1;
        }
        .step {
            text-align: center;
            position: relative;
            z-index: 2;
        }
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e0e0e0;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: bold;
        }
        .step.active .step-number {
            background: #ff6b35;
            color: white;
        }
        .step.completed .step-number {
            background: #28a745;
            color: white;
        }
        .rental-dates {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .btn-orange {
            background: linear-gradient(45deg, #ff6b35, #ff8e53);
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 25px;
            font-weight: 600;
            transition: all 0.3s;
        }
        .btn-orange:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 53, 0.3);
            color: white;
        }
    </style>
</head>
<body>
    <?php include "includes/header.php"; ?>

    <div class="container mt-4">
        <!-- Step Indicator -->
        <div class="step-indicator">
            <div class="step completed">
                <div class="step-number">1</div>
                <small>Cart</small>
            </div>
            <div class="step active">
                <div class="step-number">2</div>
                <small>Checkout</small>
            </div>
            <div class="step">
                <div class="step-number">3</div>
                <small>Payment</small>
            </div>
            <div class="step">
                <div class="step-number">4</div>
                <small>Complete</small>
            </div>
        </div>

        <h2 class="mb-4" style="color: #2c3e50;">
            <i class="fas fa-credit-card me-2"></i>Checkout
        </h2>

        <?php if(isset($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Delivery Information -->
            <div class="col-lg-8 mb-4">
                <div class="checkout-container">
                    <h4 class="mb-4" style="color: #2c3e50;">
                        <i class="fas fa-truck me-2"></i>Delivery Information
                    </h4>
                    

                </div>
            </div>

            <!-- Order Summary -->
            <div class="col-lg-4">
                <div class="checkout-container">
                    <h4 class="mb-4" style="color: #2c3e50;">
                        <i class="fas fa-receipt me-2"></i>Order Summary
                    </h4>
                    
                    <!-- Cart Items -->
                    <div class="mb-4">
                        <?php foreach($_SESSION['cart'] as $item): 
                            $item_total = $item['price'] * $item['qty'];
                        ?>
                        <div class="d-flex mb-3 pb-3 border-bottom">
                            <?php
                            $cs_img = $item['image'] ?? $item['images'] ?? '';
                            $cs_path = 'assets/images/products/' . $cs_img;
                            $cs_src = (!empty($cs_img) && file_exists($cs_path)) ? $cs_path : '';
                            ?>
                            <img src="<?php echo $cs_src; ?>" 
                                 class="rounded me-3" 
                                 style="width: 60px; height: 60px; object-fit: cover;">
                            <div>
                                <h6 class="mb-1"><?php echo htmlspecialchars($item['name']); ?></h6>
                                <small class="text-muted d-block">
                                    Qty: <?php echo $item['qty']; ?>
                                </small>
                                <small class="text-primary">
                                    ₹<?php echo number_format($item_total, 2); ?>
                                </small>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Price Breakdown -->
                    <div class="mb-4">
                        <div class="d-flex justify-content-between mb-2">
                            <span>Rental Subtotal:</span>
                            <span>₹<?php echo number_format($subtotal, 2); ?></span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>Delivery Charge:</span>
                            <span>₹<?php echo number_format($delivery_charge, 2); ?></span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>GST (18%):</span>
                            <span>₹<?php echo number_format($tax, 2); ?></span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between fw-bold">
                            <span>Total Payable:</span>
                            <span class="text-success">₹<?php echo number_format($total_payable, 2); ?></span>
                        </div>
                    </div>

                    <!-- Important Notes -->
                    <div class="alert alert-warning">
                        <h6><i class="fas fa-exclamation-triangle me-2"></i>Important</h6>
                        <small>
                            <ul class="mb-0 ps-3">
                                <li>Free pickup included after rental period</li>
                                <li>Late returns incur additional charges (₹500/day)</li>
                                <li>Professional cleaning provided</li>
                                <li>24/7 customer support</li>
                            </ul>
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Calculate rental days
        function calculateRentalDays() {
            const startDate = document.querySelector('input[name="start_date"]');
            const returnDate = document.querySelector('input[name="return_date"]');
            const rentalDaysText = document.getElementById('rentalDaysText');
            
            if (startDate.value && returnDate.value) {
                const start = new Date(startDate.value);
                const end = new Date(returnDate.value);
                const diffTime = Math.abs(end - start);
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                
                if (diffDays > 0) {
                    rentalDaysText.textContent = `Rental period: ${diffDays} day${diffDays > 1 ? 's' : ''}`;
                } else {
                    rentalDaysText.textContent = 'Rental period: Please select valid dates';
                }
            }
        }
        
        // Form validation
        document.getElementById('checkoutForm').onsubmit = function(e) {
            const startDate = document.querySelector('input[name="start_date"]');
            const returnDate = document.querySelector('input[name="return_date"]');
            const today = new Date().toISOString().split('T')[0];
            
            if (startDate.value < today) {
                alert('Start date cannot be in the past!');
                startDate.focus();
                e.preventDefault();
                return false;
            }
            
            if (returnDate.value <= startDate.value) {
                alert('Return date must be after start date!');
                returnDate.focus();
                e.preventDefault();
                return false;
            }
            
            // Check if rental period is reasonable (max 30 days)
            const start = new Date(startDate.value);
            const end = new Date(returnDate.value);
            const diffTime = Math.abs(end - start);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            
            if (diffDays > 30) {
                alert('Maximum rental period is 30 days. Please select a shorter period.');
                returnDate.focus();
                e.preventDefault();
                return false;
            }
            
            if (diffDays < 1) {
                alert('Minimum rental period is 1 day.');
                returnDate.focus();
                e.preventDefault();
                return false;
            }
            
            return true;
        };
        
        // Add event listeners for date changes
        document.querySelector('input[name="start_date"]').addEventListener('change', calculateRentalDays);
        document.querySelector('input[name="return_date"]').addEventListener('change', calculateRentalDays);
        
        // Initialize rental days calculation
        calculateRentalDays();
    </script>

    <?php include "includes/footer.php"; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>