<?php
require_once __DIR__ . '/../services/RentalService.php';

class RentalController {

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

        // Automatically update statuses whenever user checks their rentals
        RentalService::updateStatuses($db, $userId);

        // 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.end_date, o.created_at,
                    o.penalty_amount, o.damage_cost, o.pickup_scheduled_date, o.refund_status
             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, p.security_deposit
                 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      = [];
        $purchases = [];

        foreach ($allOrders as $order) {
            $startDate = $order['start_date'];
            $status = $order['status'];
            $rentalDays = (int)$order['rental_days'];

            if ($rentalDays === 0) {
                $purchases[] = $order;
                continue;
            }

            if ($status === 'Cancelled' || $status === 'Returned') {
                $past[] = $order;
                continue;
            }

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

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

    // ─── POST /api/rentals/schedule-pickup ──────────────────────────────────
    public static function schedulePickup(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $body   = getJsonBody();
        $db     = getDb();

        // Ensure status is current before scheduling pickup
        RentalService::updateStatuses($db, $userId);

        $orderId     = (int)($body['order_id'] ?? 0);
        $pickupDate  = trim($body['pickup_date']   ?? '');
        $pickupTime  = trim($body['pickup_time']   ?? '');

        if (!$orderId || !$pickupDate) {
            sendError('Order ID and pickup date are required', 422);
        }

        // Verify order belongs to user
        $stmt = $db->prepare("SELECT id, special_instructions FROM orders WHERE id = ? AND user_id = ?");
        $stmt->bind_param('ii', $orderId, $userId);
        $stmt->execute();
        $order = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$order) sendError('Order not found', 404);

        $instructions = $order['special_instructions'] ?? '';
        $newInstructions = (empty($instructions) ? "" : $instructions . "\n") . "Rental Return Pickup: " . $pickupDate . " (" . $pickupTime . ")";
        $status = 'Return Requested';

        $stmt = $db->prepare(
            "UPDATE orders SET status = ?, pickup_scheduled_date = ?, special_instructions = ? WHERE id = ?"
        );
        $stmt->bind_param('sssi', $status, $pickupDate, $newInstructions, $orderId);
        
        if ($stmt->execute()) {
            $stmt->close();
            
            // Add notification for admin
            $notifTitle = "New Pickup Scheduled - Order #$orderId";
            $notifMsg   = "User scheduled a rental return pickup for $pickupDate during $pickupTime.";
            $db->query("INSERT INTO admin_notifications (title, message, type) VALUES ('$notifTitle', '$notifMsg', 'pickup')");
            
            sendSuccess(null, 'Pickup scheduled successfully');
        } else {
            sendError('Failed to schedule pickup', 500);
        }
    }
}
?>
