<?php
// product/checkout.php
require_once __DIR__ . '/includes/header.php';

// Calculate Total & Fetch Cart Items for Display
$total = 0;
$cart_items = []; 

if (!empty($_SESSION['cart'])) {
    $ids = implode(',', array_keys($_SESSION['cart']));
    
    if ($ids) {
        $in  = str_repeat('?,', count($_SESSION['cart']) - 1) . '?';
        // Fetch full details for display in summary
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($in)");
        $stmt->execute(array_keys($_SESSION['cart']));
        $products = $stmt->fetchAll();

        foreach ($products as $p) {
            $qty = $_SESSION['cart'][$p['id']];
            $subtotal = $p['price'] * $qty;
            $total += $subtotal;
            
            // Add quantity and subtotal to product array for display
            $p['qty'] = $qty;
            $p['subtotal'] = $subtotal;
            $cart_items[] = $p;
        }
    }
}

if ($total == 0) {
    echo "<script>window.location.href='cart.php';</script>";
    exit;
}

// Handle Order Placement
$error = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];
    $email = $_POST['email']; 
    $phone = $_POST['phone']; 
    $address = $_POST['address'];

    if (!$name || !$address || !$phone) {
        $error = "Please fill in all required fields.";
    } else {
        try {
            $pdo->beginTransaction();

            // 1. Create Order
            $full_address = $address . "\nPhone: " . $phone; 
            
            $sql = "INSERT INTO orders (guest_name, guest_email, address, total_amount, status) VALUES (?, ?, ?, ?, 'pending')";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$name, $email, $full_address, $total]);
            $order_id = $pdo->lastInsertId();

            // 2. Insert Items
            $itemSql = "INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)";
            $itemStmt = $pdo->prepare($itemSql);

            foreach ($cart_items as $item) {
                $itemStmt->execute([$order_id, $item['id'], $item['qty'], $item['price']]);
            }

            $pdo->commit();
            
            // Clear Cart
            unset($_SESSION['cart']);
            
            // Success Page
            echo "<div class='container my-5 text-center' style='min-height:60vh; display:flex; flex-direction:column; justify-content:center; align-items:center;'>
                    <div class='mb-4 text-success display-1'><i class='far fa-check-circle'></i></div>
                    <h2 class='fw-bold'>Thank you for your order!</h2>
                    <p class='lead text-muted'>Your Order ID is <strong>$order_id</strong></p>
                    <p>We will contact you shortly to confirm delivery.</p>
                    <a href='index.php' class='btn btn-dark mt-4 px-5 py-3 rounded-pill fw-bold'>Continue Shopping</a>
                  </div>";
            require_once __DIR__ . '/includes/footer.php';
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Order failed: " . $e->getMessage();
        }
    }
}

// Fetch 20 Random Suggested Products
$suggestions = $pdo->query("SELECT * FROM products ORDER BY RAND() LIMIT 20")->fetchAll();
?>

<style>
    /* --- DESKTOP / DEFAULT STYLES --- */
    .product-card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        overflow: hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        background: #fff;
        height: 100%;
        display: flex;
        flex-direction: column;
    }
    .product-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 35px rgba(0,0,0,0.1);
    }
    .product-img-wrapper {
        background-color: #fff;
        padding: 20px;
        position: relative;
        height: 180px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .product-img-wrapper img {
        max-height: 100%;
        max-width: 100%;
        object-fit: contain;
    }
    .card-body-custom {
        padding: 15px;
        text-align: center;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
    .card-title {
        font-weight: 700;
        font-size: 0.95rem;
        margin-bottom: 5px;
        color: #2c3e50;
    }
    .price-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #f0f0f0;
        padding-top: 10px;
        margin-top: auto;
        flex-wrap: wrap;
        gap: 5px;
    }
    .price-tag {
        font-size: 1.1rem;
        font-weight: 800;
        color: #2c3e50;
    }
    .btn-add-cart-custom {
        background: transparent;
        color: #2c3e50;
        border: 2px solid #2c3e50;
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 0.7rem;
        font-weight: 700;
        text-transform: uppercase;
        transition: all 0.2s;
    }
    .btn-add-cart-custom:hover {
        background: #2c3e50;
        color: #fff;
    }

    /* Checkout Specific Styles */
    .checkout-form-card {
        border: none;
        border-radius: 16px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.03);
        background: #fff;
        padding: 30px;
    }
    .form-control {
        padding: 12px 15px;
        border-radius: 8px;
        border: 1px solid #e0e0e0;
        background-color: #f9f9f9;
        font-size: 1rem; /* Prevents zoom on iOS */
    }
    .form-control:focus {
        background-color: #fff;
        box-shadow: 0 0 0 3px rgba(44, 62, 80, 0.1);
        border-color: #2c3e50;
    }
    .summary-card {
        background-color: #f8f9fa;
        border-radius: 16px;
        padding: 25px;
        position: sticky;
        top: 20px;
    }
    .summary-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 15px;
        border-bottom: 1px solid #e9ecef;
    }
    .summary-item:last-child {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }
    .summary-img {
        width: 60px;
        height: 60px;
        background: #fff;
        border-radius: 8px;
        padding: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #eee;
        margin-right: 15px;
    }
    .summary-img img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
    }

    /* --- MOBILE OPTIMIZATION --- */
    @media (max-width: 768px) {
        .checkout-form-card, .summary-card {
            padding: 20px; /* Reduce padding */
        }
        
        .product-img-wrapper {
            height: 120px; /* Smaller images in suggestions */
            padding: 10px;
        }

        .card-body-custom {
            padding: 10px;
        }

        .card-title {
            font-size: 0.8rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .price-row {
            flex-direction: column;
            justify-content: center;
            align-items: flex-start;
        }
        
        .price-tag {
            font-size: 0.95rem;
            margin-bottom: 4px;
        }

        .btn-add-cart-custom {
            width: 100%;
            text-align: center;
            font-size: 0.65rem;
        }

        /* Adjust summary image size */
        .summary-img {
            width: 50px;
            height: 50px;
            margin-right: 10px;
        }
        
        h3 { font-size: 1.5rem; }
        h4 { font-size: 1.3rem; }
    }
</style>

<div class="container my-5">
    <div class="row g-4 g-lg-5">
        
        <div class="col-lg-7">
            <h3 class="mb-4 fw-bold" style="letter-spacing: 1px;">CHECKOUT</h3>
            
            <?php if($error): ?>
                <div class="alert alert-danger rounded-3"><?= $error ?></div>
            <?php endif; ?>

            <div class="checkout-form-card">
                <form method="POST" id="checkoutForm">
                    <h5 class="mb-4 text-muted border-bottom pb-2">Contact Info</h5>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-uppercase">Full Name</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small text-uppercase">Phone Number</label>
                            <input type="tel" name="phone" class="form-control" required placeholder="">
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold small text-uppercase">Email <span class="text-muted fw-normal text-lowercase">(optional)</span></label>
                        <input type="email" name="email" class="form-control">
                    </div>

                    <h5 class="mb-4 text-muted border-bottom pb-2 mt-4">Shipping Address</h5>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold small text-uppercase">Street Address, City</label>
                        <textarea name="address" class="form-control" rows="3" required placeholder="Full delivery address..."></textarea>
                    </div>

                    <div class="d-grid mt-4">
                        <button type="submit" class="btn btn-dark py-3 fw-bold text-uppercase shadow-sm" style="letter-spacing: 1px; border-radius: 10px;">
                            Complete Order &nbsp; <i class="fas fa-arrow-right"></i>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="col-lg-5">
            <div class="summary-card">
                <h4 class="mb-4 fw-bold">Summary</h4>
                
                <div class="mb-4" style="max-height: 400px; overflow-y: auto;">
                    <?php foreach($cart_items as $item): ?>
                    <div class="summary-item">
                        <div class="summary-img">
                            <img src="../../<?= $item['image'] ?>" alt="Product">
                        </div>
                        <div class="flex-grow-1" style="overflow: hidden;">
                            <h6 class="mb-0 fw-bold text-dark text-truncate" style="font-size: 0.95rem;"><?= htmlspecialchars($item['name']) ?></h6>
                            <small class="text-muted">Qty: <?= $item['qty'] ?></small>
                        </div>
                        <div class="fw-bold ps-2">
                            $<?= number_format($item['subtotal'], 2) ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="border-top pt-3">
                    <div class="d-flex justify-content-between mb-2 text-muted">
                        <span>Subtotal</span>
                        <span>$<?= number_format($total, 2) ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-3 text-muted">
                        <span>Shipping</span>
                        <span class="text-success fw-bold">Free</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center pt-3 border-top">
                        <span class="h5 fw-bold mb-0">Total</span>
                        <span class="h4 fw-bold mb-0 text-primary">$<?= number_format($total, 2) ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="mt-5 pt-5 border-top">
        <h3 class="mb-4 text-center text-uppercase fw-bold" style="letter-spacing: 2px;">You Might Also Like</h3>
        
        <div class="row row-cols-2 row-cols-sm-2 row-cols-lg-4 g-2 g-md-4">
            <?php foreach($suggestions as $p): ?>
            <div class="col">
                <div class="product-card">
                    <a href="product_detail.php?id=<?= $p['id'] ?>" class="text-decoration-none">
                        <div class="product-img-wrapper">
                            <img src="../../<?= $p['image'] ?>" alt="<?= htmlspecialchars($p['name']) ?>">
                        </div>
                    </a>
                    
                    <div class="card-body-custom">
                        <a href="product_detail.php?id=<?= $p['id'] ?>" class="text-decoration-none">
                            <h6 class="card-title"><?= htmlspecialchars($p['name']) ?></h6>
                        </a>

                        <div class="price-row">
                            <div class="price-tag">$<?= number_format($p['price'], 2) ?></div>
                            
                            <form action="cart.php" method="POST" class="w-100 w-md-auto">
                                <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                                <input type="hidden" name="action" value="add">
                                <button type="submit" class="btn-add-cart-custom">ADD</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

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