<?php
require_once __DIR__ . '/../../../../helpers/response.php';
require_once __DIR__ . '/../../../../helpers/validation.php';
require_once __DIR__ . '/../../../Middleware/VendorAuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class InterviewController {
    
    public function index() {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $status = $_GET['status'] ?? null;
        $db = Database::getInstance();

        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $countSql = "
            SELECT COUNT(*)
            FROM interview_requests ir
            WHERE ir.vendor_id = ?
        ";
        
        $sql = "
            SELECT ir.*, c.full_name as customer_name, m.full_name as maid_name, ip.name as platform_name
            FROM interview_requests ir
            JOIN customers c ON ir.customer_id = c.id
            JOIN maids m ON ir.maid_id = m.id
            LEFT JOIN interview_platforms ip ON ir.platform_id = ip.id
            WHERE ir.vendor_id = ?
        ";
        
        $params = [$vendorId];
        if ($status) {
            $countSql .= " AND ir.status = ?";
            $sql .= " AND ir.status = ?";
            $params[] = $status;
        }
        
        $sql .= " ORDER BY ir.interview_date DESC, ir.time_from DESC LIMIT " . intval($limit) . " OFFSET " . intval($offset);
        
        // Count
        $totalStmt = $db->prepare($countSql);
        $totalStmt->execute($params);
        $total = (int) $totalStmt->fetchColumn();

        // Select
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $interviews = $stmt->fetchAll();

        foreach ($interviews as &$ir) {
            $ir['translation_enabled'] = intval($ir['translation_enabled'] ?? 0) === 1;
            $ir['notify_app'] = intval($ir['notify_app'] ?? 0) === 1;
            $ir['notify_whatsapp'] = intval($ir['notify_whatsapp'] ?? 0) === 1;
            $ir['notify_email'] = intval($ir['notify_email'] ?? 0) === 1;
            $ir['notify_call'] = intval($ir['notify_call'] ?? 0) === 1;
        }
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Interviews loaded successfully.', ['interviews' => $interviews], $pagination);
    }

    public function updateStatus($id) {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $errors = validateRequired($data, ['status']);
        if (!empty($errors)) {
            sendError('Validation error', $errors, 422);
        }
        
        $allowedStatuses = ['confirmed', 'rejected', 'completed', 'cancelled', 'rescheduled'];
        if (!in_array($data['status'], $allowedStatuses)) {
            sendError('Invalid status', ['allowed' => $allowedStatuses], 422);
        }
        
        $db = Database::getInstance();
        
        // Find request
        $stmt = $db->prepare("SELECT * FROM interview_requests WHERE id = ? AND vendor_id = ? LIMIT 1");
        $stmt->execute([$id, $vendorId]);
        $request = $stmt->fetch();
        
        if (!$request) {
            sendError('Interview request not found or access denied', [], 404);
        }
        
        if ($data['status'] === 'cancelled') {
            $cancelReason = $data['cancel_reason'] ?? null;
            if (empty($cancelReason)) {
                sendError('Validation error', ['cancel_reason' => 'Cancellation reason is required.'], 422);
            }
            $cancelMessage = $data['cancel_message'] ?? null;
            if ($cancelMessage) {
                $cancelReason = $cancelReason . ' - ' . $cancelMessage;
            }
            
            $db->prepare("UPDATE interview_requests SET status = ?, cancel_reason = ?, updated_at = NOW() WHERE id = ? AND vendor_id = ?")
               ->execute([$data['status'], $cancelReason, $id, $vendorId]);
               
            sendResponse([], 'Interview request cancelled successfully.');
            return;
        }
        
        if ($data['status'] === 'rescheduled') {
            $errors = validateRequired($data, ['interview_date', 'time_from', 'time_to']);
            if (!empty($errors)) {
                sendError('Validation error', $errors, 422);
            }
            
            $date = date('Y-m-d', strtotime($data['interview_date']));
            $timeFrom = date('H:i:s', strtotime($data['time_from']));
            $timeTo = date('H:i:s', strtotime($data['time_to']));
            
            $notes = $data['notes'] ?? $data['vendor_notes'] ?? null;
            
            $updateSql = "UPDATE interview_requests SET status = ?, interview_date = ?, time_from = ?, time_to = ?";
            $params = [$data['status'], $date, $timeFrom, $timeTo];
            if ($notes !== null) {
                $updateSql .= ", vendor_notes = ?";
                $params[] = htmlspecialchars($notes);
            }
            $updateSql .= ", updated_at = NOW() WHERE id = ? AND vendor_id = ?";
            $params[] = $id;
            $params[] = $vendorId;
            
            $db->prepare($updateSql)->execute($params);
            sendResponse([], 'Interview request rescheduled successfully.');
            return;
        }
        
        // Handle confirmed and other statuses
        $updateSql = "UPDATE interview_requests SET status = ?, updated_at = NOW()";
        $params = [$data['status']];
        
        if ($data['status'] === 'confirmed') {
            $meetingLink = $data['meeting_link'] ?? null;
            $roomId = $request['meeting_room_id'] ?? null;
            if (empty($meetingLink)) {
                $randomCode = substr(md5(uniqid(rand(), true)), 0, 3) . '-' . substr(md5(uniqid(rand(), true)), 3, 4) . '-' . substr(md5(uniqid(rand(), true)), 7, 3);
                $meetingLink = "https://meet.google.com/" . strtolower($randomCode);
            }
            if (empty($roomId)) {
                $roomId = 'room-' . substr(md5(uniqid(rand(), true)), 0, 8);
            }
            $updateSql .= ", meeting_link = ?, meeting_room_id = ?";
            $params[] = $meetingLink;
            $params[] = $roomId;
        } else {
            if (isset($data['meeting_link'])) {
                $updateSql .= ", meeting_link = ?";
                $params[] = htmlspecialchars($data['meeting_link']);
            }
        }
        
        $notes = $data['notes'] ?? $data['vendor_notes'] ?? null;
        if ($notes !== null) {
            $updateSql .= ", vendor_notes = ?";
            $params[] = htmlspecialchars($notes);
        }
        
        $updateSql .= " WHERE id = ? AND vendor_id = ?";
        $params[] = $id;
        $params[] = $vendorId;
        
        $db->prepare($updateSql)->execute($params);
        
        sendResponse([], 'Interview status updated successfully.');
    }

    public function reschedule($id) {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $errors = validateRequired($data, ['interview_date', 'time_from', 'time_to']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }
        
        $db = Database::getInstance();
        
        // Fetch current interview details
        $stmt = $db->prepare("SELECT * FROM interview_requests WHERE id = ? AND vendor_id = ? LIMIT 1");
        $stmt->execute([$id, $vendorId]);
        $interview = $stmt->fetch();
        
        if (!$interview) {
            sendError('Interview request not found or access denied', [], 404);
        }
        
        if ($interview['status'] === 'cancelled' || $interview['status'] === 'completed' || $interview['status'] === 'rejected') {
            sendError('Cannot reschedule interview in its current state', [], 400);
        }
        
        // Validate proposed new time
        $dateStr = $data['interview_date'];
        $timeFromStr = $data['time_from'];
        $timeToStr = $data['time_to'];
        
        $d = DateTime::createFromFormat('Y-m-d', $dateStr);
        if (!$d || $d->format('Y-m-d') !== $dateStr) {
            sendError('Validation failed', ['interview_date' => 'Invalid date format. Expected YYYY-MM-DD.'], 422);
        }
        
        if (strtotime($timeFromStr) >= strtotime($timeToStr)) {
            sendError('Validation failed', ['time_from' => 'Start time must be before end time.'], 422);
        }
        
        $isToday = ($dateStr === date('Y-m-d'));
        if (strtotime($dateStr) < strtotime(date('Y-m-d'))) {
            sendError('Validation failed', ['interview_date' => 'The selected date cannot be in the past.'], 422);
        }
        if ($isToday && strtotime($timeFromStr) < strtotime(date('H:i:s'))) {
            sendError('Validation failed', ['time_from' => 'The selected start time cannot be in the past.'], 422);
        }
        
        // Check vendor availability
        $dayOfWeek = strtolower(date('l', strtotime($dateStr)));
        
        $stmtAvail = $db->prepare("
            SELECT * FROM vendor_interview_availability 
            WHERE vendor_id = ? AND day_of_week = ?
        ");
        $stmtAvail->execute([$vendorId, $dayOfWeek]);
        $availabilities = $stmtAvail->fetchAll();
        
        $stmtCount = $db->prepare("SELECT COUNT(*) FROM vendor_interview_availability WHERE vendor_id = ?");
        $stmtCount->execute([$vendorId]);
        $hasAnyAvailability = $stmtCount->fetchColumn() > 0;
        
        $isValidSlot = false;
        if ($hasAnyAvailability) {
            foreach ($availabilities as $av) {
                if (intval($av['is_available']) === 1) {
                    if ($timeFromStr >= $av['time_from'] && $timeToStr <= $av['time_to']) {
                        $isValidSlot = true;
                        break;
                    }
                }
            }
        } else {
            // Fallback: UAE Sun-Thu 9 AM - 6 PM
            if (in_array($dayOfWeek, ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday'])) {
                if ($timeFromStr >= '09:00:00' && $timeToStr <= '18:00:00') {
                    $isValidSlot = true;
                }
            }
        }
        
        if (!$isValidSlot) {
            sendError('Validation failed', ['time_from' => 'The selected time is outside the vendor\'s available working hours for this day.'], 422);
        }
        
        // Overlap Check (exclude current request)
        $stmtOverlaps = $db->prepare("
            SELECT COUNT(*) FROM interview_requests 
            WHERE maid_id = ? AND interview_date = ? AND status NOT IN ('cancelled', 'rejected')
            AND id != ? AND time_from < ? AND time_to > ?
        ");
        $stmtOverlaps->execute([$interview['maid_id'], $dateStr, $id, $timeToStr, $timeFromStr]);
        $hasOverlap = $stmtOverlaps->fetchColumn() > 0;
        
        if ($hasOverlap) {
            sendError('Validation failed', ['time_from' => 'The selected time slot overlaps with an existing booking for this maid.'], 422);
        }
        
        $notes = $data['notes'] ?? $data['vendor_notes'] ?? null;
        
        // Begin transaction
        $db->beginTransaction();
        try {
            // Insert reschedule request record
            $stmtResched = $db->prepare("
                INSERT INTO interview_reschedules (
                    interview_request_id, requested_by, 
                    old_date, old_time_from, old_time_to, 
                    new_date, new_time_from, new_time_to, status
                ) VALUES (?, 'vendor', ?, ?, ?, ?, ?, ?, 'pending')
            ");
            $stmtResched->execute([
                $id,
                $interview['interview_date'],
                $interview['time_from'],
                $interview['time_to'],
                $dateStr,
                $timeFromStr,
                $timeToStr
            ]);
            
            // Update main interview request status to rescheduled and new times
            $updateSql = "UPDATE interview_requests SET status = 'rescheduled', interview_date = ?, time_from = ?, time_to = ?";
            $params = [$dateStr, $timeFromStr, $timeToStr];
            if ($notes !== null) {
                $updateSql .= ", vendor_notes = ?";
                $params[] = htmlspecialchars($notes);
            }
            $updateSql .= ", updated_at = NOW() WHERE id = ?";
            $params[] = $id;
            
            $db->prepare($updateSql)->execute($params);
            
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to reschedule interview request: ' . $e->getMessage(), [], 500);
        }
        
        sendResponse([], 'Interview request rescheduled successfully.');
    }

    public function getAvailability() {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $db = Database::getInstance();
        
        // Get settings
        $settingsStmt = $db->prepare("SELECT * FROM vendor_interview_settings WHERE vendor_id = ? LIMIT 1");
        $settingsStmt->execute([$vendorId]);
        $settings = $settingsStmt->fetch() ?: [
            'timezone' => 'Asia/Dubai',
            'duration_minutes' => 45
        ];
        
        // Get working days & hours
        $availabilityStmt = $db->prepare("SELECT * FROM vendor_interview_availability WHERE vendor_id = ?");
        $availabilityStmt->execute([$vendorId]);
        $availability = $availabilityStmt->fetchAll();
        
        sendResponse([
            'settings' => $settings,
            'availability' => $availability
        ], 'Interview availability retrieved.');
    }

    public function saveAvailability() {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true);
        if (!isset($data['slots']) || !is_array($data['slots'])) {
            sendError('Availability slots are required', [], 422);
        }
        
        $db = Database::getInstance();
        
        try {
            $db->beginTransaction();
            
            // Delete old slots
            $db->prepare("DELETE FROM vendor_interview_availability WHERE vendor_id = ?")->execute([$vendorId]);
            
            // Insert new slots
            $stmt = $db->prepare("
                INSERT INTO vendor_interview_availability (vendor_id, day_of_week, is_available, time_from, time_to)
                VALUES (?, ?, ?, ?, ?)
            ");
            
            foreach ($data['slots'] as $slot) {
                $stmt->execute([
                    $vendorId,
                    $slot['day_of_week'],
                    $slot['is_available'] ?? 1,
                    $slot['time_from'],
                    $slot['time_to']
                ]);
            }
            
            $db->commit();
            sendResponse([], 'Availability schedule saved successfully.');
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to save availability', ['error' => $e->getMessage()], 500);
        }
    }

    public function getSettings() {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $db = Database::getInstance();
        
        $settingsStmt = $db->prepare("SELECT * FROM vendor_interview_settings WHERE vendor_id = ? LIMIT 1");
        $settingsStmt->execute([$vendorId]);
        $settings = $settingsStmt->fetch();
        
        if (!$settings) {
            $settings = [
                'timezone' => 'Asia/Dubai',
                'duration_minutes' => 45
            ];
        }
        
        $availabilityStmt = $db->prepare("SELECT * FROM vendor_interview_availability WHERE vendor_id = ? ORDER BY id ASC");
        $availabilityStmt->execute([$vendorId]);
        $rawAvailability = $availabilityStmt->fetchAll();
        
        $days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
        $availability = [];
        foreach ($days as $day) {
            $availability[$day] = [
                'day_of_week' => $day,
                'is_available' => false,
                'slots' => []
            ];
        }
        
        foreach ($rawAvailability as $row) {
            $day = strtolower($row['day_of_week']);
            if (isset($availability[$day])) {
                $availability[$day]['is_available'] = (bool)$row['is_available'];
                if ($row['is_available'] && $row['time_from'] && $row['time_to']) {
                    $availability[$day]['slots'][] = [
                        'from' => date('h:i A', strtotime($row['time_from'])),
                        'to' => date('h:i A', strtotime($row['time_to']))
                    ];
                }
            }
        }
        
        if (empty($rawAvailability)) {
            foreach (['monday', 'tuesday', 'wednesday', 'thursday', 'friday'] as $d) {
                $availability[$d]['is_available'] = true;
                $availability[$d]['slots'][] = ['from' => '09:00 AM', 'to' => '06:00 PM'];
            }
        }
        
        $availabilityList = array_values($availability);
        
        sendResponse([
            'timezone' => $settings['timezone'] ?? 'Asia/Dubai',
            'duration_minutes' => (int)($settings['duration_minutes'] ?? 45),
            'availability' => $availabilityList
        ], 'Interview settings retrieved.');
    }

    public function saveSettings() {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        
        $db = Database::getInstance();
        
        try {
            $db->beginTransaction();
            
            $timezone = $data['timezone'] ?? 'Asia/Dubai';
            $duration = (int)($data['duration_minutes'] ?? 45);
            
            $stmt = $db->prepare("SELECT id FROM vendor_interview_settings WHERE vendor_id = ? LIMIT 1");
            $stmt->execute([$vendorId]);
            $exists = $stmt->fetchColumn();
            
            if ($exists) {
                $db->prepare("
                    UPDATE vendor_interview_settings 
                    SET timezone = ?, duration_minutes = ?, updated_at = NOW() 
                    WHERE vendor_id = ?
                ")->execute([$timezone, $duration, $vendorId]);
            } else {
                $db->prepare("
                    INSERT INTO vendor_interview_settings (vendor_id, timezone, duration_minutes) 
                    VALUES (?, ?, ?)
                ")->execute([$vendorId, $timezone, $duration]);
            }
            
            if (isset($data['availability']) && is_array($data['availability'])) {
                $db->prepare("DELETE FROM vendor_interview_availability WHERE vendor_id = ?")->execute([$vendorId]);
                
                $insertStmt = $db->prepare("
                    INSERT INTO vendor_interview_availability (vendor_id, day_of_week, is_available, time_from, time_to)
                    VALUES (?, ?, ?, ?, ?)
                ");
                
                foreach ($data['availability'] as $dayData) {
                    $dayOfWeek = strtolower($dayData['day_of_week'] ?? '');
                    $isAvailable = isset($dayData['is_available']) ? ($dayData['is_available'] ? 1 : 0) : 0;
                    
                    if ($isAvailable) {
                        $slots = $dayData['slots'] ?? [];
                        if (empty($slots)) {
                            $insertStmt->execute([$vendorId, $dayOfWeek, 1, '09:00:00', '18:00:00']);
                        } else {
                            foreach ($slots as $slot) {
                                $timeFrom = null;
                                $timeTo = null;
                                if (!empty($slot['from'])) {
                                    $timeFrom = date('H:i:s', strtotime($slot['from']));
                                }
                                if (!empty($slot['to'])) {
                                    $timeTo = date('H:i:s', strtotime($slot['to']));
                                }
                                $insertStmt->execute([$vendorId, $dayOfWeek, 1, $timeFrom, $timeTo]);
                            }
                        }
                    } else {
                        $insertStmt->execute([$vendorId, $dayOfWeek, 0, null, null]);
                    }
                }
            }
            
            $db->commit();
            sendResponse([], 'Interview settings saved successfully.');
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to save settings', ['error' => $e->getMessage()], 500);
        }
    }



    public function show($id) {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $db = Database::getInstance();
        
        $stmt = $db->prepare("
            SELECT ir.*, 
                   c.full_name as customer_name, c.profile_image as customer_avatar, c.created_at as customer_created_at,
                   m.full_name as maid_name, m.profile_image as maid_avatar, 
                   COALESCE((SELECT AVG(rating) FROM reviews WHERE maid_id = m.id), 5.0) as maid_rating, 
                   m.years_experience as maid_experience_years, m.bio as maid_about,
                   ip.name as platform_name, ip.icon as platform_icon,
                   nat.name_en as maid_nationality_name,
                   sm.name_en as maid_contract_badge
            FROM interview_requests ir
            JOIN customers c ON ir.customer_id = c.id
            JOIN maids m ON ir.maid_id = m.id
            LEFT JOIN interview_platforms ip ON ir.platform_id = ip.id
            LEFT JOIN nationalities nat ON m.nationality_id = nat.id
            LEFT JOIN service_models sm ON m.service_model_id = sm.id
            WHERE ir.id = ? AND ir.vendor_id = ?
            LIMIT 1
        ");
        $stmt->execute([$id, $vendorId]);
        $ir = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$ir) {
            sendError('Interview request not found or access denied', [], 404);
        }
        
        // Format boolean and numeric values
        $ir['translation_enabled'] = intval($ir['translation_enabled'] ?? 0) === 1;
        $ir['notify_app'] = intval($ir['notify_app'] ?? 0) === 1;
        $ir['notify_whatsapp'] = intval($ir['notify_whatsapp'] ?? 0) === 1;
        $ir['notify_email'] = intval($ir['notify_email'] ?? 0) === 1;
        $ir['notify_call'] = intval($ir['notify_call'] ?? 0) === 1;
        
        $ir['customer_member_since'] = $ir['customer_created_at'] ? date('Y', strtotime($ir['customer_created_at'])) : '2022';
        
        if ($ir['time_from'] && $ir['time_to']) {
            $durationMin = round((strtotime($ir['time_to']) - strtotime($ir['time_from'])) / 60);
            $ir['interview_duration_minutes'] = $durationMin;
            $ir['formatted_time_range'] = date('h:i A', strtotime($ir['time_from'])) . ' — ' . date('h:i A', strtotime($ir['time_to'])) . ' (' . $durationMin . ' min)';
        } else {
            $ir['interview_duration_minutes'] = 90;
            $ir['formatted_time_range'] = '';
        }
        
        $ir['maid_nationality_name'] = $ir['maid_nationality_name'] ?: 'Philippines';
        $ir['maid_experience_formatted'] = ($ir['maid_experience_years'] ?: '5') . ' yrs exp';
        $ir['maid_rating'] = floatval($ir['maid_rating'] ?: 4.9);
        $ir['maid_contract_badge'] = $ir['maid_contract_badge'] ?: 'MONTHLY CONTRACT';

        sendResponse($ir, 'Interview request details loaded successfully.');
    }


    public function getInterviewAvailability($id) {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];
        
        $db = Database::getInstance();
        
        // Find interview request
        $stmt = $db->prepare("SELECT * FROM interview_requests WHERE id = ? AND vendor_id = ? LIMIT 1");
        $stmt->execute([$id, $vendorId]);
        $ir = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$ir) {
            sendError('Interview request not found or access denied', [], 404);
        }
        
        $dateStr = $_GET['date'] ?? null;
        if (!$dateStr) {
            $dateStr = $ir['interview_date'];
        }
        
        $d = DateTime::createFromFormat('Y-m-d', $dateStr);
        if (!$d || $d->format('Y-m-d') !== $dateStr) {
            sendError('Invalid date format. Expected YYYY-MM-DD.', [], 422);
        }
        
        $dayOfWeek = strtolower(date('l', strtotime($dateStr)));
        
        // Fetch availability slots of this vendor for this day
        $stmtAvail = $db->prepare("
            SELECT * FROM vendor_interview_availability 
            WHERE vendor_id = ? AND day_of_week = ? AND is_available = 1
        ");
        $stmtAvail->execute([$vendorId, $dayOfWeek]);
        $availabilities = $stmtAvail->fetchAll(PDO::FETCH_ASSOC);
        
        // Fallback to default working hours (Sun-Thu 9 AM - 6 PM) if vendor has no availability configured at all
        $stmtCount = $db->prepare("SELECT COUNT(*) FROM vendor_interview_availability WHERE vendor_id = ?");
        $stmtCount->execute([$vendorId]);
        $hasAnyAvailability = $stmtCount->fetchColumn() > 0;
        
        if (!$hasAnyAvailability) {
            if (in_array($dayOfWeek, ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday'])) {
                $availabilities = [
                    [
                        'time_from' => '09:00:00',
                        'time_to' => '18:00:00'
                    ]
                ];
            } else {
                $availabilities = [];
            }
        }
        
        // Fetch duration
        $stmtSettings = $db->prepare("SELECT duration_minutes FROM vendor_interview_settings WHERE vendor_id = ? LIMIT 1");
        $stmtSettings->execute([$vendorId]);
        $duration = $stmtSettings->fetchColumn() ?: 45;
        
        // Generate slots
        $allSlots = [];
        foreach ($availabilities as $av) {
            $start = strtotime($av['time_from']);
            $end = strtotime($av['time_to']);
            $durationSec = $duration * 60;
            
            for ($time = $start; $time + $durationSec <= $end; $time += $durationSec) {
                $slotStart = date('H:i:s', $time);
                $slotEnd = date('H:i:s', $time + $durationSec);
                
                $allSlots[] = [
                    'from' => $slotStart,
                    'to' => $slotEnd,
                    'from_formatted' => date('h:i A', $time),
                    'to_formatted' => date('h:i A', $time + $durationSec)
                ];
            }
        }
        
        // Fetch booked interviews for this maid on this date (excluding current interview being rescheduled)
        $stmtBooked = $db->prepare("
            SELECT time_from, time_to FROM interview_requests 
            WHERE maid_id = ? AND interview_date = ? AND id != ? AND status NOT IN ('cancelled', 'rejected')
        ");
        $stmtBooked->execute([$ir['maid_id'], $dateStr, $id]);
        $bookedInterviews = $stmtBooked->fetchAll(PDO::FETCH_ASSOC);
        
        $now = time();
        $isToday = ($dateStr === date('Y-m-d'));
        
        $finalSlots = [];
        foreach ($allSlots as $slot) {
            if ($isToday) {
                $currentDubaiTime = date('H:i:s');
                if ($slot['from'] < $currentDubaiTime) {
                    continue; // Skip past slots for today
                }
            }
            
            // Check status: selected, taken, or available
            $status = 'available';
            
            // If it matches the current scheduled slot of THIS interview, it's 'selected'
            if ($dateStr === $ir['interview_date'] && 
                date('H:i:s', strtotime($slot['from'])) === date('H:i:s', strtotime($ir['time_from'])) && 
                date('H:i:s', strtotime($slot['to'])) === date('H:i:s', strtotime($ir['time_to']))) {
                $status = 'selected';
            } else {
                // Check if it overlaps with any other booked interview
                $overlaps = false;
                foreach ($bookedInterviews as $booked) {
                    if ($slot['from'] < $booked['time_to'] && $slot['to'] > $booked['time_from']) {
                        $overlaps = true;
                        break;
                    }
                }
                if ($overlaps) {
                    $status = 'taken';
                }
            }
            
            $slot['status'] = $status;
            $finalSlots[] = $slot;
        }
        
        sendResponse([
            'interview_id' => intval($id),
            'maid_id' => intval($ir['maid_id']),
            'date' => $dateStr,
            'duration_minutes' => intval($duration),
            'slots' => $finalSlots
        ], 'Interview reschedule slots loaded successfully.');
    }
}
