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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Initialize wishlist session
if (!isset($_SESSION['wishlist'])) {
    $_SESSION['wishlist'] = [];
}

// Add to wishlist
if (isset($_GET['add']) && isset($_GET['id'])) {
    $product_id = $_GET['id'];
    
    // Check if product exists
    $product_query = mysqli_query($conn, "SELECT * FROM products WHERE id='$product_id'");
    if (mysqli_num_rows($product_query) > 0) {
        $product = mysqli_fetch_assoc($product_query);
        
        // Check if already in wishlist
        $already_in_wishlist = false;
        foreach ($_SESSION['wishlist'] as $item) {
            if ($item['id'] == $product_id) {
                $already_in_wishlist = true;
                break;
            }
        }
        
        if (!$already_in_wishlist) {
            $_SESSION['wishlist'][] = [
                'id' => $product['id'],
                'name' => $product['name'],
                'price' => $product['price'],
                'image' => $product['images']
            ];
            $success = "Added to wishlist!";
        } else {
            $error = "Already in wishlist!";
        }
    }
}

// Remove from wishlist
if (isset($_GET['remove']) && isset($_GET['index'])) {
    $index = $_GET['index'];
    if (isset($_SESSION['wishlist'][$index])) {
        unset($_SESSION['wishlist'][$index]);
        $_SESSION['wishlist'] = array_values($_SESSION['wishlist']);
        $success = "Removed from wishlist!";
    }
}

// Move to cart
if (isset($_GET['move_to_cart']) && isset($_GET['index'])) {
    $index = $_GET['index'];
    if (isset($_SESSION['wishlist'][$index])) {
        $item = $_SESSION['wishlist'][$index];
        
        // Initialize cart if not exists
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = [];
        }
        
        // Add to cart
        $_SESSION['cart'][] = [
            'id' => $item['id'],
            'name' => $item['name'],
            'price' => $item['price'],
            'image' => $item['image'],
            'qty' => 1
        ];
        
        // Remove from wishlist
        unset($_SESSION['wishlist'][$index]);
        $_SESSION['wishlist'] = array_values($_SESSION['wishlist']);
        
        header("Location: ../cart.php");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Wishlist - ShopNest</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>
        .wishlist-container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        .empty-state i {
            font-size: 4rem;
            color: #ddd;
            margin-bottom: 20px;
        }
        .wishlist-item {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            transition: all 0.3s;
        }
        .wishlist-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        .product-img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <?php include "../includes/header.php"; ?>

    <div class="container mt-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="../index.php">Home</a></li>
                <li class="breadcrumb-item"><a href="profile.php">My Account</a></li>
                <li class="breadcrumb-item active">My Wishlist</li>
            </ol>
        </nav>

        <div class="row">
            <!-- Sidebar -->
            <?php include "includes/sidebar.php"; ?>

            <!-- Wishlist Content -->
            <div class="col-md-9">
                <div class="profile-content" style="background: white; border-radius: 15px; padding: 30px; box-shadow: 0 5px 15px rgba(0,0,0,0.05);">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h3 style="color: #2c3e50;">
                            <i class="fas fa-heart me-2" style="color: #e74c3c;"></i>My Wishlist
                        </h3>
                        <?php if(count($_SESSION['wishlist']) > 0): ?>
                            <a href="wishlist.php?clear_all=1" 
                               class="btn btn-outline-danger btn-sm"
                               onclick="return confirm('Clear all items from wishlist?')">
                                <i class="fas fa-trash me-2"></i>Clear All
                            </a>
                        <?php endif; ?>
                    </div>

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

                    <?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; ?>

                    <?php if(count($_SESSION['wishlist']) > 0): ?>
                        <div class="row">
                            <?php foreach($_SESSION['wishlist'] as $index => $item): 
                                // Get product details from database
                                $product_query = mysqli_query($conn, "SELECT * FROM products WHERE id='{$item['id']}'");
                                $product = mysqli_fetch_assoc($product_query);
                            ?>
                            <div class="col-md-6 mb-4">
                                <div class="wishlist-item">
                                    <div class="row align-items-center">
                                        <div class="col-4">
                                                <?php
                                                $w_img = $item['image'] ?? $item['images'] ?? '';
                                                $w_fs = __DIR__ . '/../assets/images/products/' . $w_img;
                                                $w_src = (!empty($w_img) && file_exists($w_fs)) ? '../assets/images/products/' . $w_img : '';
                                                ?>
                                                <img src="<?php echo $w_src; ?>" 
                                                    class="product-img"
                                                    alt="<?php echo htmlspecialchars($item['name']); ?>">
                                        </div>
                                        <div class="col-8">
                                            <h6 class="mb-1"><?php echo htmlspecialchars($item['name']); ?></h6>
                                            <div class="price-info small mb-2">
                                                <?php
                                                $wi_orig = floatval($item['original_price']);
                                                $wi_rent = floatval($item['price']);
                                                $wi_disc = intval($item['discount_percent']);
                                                $wi_final = $wi_disc > 0 ? $wi_rent - ($wi_rent * $wi_disc / 100) : $wi_rent;
                                                $wi_sec = floatval($item['security_deposit']);
                                                ?>
                                                <?php if ($wi_orig > 0): ?>
                                                    <div><strong>Product:</strong> ₹<?php echo number_format($wi_orig, 2); ?></div>
                                                <?php endif; ?>
                                                <div><strong class="text-primary">Rental:</strong> ₹<?php echo number_format($wi_rent, 2); ?>/day</div>
                                                <?php if ($wi_sec > 0): ?>
                                                    <div><strong class="text-danger">Security:</strong> ₹<?php echo number_format($wi_sec, 2); ?></div>
                                                <?php endif; ?>
                                                <?php if ($wi_disc > 0): ?>
                                                    <div><strong class="text-warning">Discount:</strong> <?php echo $wi_disc; ?>%</div>
                                                <?php endif; ?>
                                            </div>
                                            <div style="margin-bottom: 8px;">
                                                <strong style="font-size: 1.3rem; color: #28a745;">₹<?php echo number_format($wi_final, 2); ?>/day</strong>
                                            </div>
                                            <div class="d-flex">
                                                <a href="wishlist.php?move_to_cart=1&index=<?php echo $index; ?>" 
                                                   class="btn btn-sm btn-orange me-2">
                                                    <i class="fas fa-cart-plus me-1"></i>Add to Cart
                                                </a>
                                                <a href="wishlist.php?remove=1&index=<?php echo $index; ?>" 
                                                   class="btn btn-sm btn-outline-danger">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="text-center mt-4">
                            <a href="../products.php" class="btn btn-outline-primary me-3">
                                <i class="fas fa-arrow-left me-2"></i>Continue Shopping
                            </a>
                            <a href="../cart.php" class="btn btn-orange">
                                <i class="fas fa-shopping-cart me-2"></i>Go to Cart
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-heart" style="color: #ddd;"></i>
                            <h4>Your wishlist is empty</h4>
                            <p class="text-muted">Save items you love for later. Click the heart icon on any product.</p>
                            <a href="../products.php" class="btn btn-orange">
                                <i class="fas fa-tshirt me-2"></i>Browse Collection
                            </a>
                        </div>
                    <?php endif; ?>

                    <!-- Recently Viewed -->
                    <div class="card mt-5">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">
                                <i class="fas fa-eye me-2"></i>You Might Also Like
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // Get random products
                            $random_products = mysqli_query($conn, 
                                "SELECT * FROM products WHERE stock > 0 ORDER BY RAND() LIMIT 3"
                            );
                            ?>
                            
                            <div class="row">
                                <?php while($product = mysqli_fetch_assoc($random_products)): ?>
                                <div class="col-md-4">
                                    <div class="card h-100">
                                        <?php
                                        $rp_img = $product['images'] ?? $product['image'] ?? '';
                                        $rp_fs = __DIR__ . '/../assets/images/products/' . $rp_img;
                                        $rp_src = (!empty($rp_img) && file_exists($rp_fs)) ? '../assets/images/products/' . $rp_img : '';
                                        ?>
                                        <img src="<?php echo $rp_src; ?>" 
                                            class="card-img-top"
                                            alt="<?php echo htmlspecialchars($product['name']); ?>"
                                            style="height: 150px; object-fit: cover;">
                                        <div class="card-body">
                                            <h6 class="card-title"><?php echo htmlspecialchars($product['name']); ?></h6>
                                            <div class="price-info small mb-2">
                                                <?php
                                                $wp_orig = floatval($product['original_price']);
                                                $wp_rent = floatval($product['price']);
                                                $wp_disc = intval($product['discount_percent']);
                                                $wp_final = $wp_disc > 0 ? $wp_rent - ($wp_rent * $wp_disc / 100) : $wp_rent;
                                                $wp_sec = floatval($product['security_deposit']);
                                                ?>
                                                <?php if ($wp_orig > 0): ?>
                                                    <div><strong>Product:</strong> ₹<?php echo number_format($wp_orig, 2); ?></div>
                                                <?php endif; ?>
                                                <div><strong class="text-primary">Rental:</strong> ₹<?php echo number_format($wp_rent, 2); ?>/day</div>
                                                <?php if ($wp_sec > 0): ?>
                                                    <div><strong class="text-danger">Security:</strong> ₹<?php echo number_format($wp_sec, 2); ?></div>
                                                <?php endif; ?>
                                                <?php if ($wp_disc > 0): ?>
                                                    <div><strong class="text-warning">Discount:</strong> <?php echo $wp_disc; ?>%</div>
                                                <?php endif; ?>
                                            </div>
                                            <div style="margin-bottom: 8px;"><strong style="font-size: 1.2rem; color: #28a745;">₹<?php echo number_format($wp_final, 2); ?>/day</strong></div>
                                            <div class="d-flex justify-content-between mt-2">
                                                <a href="../product-details.php?id=<?php echo $product['id']; ?>" 
                                                   class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <a href="wishlist.php?add=1&id=<?php echo $product['id']; ?>" 
                                                   class="btn btn-sm btn-outline-danger">
                                                    <i class="fas fa-heart"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?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>