<?php
/**
 * Rental Logic for API Server
 */
class RentalService {

    public static function updateStatuses(mysqli $db, int $userId): void {
        //$today = $_GET['test_date'] ?? date('Y-m-d', strtotime('2026-04-11'));
        $today = date('Y-m-d');
        // 1. Delivered -> In Use (when start_date is today or earlier)
        $stmt = $db->prepare("UPDATE orders SET status = 'In Use' WHERE user_id = ? AND status = 'Delivered' AND start_date <= ?");
        $stmt->bind_param('is', $userId, $today);
        $stmt->execute();
        $stmt->close();

        // 2. In Use -> Overdue (when today > return_date AND no pickup scheduled)
        $stmt = $db->prepare("SELECT id, return_date FROM orders WHERE user_id = ? AND status = 'In Use' AND return_date < ?");
        $stmt->bind_param('is', $userId, $today);
        $stmt->execute();
        $overdueOrders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        foreach ($overdueOrders as $order) {
            $orderId = $order['id'];
            $tomorrow = date('Y-m-d', strtotime('+1 day'));
            
            $db->query("UPDATE orders SET 
                        status = 'Overdue', 
                        pickup_scheduled_date = '$tomorrow',
                        special_instructions = CONCAT(IFNULL(special_instructions, ''), '\n[System]: Auto-Pickup Scheduled due to overdue.')
                        WHERE id = $orderId");
            
            // Notification logic (Admin - only if table exists)
            $checkAdminTable = $db->query("SHOW TABLES LIKE 'admin_notifications'");
            if ($checkAdminTable->num_rows > 0) {
                $notifTitle = "Auto Pickup Scheduled - Order #$orderId";
                $notifMsg   = "Order #$orderId is overdue. System scheduled auto pickup for $tomorrow.";
                $db->query("INSERT INTO admin_notifications (title, message, type) VALUES ('$notifTitle', '$notifMsg', 'rental')");
            }
            
            // Notification logic (User - only if table exists)
            $checkUserTable = $db->query("SHOW TABLES LIKE 'user_notifications'");
            if ($checkUserTable->num_rows > 0) {
                $userNotifMsg = "Your rental #$orderId is overdue! We have scheduled an automatic pickup for tomorrow.";
                $db->query("INSERT INTO user_notifications (user_id, message, type) VALUES ($userId, '$userNotifMsg', 'overdue')");
            }
        }

        // 3. Penalty Calculation for Overdue and Return Requested (if past return_date)
        // Penalty ₹100 per day
        $penaltyPerDay = 30.00;
        $stmt = $db->prepare("SELECT o.id, o.return_date, u.manual_unblock 
                              FROM orders o 
                              JOIN users u ON o.user_id = u.id 
                              WHERE o.user_id = ? AND o.status IN ('Overdue', 'Return Requested')");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $overdueList = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        foreach ($overdueList as $order) {
            $orderId = $order['id'];
            $targetDate = $order['return_date'];
            
            if (!$targetDate) continue;

            $diff = (strtotime($today) - strtotime($targetDate)) / (60 * 60 * 24);
            if ($diff > 0) {
                $currentPenalty = round($diff * $penaltyPerDay, 2);
                
                // Get total security deposit from order_items (static value at purchase)
                $depositRes = $db->query("SELECT SUM(security_deposit * quantity) as total_deposit 
                                          FROM order_items 
                                          WHERE order_id = $orderId");
                $depositRow = $depositRes->fetch_assoc();
                $totalDeposit = $depositRow['total_deposit'] ?? 0;

                $db->query("UPDATE orders SET penalty_amount = $currentPenalty WHERE id = $orderId");
                
                // [PRE-BLOCK WARNING]
                // Warn if within 1 day of deposit limit
                if ($currentPenalty < $totalDeposit && ($currentPenalty + $penaltyPerDay) >= $totalDeposit && $totalDeposit > 0) {
                    $notifMsg = "Critical Reminder: Your late penalty for Order #$orderId (₹" . number_format($currentPenalty, 2) . ") is approaching your security deposit (₹" . number_format($totalDeposit, 2) . "). Return within 24 hours to avoid an automatic account block.";
                    $db->query("INSERT INTO user_notifications (user_id, title, message, type) 
                               SELECT '$userId', '24-Hour Account Warning', '" . $db->real_escape_string($notifMsg) . "', 'warning'
                               FROM DUAL
                               WHERE (SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'user_notifications' AND table_schema = DATABASE()) > 0
                               AND NOT EXISTS (
                                   SELECT 1 FROM user_notifications 
                                   WHERE user_id = '$userId' AND type = 'warning' AND message LIKE '%Order #$orderId%' AND created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)
                               ) LIMIT 1");
                }

                // [SYSTEM AUTO-FINALIZE]
                // Block if exceeds deposit (Overriding manual unblock)
                if ($currentPenalty >= $totalDeposit && $totalDeposit > 0) {
                    // 1. Block the User & Reset manual_unblock override
                    $db->query("UPDATE users SET status = 'blocked', manual_unblock = 0 WHERE id = '$userId'");
                    
                    // 2. Finalize the Order (Stop Penalties)
                    $finalNote = "[System]: Auto-Finalized on $today because penalty (₹" . number_format($currentPenalty, 2) . ") reached security deposit.";
                    $db->query("UPDATE orders SET 
                                 status = 'Returned', 
                                 end_date = '$today',
                                 refund_status = 'blocked_penalty',
                                 special_instructions = CONCAT(IFNULL(special_instructions, ''), '\n', '" . $db->real_escape_string($finalNote) . "')
                                 WHERE id = $orderId");

                    // 3. Account Block Notification
                    $notifMsg = "Your account has been restricted because the penalty for Order #$orderId (₹" . number_format($currentPenalty, 2) . ") exceeded your security deposit. Please contact support.";
                    $db->query("INSERT INTO user_notifications (user_id, title, message, type) 
                               SELECT '$userId', 'Account Restricted', '" . $db->real_escape_string($notifMsg) . "', 'danger'
                               FROM DUAL
                               WHERE (SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'user_notifications' AND table_schema = DATABASE()) > 0
                               AND NOT EXISTS (
                                   SELECT 1 FROM user_notifications 
                                   WHERE user_id = '$userId' AND type = 'danger' AND message LIKE '%Order #$orderId%'
                               ) LIMIT 1");
                }
            } else {
                // Return Requested or Overdue but not yet past return_date (or system correction)
                $db->query("UPDATE orders SET penalty_amount = 0.00 WHERE id = $orderId");
            }
        }
    }
}
?>
