<?php

class RentalController {

    // ─── GET /api/rentals/my ─────────────────────────────────────────────────
    public static function getMyRentals(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $db     = getDb();

        // 1. Fetch all orders for the user as "rentals"
        $stmt = $db->prepare(
            "SELECT o.id, o.total_price, o.status, o.payment_status, 
                    o.start_date, o.return_date, o.rental_days, o.created_at
             FROM orders o
             WHERE o.user_id = ?
             ORDER BY o.created_at DESC"
        );
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $allOrders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        // 2. Fetch items for these orders to include some product info
        foreach ($allOrders as &$order) {
            $stmt = $db->prepare(
                "SELECT oi.product_id, oi.product_name, oi.quantity, oi.price, p.images
                 FROM order_items oi
                 LEFT JOIN products p ON p.id = oi.product_id
                 WHERE oi.order_id = ?"
            );
            $stmt->bind_param('i', $order['id']);
            $stmt->execute();
            $order['items'] = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
        }

        $today = date('Y-m-d');
        
        $active   = [];
        $upcoming = [];
        $past     = [];

        foreach ($allOrders as $order) {
            $startDate = $order['start_date'];
            $returnDate = $order['return_date'];
            $status = $order['status'];

            // Skip cancelled orders for active/upcoming/past categories? 
            // Or include them in past if they are cancelled?
            // Let's follow a logical pattern:
            
            if ($status === 'Cancelled' || $status === 'Returned') {
                $past[] = $order;
                continue;
            }

            if ($startDate > $today) {
                $upcoming[] = $order;
            } elseif (($today >= $startDate && $today <= $returnDate) || $status === 'In Use') {
                $active[] = $order;
            } else {
                $past[] = $order;
            }
        }

        sendSuccess([
            'all'      => $allOrders,
            'active'   => $active,
            'upcoming' => $upcoming,
            'past'     => $past
        ]);
    }
}
