<?php
/**
 * Rental Lifecycle Functions
 */

function updateRentalStatuses($conn) {
    $today = date('Y-m-d');
    //$today = date('Y-m-d', strtotime('2026-04-11'));
    $now = date('Y-m-d H:i:s');

    // 1. Delivered -> In Use (when start_date is today or earlier)
    $stmt = mysqli_prepare($conn, "UPDATE orders SET status = 'In Use' WHERE status = 'Delivered' AND start_date <= ?");
    mysqli_stmt_bind_param($stmt, "s", $today);
    mysqli_stmt_execute($stmt);

    // 2. In Use -> Overdue (when today > return_date AND no pickup scheduled)
    $overdue_orders = mysqli_query($conn, "SELECT id, return_date, user_id FROM orders WHERE status = 'In Use' AND return_date < '$today'");
    
    while ($order = mysqli_fetch_assoc($overdue_orders)) {
        $order_id = $order['id'];
        $user_id = $order['user_id'];
        
        // Case B: Auto Pickup Scheduled
        // Set pickup to tomorrow
        $tomorrow = date('Y-m-d', strtotime('+1 day'));
        mysqli_query($conn, "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 = '$order_id'");
        
        // Add Admin Notification (only if table exists)
        $notif_check_admin = mysqli_query($conn, "SHOW TABLES LIKE 'admin_notifications'");
        if (mysqli_num_rows($notif_check_admin) > 0) {
            $notif_title = "Auto Pickup Scheduled - Order #$order_id";
            $notif_msg = "Order #$order_id is overdue. System scheduled auto pickup for $tomorrow.";
            mysqli_query($conn, "INSERT INTO admin_notifications (title, message, type) VALUES ('$notif_title', '$notif_msg', 'rental')");
        }
        
        // Add User Notification (only if table exists)
        $notif_check_user = mysqli_query($conn, "SHOW TABLES LIKE 'user_notifications'");
        if (mysqli_num_rows($notif_check_user) > 0) {
            $user_notif_msg = "Your rental #$order_id is overdue! We have scheduled an automatic pickup for tomorrow.";
            mysqli_query($conn, "INSERT INTO user_notifications (user_id, message, type) VALUES ('$user_id', '$user_notif_msg', 'overdue')");
        }
    }

    // 3. Calculate Penalties for Overdue and Return Requested Orders (if past deadline)
    // Daily penalty: ₹100 per day.
    $penalty_per_day = 30.00;
    
    $overdue_list = mysqli_query($conn, "SELECT o.id, o.return_date, o.user_id, u.manual_unblock 
                                         FROM orders o 
                                         JOIN users u ON o.user_id = u.id 
                                         WHERE o.status IN ('Overdue', 'Return Requested')");
    while ($order = mysqli_fetch_assoc($overdue_list)) {
        $order_id = $order['id'];
        $user_id = $order['user_id'];
        $manual_unblock = $order['manual_unblock'] ?? 0;
        $target_date = $order['return_date'];
        
        if (!$target_date) continue;

        $diff = (strtotime($today) - strtotime($target_date)) / (60 * 60 * 24);
        if ($diff > 0) {
            $current_penalty = round($diff * $penalty_per_day, 2);
            
            // Get total security deposit stored in order_items (captured at time of purchase)
            $deposit_res = mysqli_query($conn, "SELECT SUM(security_deposit * quantity) as total_deposit 
                                                FROM order_items 
                                                WHERE order_id = '$order_id'");
            $deposit_row = mysqli_fetch_assoc($deposit_res);
            $total_deposit = $deposit_row['total_deposit'] ?? 0;

            mysqli_query($conn, "UPDATE orders SET penalty_amount = '$current_penalty' WHERE id = '$order_id'");
            
            // [PRE-BLOCK WARNING]
            // Warn user if they are within 1 day of hitting the deposit limit
            // Formula: If (Penalty + ₹100) >= Deposit
            if ($current_penalty < $total_deposit && ($current_penalty + $penalty_per_day) >= $total_deposit && $total_deposit > 0) {
                $warning_notif_msg = mysqli_real_escape_string($conn, "Critical Reminder: Your late penalty for Order #$order_id (₹" . number_format($current_penalty, 2) . ") is approaching your security deposit (₹" . number_format($total_deposit, 2) . "). Return within 24 hours to avoid an automatic account block.");
                // Insert warning if not already sent for this order in last 24h
                mysqli_query($conn, "INSERT INTO user_notifications (user_id, title, message, type) 
                                     SELECT '$user_id', '24-Hour Account Warning', '$warning_notif_msg', 'warning'
                                     FROM DUAL
                                     WHERE NOT EXISTS (
                                         SELECT 1 FROM user_notifications 
                                         WHERE user_id = '$user_id' AND type = 'warning' AND message LIKE '%Order #$order_id%' AND created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)
                                     ) LIMIT 1");
            }

            // [SYSTEM AUTO-FINALIZE]
            // Block user and close order if penalty exceeds deposit (Overriding manual unblock)
            if ($current_penalty >= $total_deposit && $total_deposit > 0) {
                // 1. Block the User & Reset manual_unblock override
                mysqli_query($conn, "UPDATE users SET status = 'blocked', manual_unblock = 0 WHERE id = '$user_id'");
                
                // 2. Finalize the Order (Stop penalties, mark as returned-blocked)
                $final_note = mysqli_real_escape_string($conn, "[System]: Auto-Finalized on $today because penalty (₹" . number_format($current_penalty, 2) . ") reached security deposit.");
                mysqli_query($conn, "UPDATE orders SET 
                                     status = 'Returned', 
                                     end_date = '$today',
                                     refund_status = 'blocked_penalty',
                                     special_instructions = CONCAT(IFNULL(special_instructions, ''), '\n', '$final_note')
                                     WHERE id = '$order_id'");

                // 3. User Block Notification
                $block_notif_msg = mysqli_real_escape_string($conn, "Your account has been restricted because the penalty for Order #$order_id (₹" . number_format($current_penalty, 2) . ") exceeded your security deposit. Please contact support.");
                mysqli_query($conn, "INSERT INTO user_notifications (user_id, title, message, type) 
                                     SELECT '$user_id', 'Account Restricted', '$block_notif_msg', 'danger'
                                     FROM DUAL
                                     WHERE NOT EXISTS (
                                         SELECT 1 FROM user_notifications 
                                         WHERE user_id = '$user_id' AND type = 'danger' AND message LIKE '%Order #$order_id%'
                                     ) LIMIT 1");
            }
        } else {
            mysqli_query($conn, "UPDATE orders SET penalty_amount = '0.00' WHERE id = '$order_id'");
        }
    }
}
?>
