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

class MaidController
{

    public function index()
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $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 maids WHERE vendor_id = ?");
        $totalStmt->execute([$vendorId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT m.*, 
                   n.name_en as nationality_name, n.name_ar as nationality_name_ar,
                   sm.name_en as service_model_name, sm.name_ar as service_model_name_ar,
                   at.name_en as accommodation_type_name, at.name_ar as accommodation_type_name_ar
            FROM maids m
            LEFT JOIN nationalities n ON m.nationality_id = n.id
            LEFT JOIN service_models sm ON m.service_model_id = sm.id
            LEFT JOIN accommodation_types at ON m.accommodation_type_id = at.id
            WHERE m.vendor_id = ? 
            ORDER BY m.created_at DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$vendorId]);
        $maids = $stmt->fetchAll();

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

        jsonResponse(true, 'Maids loaded successfully', ['maids' => $maids], $pagination);
    }

    public function store()
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

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

        // Support either full_name or first_name + last_name
        if (empty($data['full_name'])) {
            if (!empty($data['first_name'])) {
                $data['full_name'] = trim(($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? ''));
            }
        }

        $required = ['nationality_id'];
        if (empty($data['full_name'])) {
            $required[] = 'full_name';
        }
        $errors = validateRequired($data, $required);
        if (!empty($errors)) {
            sendError('Validation error', $errors, 422);
        }

        $maidModel = new Maid();
        $maidData = [
            'vendor_id' => $vendorId,
            'full_name' => htmlspecialchars($data['full_name'] ?? 'Unnamed'),
            'nationality_id' => (int) $data['nationality_id'],
            'date_of_birth' => $data['date_of_birth'] ?? null,
            'gender' => $data['gender'] ?? 'female',
            'monthly_salary' => (float) ($data['monthly_salary'] ?? 0),
            'years_experience' => (int) ($data['years_experience'] ?? $data['experience_years'] ?? 0),
            'availability_status' => $data['availability_status'] ?? 'available',
            'verification_status' => 'pending',
            'status' => 'draft'
        ];
        // Optional scalar fields
        $optionalStr = ['bio', 'marital_status', 'visa_status', 'custom_speciality', 'experience_location'];
        $optionalInt = ['accommodation_type_id', 'service_model_id'];
        foreach ($optionalStr as $f) {
            if (isset($data[$f]))
                $maidData[$f] = htmlspecialchars($data[$f]);
        }
        foreach ($optionalInt as $f) {
            if (isset($data[$f])) {
                $maidData[$f] = empty($data[$f]) ? null : (int) $data[$f];
            }
        }
        if (isset($data['available_from']))
            $maidData['available_from'] = $data['available_from'];

        // Handle profile image
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {

            $uploadDir = __DIR__ . '/../../../../public/uploads/maids/';
            if (!is_dir($uploadDir))
                mkdir($uploadDir, 0777, true);
            $ext = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('maid_') . '.' . $ext;
            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $uploadDir . $filename)) {
                $maidData['profile_image'] = '/public/uploads/maids/' . $filename;
            }
        }

        try {
            $maidId = $maidModel->insert($maidData);
            $maidData['id'] = $maidId;

            // Save languages if provided
            if (!empty($data['language_ids']) && is_array($data['language_ids'])) {
                $db = Database::getInstance();
                $db->prepare("DELETE FROM maid_languages WHERE maid_id = ?")->execute([$maidId]);
                $langStmt = $db->prepare("INSERT INTO maid_languages (maid_id, language_id, proficiency) VALUES (?, ?, ?)");
                foreach ($data['language_ids'] as $langEntry) {
                    if (is_array($langEntry)) {
                        $langStmt->execute([$maidId, (int) $langEntry['id'], $langEntry['proficiency'] ?? 'conversational']);
                    } else {
                        $langStmt->execute([$maidId, (int) $langEntry, 'conversational']);
                    }
                }
            }

            sendResponse(['maid' => $maidData], 'Maid draft created successfully.', 201);
        } catch (Exception $e) {
            sendError('Failed to add maid', ['error' => $e->getMessage()], 500);
        }
    }

    public function update($id)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $maidModel = new Maid();
        $maid = $maidModel->find($id);

        if (!$maid || $maid['vendor_id'] != $vendorId) {
            sendError('Maid not found', [], 404);
        }

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

        // Updateable fields
        $updateData = [];
        $stringFields = ['full_name', 'bio', 'gender', 'marital_status', 'visa_status', 'availability_status', 'status'];
        $intFields = ['nationality_id', 'years_experience', 'accommodation_type_id', 'service_model_id'];
        $floatFields = ['monthly_salary'];
        $rawFields = ['date_of_birth', 'emirates_id_verified', 'reliability_score'];

        foreach ($stringFields as $f) {
            if (isset($data[$f]))
                $updateData[$f] = htmlspecialchars($data[$f]);
        }
        if (isset($data['experience_years']))
            $updateData['years_experience'] = (int) $data['experience_years'];
        foreach ($intFields as $f) {
            if (isset($data[$f])) {
                if ($f === 'years_experience') {
                    $updateData[$f] = (int) $data[$f];
                } else {
                    $updateData[$f] = empty($data[$f]) ? null : (int) $data[$f];
                }
            }
        }
        foreach ($floatFields as $f) {
            if (isset($data[$f]))
                $updateData[$f] = (float) $data[$f];
        }
        foreach ($rawFields as $f) {
            if (isset($data[$f]))
                $updateData[$f] = $data[$f];
        }

        // Handle profile image upload in update
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../../../../public/uploads/maids/';
            if (!is_dir($uploadDir))
                mkdir($uploadDir, 0777, true);
            $ext = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid('maid_') . '.' . $ext;
            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $uploadDir . $filename)) {
                $updateData['profile_image'] = '/public/uploads/maids/' . $filename;
            }
        }

        if (empty($updateData)) {
            sendError('No data to update', [], 400);
        }

        try {
            $maidModel->update($id, $updateData);
            sendResponse([], 'Maid updated successfully');
        } catch (Exception $e) {
            sendError('Update failed', ['error' => $e->getMessage()], 500);
        }
    }

    public function show($id)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT m.*,
                   n.name_en as nationality_name, n.name_ar as nationality_name_ar,
                   sm.name_en as service_model_name, sm.name_ar as service_model_name_ar,
                   at.name_en as accommodation_type_name, at.name_ar as accommodation_type_name_ar,
                   c.name_en as country_name,
                   ci.name_en as city_name,
                   COALESCE(AVG(r.rating), 0) as rating,
                   COUNT(DISTINCT r.id) as reviews_count
            FROM maids m
            LEFT JOIN nationalities n ON m.nationality_id = n.id
            LEFT JOIN service_models sm ON m.service_model_id = sm.id
            LEFT JOIN accommodation_types at ON m.accommodation_type_id = at.id
            LEFT JOIN countries c ON m.country_id = c.id
            LEFT JOIN cities ci ON m.city_id = ci.id
            LEFT JOIN reviews r ON r.maid_id = m.id AND r.status = 'approved'
            WHERE m.id = ? AND m.vendor_id = ?
            GROUP BY m.id
        ");
        $stmt->execute([$id, $vendorId]);
        $maid = $stmt->fetch();

        if (!$maid) {
            sendError('Maid not found', [], 404);
        }

        // Gallery
        $galleryStmt = $db->prepare("SELECT id, image, sort_order FROM maid_gallery WHERE maid_id = ? ORDER BY sort_order ASC");
        $galleryStmt->execute([$id]);
        $maid['gallery'] = $galleryStmt->fetchAll();

        // Languages
        $langStmt = $db->prepare("
            SELECT l.id, l.name_en, l.name_ar 
            FROM maid_languages ml
            JOIN languages l ON ml.language_id = l.id
            WHERE ml.maid_id = ?
        ");
        $langStmt->execute([$id]);
        $maid['languages'] = $langStmt->fetchAll();

        // Skills
        $skillStmt = $db->prepare("
            SELECT s.id, s.name_en, s.name_ar 
            FROM maid_skills ms
            JOIN skills s ON ms.skill_id = s.id
            WHERE ms.maid_id = ?
        ");
        $skillStmt->execute([$id]);
        $maid['skills'] = $skillStmt->fetchAll();

        // Specialties
        $specStmt = $db->prepare("
            SELECT sp.id, sp.name_en, sp.name_ar 
            FROM maid_specialties msp
            JOIN specialties sp ON msp.specialty_id = sp.id
            WHERE msp.maid_id = ?
        ");
        $specStmt->execute([$id]);
        $maid['specialties'] = $specStmt->fetchAll();

        // Documents
        $docStmt = $db->prepare("
            SELECT md.id, md.file_path, md.expiry_date, md.status, md.admin_note,
                   dt.name_en as document_type_name
            FROM maid_documents md
            JOIN document_types dt ON md.document_type_id = dt.id
            WHERE md.maid_id = ?
            ORDER BY md.created_at DESC
        ");
        $docStmt->execute([$id]);
        $maid['documents'] = $docStmt->fetchAll();

        // Work Experience
        $expStmt = $db->prepare("
            SELECT * FROM maid_work_experience WHERE maid_id = ? ORDER BY is_current DESC, date_from DESC
        ");
        $expStmt->execute([$id]);
        $maid['work_experience'] = $expStmt->fetchAll();

        // Calculate age from date_of_birth
        $maid['age'] = null;
        if (!empty($maid['date_of_birth'])) {
            $dob = new DateTime($maid['date_of_birth']);
            $now = new DateTime();
            $maid['age'] = (int) $dob->diff($now)->y;
        }

        sendResponse(['maid' => $maid], 'Maid details loaded successfully');
    }

    public function updateStatus($id)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $maidModel = new Maid();
        $maid = $maidModel->find($id);
        if (!$maid || $maid['vendor_id'] != $vendorId) {
            sendError('Maid not found', [], 404);
        }

        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $newStatus = $data['status'] ?? null;

        $allowedStatuses = ['draft', 'published', 'hidden'];
        if (!$newStatus || !in_array($newStatus, $allowedStatuses)) {
            sendError('Invalid status. Allowed: draft, published, hidden', ['allowed' => $allowedStatuses], 422);
        }

        // Can only publish if not rejected/deactivated by admin
        $db = Database::getInstance();
        if ($newStatus === 'published') {
            if ($maid['verification_status'] === 'rejected') {
                sendError('This maid profile has been deactivated by the administrator and cannot be published.', [], 403);
            }

            // Automatically approve the maid when the vendor publishes it
            $db->prepare("UPDATE maids SET status = ?, verification_status = 'approved', updated_at = NOW() WHERE id = ?")
                ->execute([$newStatus, $id]);
        } else {
            $db->prepare("UPDATE maids SET status = ?, updated_at = NOW() WHERE id = ?")
                ->execute([$newStatus, $id]);
        }

        sendResponse(['status' => $newStatus], 'Maid listing status updated successfully.');
    }

    public function delete($id)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $maidModel = new Maid();
        $maid = $maidModel->find($id);
        if (!$maid || $maid['vendor_id'] != $vendorId) {
            sendError('Maid not found', [], 404);
        }

        try {
            $maidModel->delete($id);
            sendResponse([], 'Maid deleted successfully.');
        } catch (Exception $e) {
            sendError('Deletion failed', ['error' => $e->getMessage()], 500);
        }
    }

    public function uploadGallery($id)
    {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];

        $maidModel = new Maid();
        $maid = $maidModel->find($id);
        if (!$maid || $maid['vendor_id'] != $vendorId) {
            sendError('Maid not found', [], 404);
        }

        if (!isset($_FILES['images']) || empty($_FILES['images']['name'][0])) {
            sendError('No gallery images provided', [], 400);
        }

        $files = $_FILES['images'];
        $uploaded = [];
        $db = Database::getInstance();

        $uploadDir = __DIR__ . '/../../../../public/uploads/maids/gallery/';
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);

        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $ext = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
                $filename = uniqid('gall_' . $id . '_') . '.' . $ext;
                if (move_uploaded_file($files['tmp_name'][$i], $uploadDir . $filename)) {
                    $filePath = '/helperlink/public/uploads/maids/gallery/' . $filename;
                    $stmt = $db->prepare("INSERT INTO maid_gallery (maid_id, image, sort_order) VALUES (?, ?, ?)");
                    $stmt->execute([$id, $filePath, $i]);
                    $uploaded[] = $filePath;
                }
            }
        }

        sendResponse(['gallery' => $uploaded], 'Gallery images uploaded successfully.', 201);
    }

    public function deleteGalleryImage($imageId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT mg.* 
            FROM maid_gallery mg
            JOIN maids m ON mg.maid_id = m.id
            WHERE mg.id = ? AND m.vendor_id = ?
            LIMIT 1
        ");
        $stmt->execute([$imageId, $vendorId]);
        $image = $stmt->fetch();

        if (!$image) {
            sendError('Gallery image not found or access denied', [], 404);
        }

        $realPath = __DIR__ . '/../../../../..' . str_replace('/helperlink/public', '', $image['image']);
        if (file_exists($realPath))
            @unlink($realPath);

        $db->prepare("DELETE FROM maid_gallery WHERE id = ?")->execute([$imageId]);

        sendResponse([], 'Gallery image deleted successfully.');
    }

    public function uploadDocument($id)
    {
        $payload = VendorAuthMiddleware::authenticate();
        $vendorId = $payload['id'];

        $maidModel = new Maid();
        $maid = $maidModel->find($id);
        if (!$maid || $maid['vendor_id'] != $vendorId) {
            sendError('Maid not found', [], 404);
        }

        $documentTypeId = $_POST['document_type_id'] ?? null;
        $expiryDate = $_POST['expiry_date'] ?? null;

        if (!$documentTypeId || !isset($_FILES['document'])) {
            sendError('Document type and file are required', [], 422);
        }

        $file = $_FILES['document'];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            sendError('File upload failed', [], 400);
        }

        $uploadDir = __DIR__ . '/../../../../public/uploads/maids/documents/';
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);

        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = uniqid('doc_' . $id . '_') . '.' . $ext;

        if (move_uploaded_file($file['tmp_name'], $uploadDir . $filename)) {
            $filePath = '/helperlink/public/uploads/maids/documents/' . $filename;

            $db = Database::getInstance();
            $stmt = $db->prepare("
                INSERT INTO maid_documents (maid_id, document_type_id, file_path, expiry_date, status)
                VALUES (?, ?, ?, ?, 'pending')
            ");
            $stmt->execute([$id, $documentTypeId, $filePath, $expiryDate]);

            sendResponse(['file_path' => $filePath], 'Maid document uploaded successfully.', 201);
        } else {
            sendError('Failed to save file', [], 500);
        }
    }

    public function addExperience($maidId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $maidStmt = $db->prepare("SELECT id FROM maids WHERE id = ? AND vendor_id = ?");
        $maidStmt->execute([$maidId, $vendorId]);
        if (!$maidStmt->fetch()) {
            sendError('Maid not found', [], 404);
        }

        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $errors = validateRequired($data, ['job_title']);
        if (!empty($errors)) {
            sendError('Validation error', $errors, 422);
        }

        $stmt = $db->prepare("
            INSERT INTO maid_work_experience 
                (maid_id, job_title, employer, location, description, date_from, date_to, is_current, sort_order)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $maidId,
            htmlspecialchars($data['job_title']),
            htmlspecialchars($data['employer'] ?? ''),
            htmlspecialchars($data['location'] ?? ''),
            htmlspecialchars($data['description'] ?? ''),
            $data['date_from'] ?? null,
            $data['date_to'] ?? null,
            isset($data['is_current']) ? ($data['is_current'] ? 1 : 0) : 0,
            (int) ($data['sort_order'] ?? 0)
        ]);

        $newId = $db->lastInsertId();
        sendResponse(['id' => $newId], 'Work experience added successfully.', 201);
    }

    public function updateExperience($maidId, $expId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT we.id FROM maid_work_experience we
            JOIN maids m ON we.maid_id = m.id
            WHERE we.id = ? AND we.maid_id = ? AND m.vendor_id = ?
        ");
        $stmt->execute([$expId, $maidId, $vendorId]);
        if (!$stmt->fetch()) {
            sendError('Work experience not found', [], 404);
        }

        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $updates = [];
        $stringFields = ['job_title', 'employer', 'location', 'description'];
        foreach ($stringFields as $f) {
            if (isset($data[$f]))
                $updates[$f] = htmlspecialchars($data[$f]);
        }
        if (isset($data['date_from']))
            $updates['date_from'] = $data['date_from'];
        if (isset($data['date_to']))
            $updates['date_to'] = $data['date_to'];
        if (isset($data['is_current']))
            $updates['is_current'] = $data['is_current'] ? 1 : 0;
        if (isset($data['sort_order']))
            $updates['sort_order'] = (int) $data['sort_order'];

        if (empty($updates)) {
            sendError('No data to update', [], 400);
        }

        $setParts = array_map(fn($k) => "$k = ?", array_keys($updates));
        $values = array_values($updates);
        $values[] = $expId;

        $db->prepare("UPDATE maid_work_experience SET " . implode(', ', $setParts) . " WHERE id = ?")
            ->execute($values);

        sendResponse([], 'Work experience updated successfully.');
    }

    public function deleteExperience($maidId, $expId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT we.id FROM maid_work_experience we
            JOIN maids m ON we.maid_id = m.id
            WHERE we.id = ? AND we.maid_id = ? AND m.vendor_id = ?
        ");
        $stmt->execute([$expId, $maidId, $vendorId]);
        if (!$stmt->fetch()) {
            sendError('Work experience not found', [], 404);
        }

        $db->prepare("DELETE FROM maid_work_experience WHERE id = ?")->execute([$expId]);
        sendResponse([], 'Work experience deleted successfully.');
    }

    /**
     * POST /api/vendor/maids/{id}/languages
     * Sync languages — replaces all existing entries.
     * Body: { "languages": [{"id": 1, "proficiency": "fluent"}, ...] }
     *   OR: { "language_ids": [1, 2, 3] }
     */
    public function syncLanguages($maidId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $maidStmt = $db->prepare("SELECT id FROM maids WHERE id = ? AND vendor_id = ?");
        $maidStmt->execute([$maidId, $vendorId]);
        if (!$maidStmt->fetch()) {
            sendError('Maid not found', [], 404);
        }

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

        // Accept either 'languages' (with proficiency) or 'language_ids' (simple array)
        $languages = $data['languages'] ?? [];
        if (empty($languages) && !empty($data['language_ids'])) {
            foreach ($data['language_ids'] as $lid) {
                $languages[] = ['id' => $lid, 'proficiency' => 'conversational'];
            }
        }

        $db->prepare("DELETE FROM maid_languages WHERE maid_id = ?")->execute([$maidId]);

        $inserted = [];
        if (!empty($languages)) {
            $stmt = $db->prepare("INSERT INTO maid_languages (maid_id, language_id, proficiency) VALUES (?, ?, ?)");
            foreach ($languages as $lang) {
                $langId = is_array($lang) ? (int) ($lang['id'] ?? 0) : (int) $lang;
                $proficiency = is_array($lang) ? ($lang['proficiency'] ?? 'conversational') : 'conversational';
                if ($langId) {
                    $stmt->execute([$maidId, $langId, $proficiency]);
                    $inserted[] = ['language_id' => $langId, 'proficiency' => $proficiency];
                }
            }
        }

        sendResponse(['languages' => $inserted], 'Languages updated successfully.');
    }

    /**
     * POST /api/vendor/maids/{id}/specialties
     * Sync specialties — replaces all existing entries.
     * Body: { "specialty_ids": [1, 2, 3] }
     */
    public function syncSpecialties($maidId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $maidStmt = $db->prepare("SELECT id FROM maids WHERE id = ? AND vendor_id = ?");
        $maidStmt->execute([$maidId, $vendorId]);
        if (!$maidStmt->fetch()) {
            sendError('Maid not found', [], 404);
        }

        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $specialtyIds = $data['specialty_ids'] ?? [];

        $db->prepare("DELETE FROM maid_specialties WHERE maid_id = ?")->execute([$maidId]);

        $inserted = [];
        if (!empty($specialtyIds)) {
            $stmt = $db->prepare("INSERT INTO maid_specialties (maid_id, specialty_id) VALUES (?, ?)");
            foreach ($specialtyIds as $spId) {
                $spId = (int) $spId;
                if ($spId) {
                    $stmt->execute([$maidId, $spId]);
                    $inserted[] = $spId;
                }
            }
        }

        // Also save custom_speciality text if provided
        if (isset($data['custom_speciality'])) {
            $db->prepare("UPDATE maids SET custom_speciality = ? WHERE id = ?")
                ->execute([htmlspecialchars($data['custom_speciality']), $maidId]);
        }

        sendResponse(['specialty_ids' => $inserted], 'Specialties updated successfully.');
    }

    /**
     * POST /api/vendor/maids/{id}/skills
     * Sync skills — replaces all existing entries.
     * Body: { "skill_ids": [1, 2, 3] }
     */
    public function syncSkills($maidId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $maidStmt = $db->prepare("SELECT id FROM maids WHERE id = ? AND vendor_id = ?");
        $maidStmt->execute([$maidId, $vendorId]);
        if (!$maidStmt->fetch()) {
            sendError('Maid not found', [], 404);
        }

        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $skillIds = $data['skill_ids'] ?? [];

        $db->prepare("DELETE FROM maid_skills WHERE maid_id = ?")->execute([$maidId]);

        $inserted = [];
        if (!empty($skillIds)) {
            $stmt = $db->prepare("INSERT INTO maid_skills (maid_id, skill_id) VALUES (?, ?)");
            foreach ($skillIds as $sId) {
                $sId = (int) $sId;
                if ($sId) {
                    $stmt->execute([$maidId, $sId]);
                    $inserted[] = $sId;
                }
            }
        }

        sendResponse(['skill_ids' => $inserted], 'Skills updated successfully.');
    }

    /**
     * POST /api/vendor/maids/{id}/photo
     * Upload or replace the profile photo (multipart/form-data, field: profile_image)
     */
    public function uploadPhoto($maidId)
    {
        $payload = VendorAuthMiddleware::authenticate();
        VendorAuthMiddleware::enforceApproved($payload);
        $vendorId = $payload['id'];

        $db = Database::getInstance();
        $maidStmt = $db->prepare("SELECT id FROM maids WHERE id = ? AND vendor_id = ?");
        $maidStmt->execute([$maidId, $vendorId]);
        if (!$maidStmt->fetch()) {
            sendError('Maid not found', [], 404);
        }

        if (!isset($_FILES['profile_image']) || $_FILES['profile_image']['error'] !== UPLOAD_ERR_OK) {
            sendError('No profile image provided or upload error', [], 400);
        }

        $file = $_FILES['profile_image'];
        $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
        if (!in_array($file['type'], $allowedTypes)) {
            sendError('Invalid file type. Allowed: JPG, PNG, WEBP', [], 422);
        }
        if ($file['size'] > 5 * 1024 * 1024) {
            sendError('File size exceeds 5MB limit', [], 422);
        }

        $uploadDir = __DIR__ . '/../../../../public/uploads/maids/';
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);

        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $filename = 'maid_' . $maidId . '_' . uniqid() . '.' . $ext;

        if (move_uploaded_file($file['tmp_name'], $uploadDir . $filename)) {
            $filePath = '/public/uploads/maids/' . $filename;
            $db->prepare("UPDATE maids SET profile_image = ?, updated_at = NOW() WHERE id = ?")
                ->execute([$filePath, $maidId]);
            sendResponse(['profile_image' => $filePath], 'Profile photo uploaded successfully.');
        } else {
            sendError('Failed to save file', [], 500);
        }
    }
}
