<?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();
}

$user_id = $_SESSION['user_id'];

// Get user's rental orders
$orders_result = mysqli_query($conn, 
    "SELECT * FROM orders 
     WHERE user_id = '$user_id' 
     ORDER BY created_at DESC"
);

$all_orders = [];
if ($orders_result) {
    while($row = mysqli_fetch_assoc($orders_result)) {
        $all_orders[] = $row;
    }
}

function renderOrderCards($orders_list, $conn, $allowed_statuses = null, $empty_icon = 'fa-box-open', $empty_title = 'No rentals yet', $empty_msg = 'You haven\'t rented any outfits yet.') {
    $filtered = [];
    if ($allowed_statuses === null) {
        $filtered = $orders_list;
    } else {
        foreach ($orders_list as $o) {
            if (in_array($o['status'], $allowed_statuses)) {
                $filtered[] = $o;
            }
        }
    }
    
    if (empty($filtered)) {
        echo '<div class="empty-state">
                <i class="fas '.$empty_icon.'"></i>
                <h4>'.$empty_title.'</h4>
                <p class="text-muted">'.$empty_msg.'</p>
                <a href="../products.php" class="btn btn-orange">
                    <i class="fas fa-tshirt me-2"></i>Browse Collection
                </a>
              </div>';
        return;
    }
    
    foreach ($filtered as $order):
        $items_count = mysqli_fetch_assoc(mysqli_query($conn, 
            "SELECT COUNT(*) as count FROM order_items WHERE order_id = '{$order['id']}'"
        ))['count'];
        
        $border_color = '#6c757d';
        $badge_class = '';
        switch($order['status']) {
            case 'Pending':   $border_color = '#ffc107'; $badge_class = 'status-pending'; break;
            case 'Confirmed': $border_color = '#3498db'; $badge_class = 'status-confirmed'; break;
            case 'Shipped':   $border_color = '#28a745'; $badge_class = 'status-shipped'; break;
            case 'Delivered': $border_color = '#17a2b8'; $badge_class = 'status-delivered'; break;
            case 'Cancelled': $border_color = '#dc3545'; $badge_class = 'status-cancelled'; break;
            case 'In Use':    $border_color = '#fd7e14'; $badge_class = 'status-inuse'; break;
            case 'Overdue':   $border_color = '#e74c3c'; $badge_class = 'status-overdue'; break;
            case 'Returned':  $border_color = '#6f42c1'; $badge_class = 'status-returned'; break;
            case 'Return Requested':  $border_color = '#a0aec0'; $badge_class = 'status-requested'; break;
        }
        ?>
        <div class="rental-card" style="border-left-color: <?php echo $border_color; ?>;">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="d-flex align-items-center mb-2">
                        <span class="order-id me-3">ORDER #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></span>
                        <span class="status-badge <?php echo $badge_class; ?>"><?php echo htmlspecialchars($order['status']); ?></span>
                    </div>
                    <div class="mb-2">
                        <h5 class="mb-1">₹<?php echo number_format($order['total_price'], 2); ?></h5>
                        <p class="text-muted mb-1"><i class="far fa-calendar me-1"></i> <?php echo date('F j, Y', strtotime($order['created_at'])); ?></p>
                        <p class="text-muted mb-0"><i class="fas fa-tshirt me-1"></i> <?php echo $items_count; ?> item<?php echo $items_count > 1 ? 's' : ''; ?></p>
                        
                        <?php if ($order['status'] == 'In Use'): ?>
                            <?php 
                                $days_left = ceil((strtotime($order['end_date']) - time()) / (60 * 60 * 24));
                                if ($days_left == 1) {
                                    $countdown_class = 'text-danger fw-bold';
                                    $msg = 'Expiring Tomorrow!';
                                } elseif ($days_left <= 0) {
                                    $countdown_class = 'text-danger fw-bold pulse';
                                    $msg = 'Expiring Today!';
                                } else {
                                    $countdown_class = 'text-orange fw-bold';
                                    $msg = $days_left . ' days Left';
                                }
                            ?>
                            <div class="mt-2 p-2 bg-light rounded border-start border-3 <?php echo ($days_left <= 1) ? 'border-danger' : 'border-warning'; ?>">
                                <span class="<?php echo $countdown_class; ?>">
                                    <i class="fas fa-hourglass-half me-1"></i> 
                                    <?php echo $msg; ?>
                                </span>
                            </div>
                        <?php elseif ($order['status'] == 'Overdue'): ?>
                            <div class="mt-2 p-2 bg-light rounded border-start border-3 border-danger">
                                <span class="text-danger fw-bold">
                                    <i class="fas fa-exclamation-triangle me-1"></i> Overdue! Penalty: ₹<?php echo number_format($order['penalty_amount'] ?? 0, 2); ?>
                                </span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="col-md-4 text-end">
                    <a href="order-details.php?id=<?php echo $order['id']; ?>" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-eye me-1"></i>View Details
                    </a>
                    <?php if($order['status'] == 'Pending'): ?>
                        <a href="cancel-order.php?id=<?php echo $order['id']; ?>" class="btn btn-outline-danger btn-sm" onclick="return confirm('Are you sure you want to cancel this order?')">
                            <i class="fas fa-times me-1"></i>Cancel
                        </a>
                    <?php endif; ?>

                    <?php if($order['status'] == 'In Use' || $order['status'] == 'Overdue'): ?>
                        <button type="button" class="btn btn-orange btn-sm mt-1" data-bs-toggle="modal" data-bs-target="#returnModal<?php echo $order['id']; ?>">
                            <i class="fas fa-undo me-1"></i>Return Product
                        </button>
                    <?php endif; ?>
                    
                </div>
            </div>
        </div>

        <?php if($order['status'] == 'In Use' || $order['status'] == 'Overdue'): ?>
            <!-- Return Modal (Moved outside rental-card to prevent flickering) -->
            <div class="modal fade text-start" id="returnModal<?php echo $order['id']; ?>" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Schedule Pickup - Order #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <form action="schedule-return.php" method="POST">
                            <div class="modal-body">
                                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                <div class="mb-3">
                                    <label class="form-label">When should we pick up the product?</label>
                                    <input type="date" name="pickup_date" class="form-control" required min="<?php echo date('Y-m-d'); ?>">
                                    <div class="form-text">Pickups are scheduled between 10 AM and 6 PM.</div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Additional Instructions (Optional)</label>
                                    <textarea name="instructions" class="form-control" rows="2"></textarea>
                                </div>
                                <?php if($order['status'] == 'Overdue'): ?>
                                    <div class="alert alert-warning small">
                                        <i class="fas fa-info-circle me-1"></i> Note: Late return penalties apply until pickup is completed.
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-orange">Confirm Pickup</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        <?php
    endforeach;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Rentals - 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>
        .rentals-container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .rental-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            border-left: 4px solid;
            transition: all 0.3s;
        }
        .rental-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        .status-badge {
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-confirmed { background: #cce5ff; color: #004085; }
        .status-shipped { background: #d4edda; color: #155724; }
        .status-delivered { background: #d1ecf1; color: #0c5460; }
        .status-cancelled { background: #f8d7da; color: #721c24; }
        .status-inuse { background: #fff4e5; color: #d9480f; }
        .status-overdue { background: #ffe3e3; color: #c92a2a; }
        .status-returned { background: #f3e5f5; color: #7b1fa2; }
        .status-requested { background: #e9ecef; color: #495057; }
        .text-orange { color: #ff6b35; }
        .pulse {
            animation: pulse-red 2s infinite;
        }
        @keyframes pulse-red {
            0% { opacity: 1; }
            50% { opacity: 0.6; color: #ff0000; }
            100% { opacity: 1; }
        }
        .order-id {
            font-family: monospace;
            background: #2c3e50;
            color: white;
            padding: 3px 10px;
            border-radius: 5px;
            display: inline-block;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        .empty-state i {
            font-size: 4rem;
            color: #ddd;
            margin-bottom: 20px;
        }
    </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 Rentals</li>
            </ol>
        </nav>

        <?php if(isset($_SESSION['success_msg'])): ?>
            <div class="alert alert-success alert-dismissible fade show mb-4" role="alert">
                <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($_SESSION['success_msg']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['success_msg']); ?>
        <?php endif; ?>

        <?php if(isset($_SESSION['error_msg'])): ?>
            <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($_SESSION['error_msg']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['error_msg']); ?>
        <?php endif; ?>

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

            <!-- Rentals 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-box me-2"></i>My Rentals
                        </h3>
                        <a href="../products.php" class="btn btn-orange">
                            <i class="fas fa-plus me-2"></i>Rent New Outfit
                        </a>
                    </div>

                    <!-- Filter Tabs -->
                    <ul class="nav nav-tabs mb-4" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#all" type="button" role="tab">All Rentals</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#active" type="button" role="tab">Active</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#upcoming" type="button" role="tab">Upcoming</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#past" type="button" role="tab">Past</button>
                        </li>
                    </ul>

                    <div class="tab-content">
                        <!-- All Rentals -->
                        <div class="tab-pane fade show active" id="all">
                            <?php renderOrderCards($all_orders, $conn, null); ?>
                        </div>

                        <!-- Active Rentals (Shipped/Delivered/In Use/Overdue/Requested) -->
                        <div class="tab-pane fade" id="active">
                            <?php renderOrderCards($all_orders, $conn, ['Shipped', 'Delivered', 'In Use', 'Overdue', 'Return Requested'], 'fa-clock', 'No active rentals', 'You don\'t have any active rentals at the moment.'); ?>
                        </div>

                        <!-- Upcoming Rentals (Pending/Confirmed equivalent) -->
                        <div class="tab-pane fade" id="upcoming">
                            <?php renderOrderCards($all_orders, $conn, ['Pending', 'Confirmed'], 'fa-calendar-alt', 'No upcoming rentals', 'You don\'t have any pending or upcoming rentals scheduled.'); ?>
                        </div>

                        <!-- Past Rentals (Returned/Cancelled/Delivered equivalent) -->
                        <div class="tab-pane fade" id="past">
                            <?php renderOrderCards($all_orders, $conn, ['Returned', 'Cancelled'], 'fa-history', 'No past rentals', 'You haven\'t completed or cancelled any rentals yet.'); ?>
                        </div>
                    </div>

                    <!-- Help Section -->
                    <div class="card mt-4">
                        <div class="card-body">
                            <h5><i class="fas fa-question-circle me-2"></i>Need Help?</h5>
                            <p class="mb-2">If you have any questions about your rentals:</p>
                            <ul class="mb-0">
                                <li>Contact our support team at support@shopnest.com</li>
                                <li>Call us at +1 234 567 8900</li>
                                <li>Check our <a href="../faq.php">FAQ section</a></li>
                            </ul>
                        </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>
    <script>
        // Initialize Bootstrap tabs
        var triggerTabList = [].slice.call(document.querySelectorAll('button[data-bs-toggle="tab"]'))
        triggerTabList.forEach(function (triggerEl) {
            var tabTrigger = new bootstrap.Tab(triggerEl)
            
            triggerEl.addEventListener('click', function (event) {
                event.preventDefault()
                tabTrigger.show()
            })
        })
    </script>
</body>
</html>