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

class InterviewController {
    
    public function create() {
        // Authenticate customer
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['vendor_id', 'maid_id', 'interview_date', 'time_from', 'time_to']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }

        $db = Database::getInstance();

        // Verify maid exists
        $stmt = $db->prepare("SELECT id FROM maids WHERE id = ?");
        $stmt->execute([$data['maid_id']]);
        if (!$stmt->fetch()) {
            sendError('Validation failed', ['maid_id' => 'Selected maid does not exist'], 422);
        }

        // Verify vendor exists
        $stmt = $db->prepare("SELECT id FROM vendors WHERE id = ?");
        $stmt->execute([$data['vendor_id']]);
        if (!$stmt->fetch()) {
            sendError('Validation failed', ['vendor_id' => 'Selected vendor does not exist'], 422);
        }

        // Verify platform exists (if provided)
        $platformId = !empty($data['platform_id']) ? $data['platform_id'] : null;
        if ($platformId) {
            $stmt = $db->prepare("SELECT id FROM interview_platforms WHERE id = ?");
            $stmt->execute([$platformId]);
            if (!$stmt->fetch()) {
                sendError('Validation failed', ['platform_id' => 'Selected interview platform does not exist'], 422);
            }
        }

        // 1. Time validations
        $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);
        }

        // 2. Vendor availability check
        $dayOfWeek = strtolower(date('l', strtotime($dateStr)));
        $vendorId = $data['vendor_id'];

        $stmtAvail = $db->prepare("
            SELECT * FROM vendor_interview_availability 
            WHERE vendor_id = ? AND day_of_week = ?
        ");
        $stmtAvail->execute([$vendorId, $dayOfWeek]);
        $availabilities = $stmtAvail->fetchAll();

        // Check if there are availability records configured for this vendor
        $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: Monday-Friday 09:00:00 to 18:00:00
            if (in_array($dayOfWeek, ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'])) {
                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);
        }

        // 3. Clashing bookings check
        $stmtOverlaps = $db->prepare("
            SELECT COUNT(*) FROM interview_requests 
            WHERE maid_id = ? AND interview_date = ? AND status NOT IN ('cancelled', 'rejected')
            AND time_from < ? AND time_to > ?
        ");
        $stmtOverlaps->execute([$data['maid_id'], $dateStr, $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);
        }


        $translationEnabled = isset($data['translation_enabled']) ? ($data['translation_enabled'] ? 1 : 0) : 0;
        $customerLanguage = !empty($data['customer_language']) ? $data['customer_language'] : null;
        $helperLanguage = !empty($data['helper_language']) ? $data['helper_language'] : null;
        $notifyApp = isset($data['notify_app']) ? ($data['notify_app'] ? 1 : 0) : 1;
        $notifyWhatsapp = isset($data['notify_whatsapp']) ? ($data['notify_whatsapp'] ? 1 : 0) : 0;
        $notifyEmail = isset($data['notify_email']) ? ($data['notify_email'] ? 1 : 0) : 0;
        $notifyCall = isset($data['notify_call']) ? ($data['notify_call'] ? 1 : 0) : 0;

        $stmt = $db->prepare("
            INSERT INTO interview_requests (
                customer_id, vendor_id, maid_id, platform_id, 
                interview_date, time_from, time_to, customer_notes, status,
                translation_enabled, customer_language, helper_language,
                notify_app, notify_whatsapp, notify_email, notify_call
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $customerId,
            $data['vendor_id'],
            $data['maid_id'],
            $platformId,
            $data['interview_date'],
            $data['time_from'],
            $data['time_to'],
            !empty($data['customer_notes']) ? $data['customer_notes'] : null,
            $translationEnabled,
            $customerLanguage,
            $helperLanguage,
            $notifyApp,
            $notifyWhatsapp,
            $notifyEmail,
            $notifyCall
        ]);

        $interviewId = $db->lastInsertId();

        // Fetch inserted interview details
        $stmt = $db->prepare("
            SELECT ir.*, v.agency_name as vendor_name, v.logo as vendor_logo, m.full_name as maid_name, m.profile_image as maid_image, p.name as platform_name
            FROM interview_requests ir
            LEFT JOIN vendors v ON ir.vendor_id = v.id
            LEFT JOIN maids m ON ir.maid_id = m.id
            LEFT JOIN interview_platforms p ON ir.platform_id = p.id
            WHERE ir.id = ?
        ");
        $stmt->execute([$interviewId]);
        $interviewDetails = $stmt->fetch();

        if ($interviewDetails) {
            $interviewDetails['translation_enabled'] = intval($interviewDetails['translation_enabled']) === 1;
            $interviewDetails['notify_app'] = intval($interviewDetails['notify_app']) === 1;
            $interviewDetails['notify_whatsapp'] = intval($interviewDetails['notify_whatsapp']) === 1;
            $interviewDetails['notify_email'] = intval($interviewDetails['notify_email']) === 1;
            $interviewDetails['notify_call'] = intval($interviewDetails['notify_call']) === 1;
        }

        sendResponse($interviewDetails, 'Interview request submitted successfully', 201);
    }

    private function formatDateDisplay($dateStr) {
        $targetTime = strtotime($dateStr);
        $today = strtotime(date('Y-m-d'));
        $tomorrow = strtotime(date('Y-m-d', strtotime('+1 day')));
        
        if ($targetTime === $today) {
            return 'Today';
        } elseif ($targetTime === $tomorrow) {
            return 'Tomorrow';
        } else {
            return date('l, M d', $targetTime); // e.g. "Thursday, Oct 24"
        }
    }

    public function index() {
        // Authenticate customer
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $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;

        $totalStmt = $db->prepare("SELECT COUNT(*) FROM interview_requests WHERE customer_id = ?");
        $totalStmt->execute([$customerId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT ir.*, 
                   v.agency_name as vendor_name, v.logo as vendor_logo, v.is_verified as vendor_verified,
                   m.full_name as maid_name, m.profile_image as maid_image, m.bio as maid_bio, m.years_experience as maid_experience,
                   n.name_en as maid_nationality_name,
                   p.name as platform_name
            FROM interview_requests ir
            LEFT JOIN vendors v ON ir.vendor_id = v.id
            LEFT JOIN maids m ON ir.maid_id = m.id
            LEFT JOIN nationalities n ON m.nationality_id = n.id
            LEFT JOIN interview_platforms p ON ir.platform_id = p.id
            WHERE ir.customer_id = ?
            ORDER BY ir.interview_date DESC, ir.time_from DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$customerId]);
        $interviews = $stmt->fetchAll();

        foreach ($interviews as &$ir) {
            // Cast Booleans
            $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;
            
            // Format ID
            $ir['reference_id'] = 'AZ-' . str_pad($ir['id'], 5, '0', STR_PAD_LEFT);
            
            // Get Maid Rating
            $stmtRating = $db->prepare("
                SELECT COALESCE(AVG(rating), 5.0) as rating, COUNT(id) as reviews_count 
                FROM reviews 
                WHERE maid_id = ? AND status = 'approved'
            ");
            $stmtRating->execute([$ir['maid_id']]);
            $ratingDetails = $stmtRating->fetch();
            $ir['maid_rating'] = floatval($ratingDetails['rating']);
            $ir['maid_reviews_count'] = intval($ratingDetails['reviews_count']);
            
            // Date formatting
            $ir['date_formatted'] = $this->formatDateDisplay($ir['interview_date']);
            $ir['time_formatted'] = date('h:i A', strtotime($ir['time_from']));
            $ir['datetime_formatted'] = $ir['date_formatted'] . ' • ' . $ir['time_formatted'];
            
            // Timing states
            $interviewStartStr = $ir['interview_date'] . ' ' . $ir['time_from'];
            $interviewStartTimestamp = strtotime($interviewStartStr);
            $timeDiffSeconds = $interviewStartTimestamp - time();
            
            $ir['is_upcoming'] = (strtotime($ir['interview_date'] . ' ' . $ir['time_to']) >= time());
            
            $statusBadge = 'Awaiting Confirmation';
            if ($ir['status'] === 'confirmed') {
                $statusBadge = 'Confirmed';
                if ($timeDiffSeconds > 0 && $timeDiffSeconds <= 900) {
                    $minutes = ceil($timeDiffSeconds / 60);
                    $statusBadge = "Starts in {$minutes}m";
                }
            } elseif ($ir['status'] === 'cancelled') {
                $statusBadge = 'Cancelled';
            } elseif ($ir['status'] === 'completed') {
                $statusBadge = 'Completed';
            } elseif ($ir['status'] === 'rejected') {
                $statusBadge = 'Rejected';
            }
            $ir['status_badge'] = $statusBadge;
        }

        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

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

    public function show($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT ir.*, 
                   v.agency_name as vendor_name, v.logo as vendor_logo, v.is_verified as vendor_verified,
                   m.full_name as maid_name, m.profile_image as maid_image, m.bio as maid_bio, m.years_experience as maid_experience,
                   n.name_en as maid_nationality_name,
                   p.name as platform_name
            FROM interview_requests ir
            LEFT JOIN vendors v ON ir.vendor_id = v.id
            LEFT JOIN maids m ON ir.maid_id = m.id
            LEFT JOIN nationalities n ON m.nationality_id = n.id
            LEFT JOIN interview_platforms p ON ir.platform_id = p.id
            WHERE ir.id = ? AND ir.customer_id = ?
            LIMIT 1
        ");
        $stmt->execute([$id, $customerId]);
        $ir = $stmt->fetch();

        if (!$ir) {
            sendError('Interview request not found', [], 404);
        }

        // Cast Booleans
        $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;
        
        // Format ID
        $ir['reference_id'] = 'AZ-' . str_pad($ir['id'], 5, '0', STR_PAD_LEFT);
        
        // Get Maid Rating
        $stmtRating = $db->prepare("
            SELECT COALESCE(AVG(rating), 5.0) as rating, COUNT(id) as reviews_count 
            FROM reviews 
            WHERE maid_id = ? AND status = 'approved'
        ");
        $stmtRating->execute([$ir['maid_id']]);
        $ratingDetails = $stmtRating->fetch();
        $ir['maid_rating'] = floatval($ratingDetails['rating']);
        $ir['maid_reviews_count'] = intval($ratingDetails['reviews_count']);
        
        // Date formatting
        $ir['date_formatted'] = $this->formatDateDisplay($ir['interview_date']);
        $ir['time_formatted'] = date('h:i A', strtotime($ir['time_from']));
        $ir['datetime_formatted'] = $ir['date_formatted'] . ' • ' . $ir['time_formatted'];
        
        // Timing states
        $interviewStartStr = $ir['interview_date'] . ' ' . $ir['time_from'];
        $interviewStartTimestamp = strtotime($interviewStartStr);
        $timeDiffSeconds = $interviewStartTimestamp - time();
        
        $ir['is_upcoming'] = (strtotime($ir['interview_date'] . ' ' . $ir['time_to']) >= time());
        
        $statusBadge = 'Awaiting Confirmation';
        if ($ir['status'] === 'confirmed') {
            $statusBadge = 'Confirmed';
            if ($timeDiffSeconds > 0 && $timeDiffSeconds <= 900) {
                $minutes = ceil($timeDiffSeconds / 60);
                $statusBadge = "Starts in {$minutes}m";
            }
        } elseif ($ir['status'] === 'cancelled') {
            $statusBadge = 'Cancelled';
        } elseif ($ir['status'] === 'completed') {
            $statusBadge = 'Completed';
        } elseif ($ir['status'] === 'rejected') {
            $statusBadge = 'Rejected';
        }
        $ir['status_badge'] = $statusBadge;

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

    public function cancel($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $db = Database::getInstance();
        
        $stmt = $db->prepare("SELECT id, status FROM interview_requests WHERE id = ? AND customer_id = ?");
        $stmt->execute([$id, $customerId]);
        $interview = $stmt->fetch();

        if (!$interview) {
            sendError('Interview request not found', [], 404);
        }

        if ($interview['status'] === 'cancelled' || $interview['status'] === 'completed') {
            sendError('Cannot cancel interview in its current state', [], 400);
        }

        $cancelReason = !empty($data['cancel_reason']) ? $data['cancel_reason'] : 'Cancelled by customer';

        $stmt = $db->prepare("UPDATE interview_requests SET status = 'cancelled', cancel_reason = ? WHERE id = ?");
        $stmt->execute([$cancelReason, $id]);

        sendResponse([], 'Interview request cancelled successfully');
    }

    public function getMaidAvailability($maidId) {
        $db = Database::getInstance();
        
        // Verify maid exists and is published
        $stmt = $db->prepare("SELECT id, vendor_id, full_name FROM maids WHERE id = ? AND status = 'published' LIMIT 1");
        $stmt->execute([$maidId]);
        $maid = $stmt->fetch();
        if (!$maid) {
            sendError('Maid not found', [], 404);
        }
        
        $vendorId = $maid['vendor_id'];
        
        $dateStr = $_GET['date'] ?? null;
        if (!$dateStr) {
            $dateStr = date('Y-m-d');
        }
        
        $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
        $stmt = $db->prepare("
            SELECT * FROM vendor_interview_availability 
            WHERE vendor_id = ? AND day_of_week = ? AND is_available = 1
        ");
        $stmt->execute([$vendorId, $dayOfWeek]);
        $availabilities = $stmt->fetchAll();
        
        // Fallback to default working hours (Mon-Fri 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, ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'])) {
                $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
        $stmtBooked = $db->prepare("
            SELECT time_from, time_to FROM interview_requests 
            WHERE maid_id = ? AND interview_date = ? AND status NOT IN ('cancelled', 'rejected')
        ");
        $stmtBooked->execute([$maidId, $dateStr]);
        $bookedInterviews = $stmtBooked->fetchAll();
        
        $now = time();
        $isToday = ($dateStr === date('Y-m-d'));
        
        $availableSlots = [];
        foreach ($allSlots as $slot) {
            if ($isToday) {
                $currentDubaiTime = date('H:i:s');
                if ($slot['from'] < $currentDubaiTime) {
                    continue;
                }
            }
            
            $overlaps = false;
            foreach ($bookedInterviews as $booked) {
                if ($slot['from'] < $booked['time_to'] && $slot['to'] > $booked['time_from']) {
                    $overlaps = true;
                    break;
                }
            }
            
            if (!$overlaps) {
                $availableSlots[] = $slot;
            }
        }
        
        sendResponse([
            'maid_id' => intval($maidId),
            'maid_name' => $maid['full_name'],
            'date' => $dateStr,
            'slots' => $availableSlots
        ], 'Available slots loaded');
    }

    public function getVendorInterviewSettings($vendorId) {
        $db = Database::getInstance();
        
        // Verify vendor exists
        $stmt = $db->prepare("SELECT id, agency_name FROM vendors WHERE id = ? LIMIT 1");
        $stmt->execute([$vendorId]);
        $vendor = $stmt->fetch();
        if (!$vendor) {
            sendError('Vendor not found', [], 404);
        }
        
        $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([
            'vendor_id' => intval($vendorId),
            'vendor_name' => $vendor['agency_name'],
            'timezone' => $settings['timezone'] ?? 'Asia/Dubai',
            'duration_minutes' => (int)($settings['duration_minutes'] ?? 45),
            'availability' => $availabilityList
        ], 'Vendor interview settings retrieved.');
    }

    public function reschedule($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['interview_date', 'time_from', 'time_to']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }

        $db = Database::getInstance();

        // 1. Fetch current interview details
        $stmt = $db->prepare("SELECT * FROM interview_requests WHERE id = ? AND customer_id = ? LIMIT 1");
        $stmt->execute([$id, $customerId]);
        $interview = $stmt->fetch();

        if (!$interview) {
            sendError('Interview request not found', [], 404);
        }

        if ($interview['status'] === 'cancelled' || $interview['status'] === 'completed' || $interview['status'] === 'rejected') {
            sendError('Cannot reschedule interview in its current state', [], 400);
        }

        // 2. 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)));
        $vendorId = $interview['vendor_id'];

        $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 {
            if (in_array($dayOfWeek, ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'])) {
                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);
        }

        // 3. 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 (?, 'customer', ?, ?, ?, ?, ?, ?, 'pending')
            ");
            $stmtResched->execute([
                $id,
                $interview['interview_date'],
                $interview['time_from'],
                $interview['time_to'],
                $dateStr,
                $timeFromStr,
                $timeToStr
            ]);

            // Update main interview request status to pending and update new times
            $stmtUpdate = $db->prepare("
                UPDATE interview_requests 
                SET status = 'pending', 
                    interview_date = ?, 
                    time_from = ?, 
                    time_to = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");
            $stmtUpdate->execute([
                $dateStr,
                $timeFromStr,
                $timeToStr,
                $id
            ]);

            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to reschedule interview request: ' . $e->getMessage(), [], 500);
        }

        sendResponse([], 'Interview rescheduled successfully. Awaiting vendor confirmation.');
    }
}


