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

/* ── Login & cart guard (must be first) ────────────────────────────────────── */
if (!isset($_SESSION['user_id'])) {
    header("Location: /shopnest/user/login.php");
    exit();
}
if (empty($_SESSION['cart'])) {
    echo "<div class='container mt-4'>
            <div class='alert alert-warning'>
                <i class='fas fa-shopping-cart me-2'></i>Your rental cart is empty!
            </div>
            <a href='products.php' class='btn btn-orange'>Browse Collection</a>
          </div>";
    exit();
}

// Check if user is verified
$user_id = (int)$_SESSION['user_id'];
$user_verified = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT id_verified FROM users WHERE id = $user_id"
));

// Calculate cart total (support both 'qty' and 'quantity' keys)
$cart_total = 0;
foreach ($_SESSION['cart'] as $item) {
    $q = isset($item['qty']) ? $item['qty'] : ($item['quantity'] ?? 1);
    $cart_total += $item['price'] * $q;
}

// Check if verification is required
$verification_required = $cart_total > 5000;

if ($verification_required && !$user_verified['id_verified']) {
    $_SESSION['checkout_message'] = "ID verification required for orders over ₹5000";
    header("Location: user/id-verification.php");
    exit();
}

/* Cart check */
if (empty($_SESSION['cart'])) {
    echo "<div class='container mt-4'>
            <div class='alert alert-warning'>
                <i class='fas fa-shopping-cart me-2'></i>Your rental cart is empty!
            </div>
            <a href='products.php' class='btn btn-orange'>Browse Collection</a>
          </div>";
    exit();
}

// Get user details
$user_id = $_SESSION['user_id'];
$user_query = mysqli_query($conn, "SELECT * FROM users WHERE id='$user_id'");
$user = mysqli_fetch_assoc($user_query);

// 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; // ₹99 delivery charge
$tax = $subtotal * 0.18; // 18% GST
$total_payable = $subtotal + $delivery_charge + $tax;

/* ─── Ensure payment columns exist ──────────────────────────────────────────── */
$_cols = [];
$_r = mysqli_query($conn, "SHOW COLUMNS FROM orders");
while ($_c = mysqli_fetch_assoc($_r)) $_cols[] = $_c['Field'];
if (!in_array('payment_id',     $_cols)) mysqli_query($conn, "ALTER TABLE orders ADD COLUMN payment_id VARCHAR(100) DEFAULT NULL");
if (!in_array('payment_status', $_cols)) mysqli_query($conn, "ALTER TABLE orders ADD COLUMN payment_status ENUM('Pending','Paid','COD','Failed') DEFAULT 'Pending'");
if (!in_array('payment_method', $_cols)) mysqli_query($conn, "ALTER TABLE orders ADD COLUMN payment_method VARCHAR(50) DEFAULT NULL");

/* Place Order */
if (isset($_POST['place_order'])) {
    $user_id              = $_SESSION['user_id'];
    $shipping_address     = mysqli_real_escape_string($conn, $_POST['shipping_address']);
    $special_instructions = mysqli_real_escape_string($conn, $_POST['special_instructions']);
    $start_date           = mysqli_real_escape_string($conn, $_POST['start_date']);
    $return_date          = mysqli_real_escape_string($conn, $_POST['return_date']);
    $payment_method       = in_array($_POST['payment_method'] ?? 'razorpay', ['razorpay','cod','upi'])
                                ? $_POST['payment_method'] : 'razorpay';

    // Calculate rental days
    $start       = new DateTime($start_date);
    $returnDate  = new DateTime($return_date);
    $rental_days = $returnDate->diff($start)->days;

    // Detect available order columns
    $check_columns = mysqli_query($conn, "SHOW COLUMNS FROM orders");
    $columns = [];
    while ($col = mysqli_fetch_assoc($check_columns)) $columns[] = $col['Field'];

    $has_extra = in_array('shipping_address', $columns) && in_array('start_date', $columns);

    // For COD → status = 'COD' | For online → status = 'Pending'
    $pay_status = ($payment_method === 'cod') ? 'COD' : 'Pending';

    if ($has_extra) {
        $order_query = "INSERT INTO orders
            (user_id, total_price, rental_days, shipping_address, special_instructions,
             start_date, return_date, payment_method, payment_status)
            VALUES
            ('$user_id','$total_payable','$rental_days','$shipping_address','$special_instructions',
             '$start_date','$return_date','$payment_method','$pay_status')";
    } else {
        $order_query = "INSERT INTO orders
            (user_id, total_price, payment_method, payment_status)
            VALUES ('$user_id','$total_payable','$payment_method','$pay_status')";
    }

    if (mysqli_query($conn, $order_query)) {
        $order_id = mysqli_insert_id($conn);

        // Insert order items & update stock
        foreach ($_SESSION['cart'] as $item) {
            $pid   = (int)$item['id'];
            $pname = mysqli_real_escape_string($conn, $item['name']);
            $price = floatval($item['price']);
            $qty   = (int)$item['qty'];
            mysqli_query($conn,
                "INSERT INTO order_items (order_id, product_id, product_name, price, quantity)
                 VALUES ('$order_id','$pid','$pname','$price','$qty')"
            );
            mysqli_query($conn, "UPDATE products SET stock = stock - 1 WHERE id = '$pid'");
        }

        if ($payment_method === 'cod') {
            // COD — order is placed, clear cart and go to success
            unset($_SESSION['cart'], $_SESSION['pending_order_id']);
            header("Location: order-success.php?order_id=$order_id");
            exit();
        } else {
            // Online payment — keep cart in session until payment verified
            $_SESSION['pending_order_id'] = $order_id;
            header("Location: payment.php");
            exit();
        }
    } else {
        $error = "Error placing order: " . mysqli_error($conn);
    }
}
?>

<!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>
                    
                    <form method="POST" id="checkoutForm">
                        <!-- Rental Dates -->
                        <div class="rental-dates">
                            <h6><i class="fas fa-calendar-alt me-2"></i>Rental Period</h6>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Start Date</label>
                                    <input type="date" 
                                           name="start_date" 
                                           class="form-control" 
                                           required
                                           min="<?php echo date('Y-m-d'); ?>"
                                           value="<?php echo date('Y-m-d'); ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Return Date</label>
                                    <input type="date" 
                                           name="return_date" 
                                           class="form-control" 
                                           required
                                           min="<?php echo date('Y-m-d', strtotime('+1 day')); ?>"
                                           value="<?php echo date('Y-m-d', strtotime('+3 days')); ?>">
                                </div>
                            </div>
                            <div class="text-center">
                                <small class="text-muted" id="rentalDaysText">Rental period: 3 days</small>
                            </div>
                        </div>

                        <!-- Shipping Address -->
                        <div class="mb-4">
                            <label class="form-label fw-bold">Shipping Address</label>
                            <textarea name="shipping_address" 
                                      class="form-control" 
                                      rows="3"
                                      placeholder="Enter your complete delivery address including house number, street, city, and pincode"
                                      required><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                        </div>

                        <!-- Contact Information -->
                        <div class="row mb-4">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Full Name</label>
                                <input type="text" 
                                       class="form-control" 
                                       value="<?php echo htmlspecialchars($user['name']); ?>"
                                       readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Phone Number</label>
                                <input type="text" 
                                       class="form-control" 
                                       value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>"
                                       readonly>
                            </div>
                        </div>

                        <!-- Special Instructions -->
                        <div class="mb-4">
                            <label class="form-label">Special Instructions (Optional)</label>
                            <textarea name="special_instructions" 
                                      class="form-control" 
                                      rows="2"
                                      placeholder="Any special delivery instructions, timing preferences, or other requests..."></textarea>
                        </div>

                        <!-- Payment Method -->
                        <div class="mb-4">
                            <h6><i class="fas fa-credit-card me-2"></i>Payment Method</h6>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="payment_method" id="razorpay" value="razorpay" checked>
                                <label class="form-check-label" for="razorpay">
                                    <i class="fas fa-credit-card me-2"></i>Credit/Debit Card
                                </label>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="payment_method" id="cod" value="cod">
                                <label class="form-check-label" for="cod">
                                    <i class="fas fa-money-bill me-2"></i>Cash on Delivery
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="payment_method" id="upi" value="upi">
                                <label class="form-check-label" for="upi">
                                    <i class="fas fa-mobile-alt me-2"></i>UPI
                                </label>
                            </div>
                        </div>

                        <!-- Terms Agreement -->
                        <div class="form-check mb-4">
                            <input class="form-check-input" type="checkbox" id="terms" required>
                            <label class="form-check-label" for="terms">
                                I agree to the <a href="#" style="color: #ff6b35;">Rental Terms & Conditions</a>
                            </label>
                        </div>

                        <div class="d-flex justify-content-between">
                            <a href="cart.php" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Back to Cart
                            </a>
                            <button type="submit" name="place_order" class="btn btn-orange btn-lg">
                                <i class="fas fa-lock me-2"></i>Proceed to Payment
                            </button>
                        </div>
                    </form>
                </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
                               $c_img = $item['image'] ?? $item['images'] ?? '';
                               $c_path = 'assets/images/products/' . $c_img;
                               $c_src = (!empty($c_img) && file_exists($c_path)) ? $c_path : '';
                               ?>
                               <img src="<?php echo $c_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>