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

class HomeController {
    
    public function index() {
        $db = Database::getInstance();
        
        // Parse Authorization token if present (optional auth for favorites status check)
        $authHeader = '';
        if (function_exists('getallheaders')) {
            $headers = getallheaders();
            $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        }
        if (empty($authHeader)) {
            $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
        }
        
        $customerId = null;
        if (!empty($authHeader) && preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            $payload = verifyJWT($matches[1]);
            if ($payload && $payload['type'] === 'customer') {
                $customerId = $payload['id'];
            }
        }
        
        // 1. Hero Sliders
        $sliders = $db->query("
            SELECT id, title_en, title_ar, badge_en, badge_ar, subtitle_en, subtitle_ar, 
                   button_text_en, button_text_ar, image, target_type, target_id, target_url 
            FROM app_sliders 
            WHERE status = 'active' 
            ORDER BY sort_order ASC, id DESC
        ")->fetchAll();
        
        // 2. Featured Vendors (agencies)
        $vendorsStmt = $db->prepare("
            SELECT v.id, v.agency_name, v.logo, v.description, v.cover_image, v.is_verified, v.is_featured,
                   COALESCE(AVG(r.rating), 5.0) as rating,
                   COUNT(r.id) as reviews_count,
                   (
                       SELECT MIN(m.monthly_salary) 
                       FROM maids m 
                       WHERE m.vendor_id = v.id AND m.status = 'published' AND m.availability_status = 'available'
                   ) as starting_price,
                   (
                       SELECT GROUP_CONCAT(DISTINCT s.name_en ORDER BY s.name_en ASC SEPARATOR ', ')
                       FROM maid_specialties ms
                       JOIN specialties s ON ms.specialty_id = s.id
                       JOIN maids m ON ms.maid_id = m.id
                       WHERE m.vendor_id = v.id AND m.status = 'published'
                   ) as specialties_concat,
                   (
                       SELECT GROUP_CONCAT(DISTINCT COALESCE(s.name_ar, s.name_en) ORDER BY s.name_en ASC SEPARATOR ', ')
                       FROM maid_specialties ms
                       JOIN specialties s ON ms.specialty_id = s.id
                       JOIN maids m ON ms.maid_id = m.id
                       WHERE m.vendor_id = v.id AND m.status = 'published'
                   ) as specialties_concat_ar,
                   (CASE WHEN ? IS NOT NULL AND EXISTS(
                       SELECT 1 FROM favorite_vendors fv 
                       WHERE fv.vendor_id = v.id AND fv.customer_id = ?
                   ) THEN 1 ELSE 0 END) as is_favorited
            FROM vendors v
            LEFT JOIN reviews r ON r.vendor_id = v.id
            WHERE v.status = 'approved' AND v.is_featured = 1
            GROUP BY v.id
            ORDER BY rating DESC, reviews_count DESC
            LIMIT 5
        ");
        $vendorsStmt->execute([$customerId, $customerId]);
        $vendorsData = $vendorsStmt->fetchAll();

        // Process vendor specialty tags
        foreach ($vendorsData as &$vendor) {
            $tags = [];
            $tags_ar = [];
            if (!empty($vendor['specialties_concat'])) {
                $tags = array_slice(array_map('trim', explode(',', $vendor['specialties_concat'])), 0, 2);
            }
            if (!empty($vendor['specialties_concat_ar'])) {
                $tags_ar = array_slice(array_map('trim', explode(',', $vendor['specialties_concat_ar'])), 0, 2);
            }
            $vendor['tags'] = $tags;
            $vendor['tags_ar'] = $tags_ar;
            $vendor['is_featured'] = intval($vendor['is_featured']) === 1;
            $vendor['starting_price'] = $vendor['starting_price'] !== null ? floatval($vendor['starting_price']) : 0;
            unset($vendor['specialties_concat']);
            unset($vendor['specialties_concat_ar']);
        }
        
        // Base Maid Query
        $maidQuery = "
            SELECT m.id, m.full_name, m.profile_image, m.years_experience, m.monthly_salary, m.bio, m.reliability_score, m.is_recommended,
                   v.agency_name, v.id as vendor_id,
                   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,
                   COALESCE(AVG(r.rating), 5.0) as rating, 
                   COUNT(r.id) as reviews_count,
                   (
                       SELECT GROUP_CONCAT(l.name_en SEPARATOR ', ')
                       FROM maid_languages ml
                       JOIN languages l ON ml.language_id = l.id
                       WHERE ml.maid_id = m.id
                   ) as languages_concat,
                   (
                       SELECT GROUP_CONCAT(COALESCE(l.name_ar, l.name_en) SEPARATOR ', ')
                       FROM maid_languages ml
                       JOIN languages l ON ml.language_id = l.id
                       WHERE ml.maid_id = m.id
                   ) as languages_concat_ar,
                   (
                       SELECT GROUP_CONCAT(s.name_en SEPARATOR ', ')
                       FROM maid_specialties ms
                       JOIN specialties s ON ms.specialty_id = s.id
                       WHERE ms.maid_id = m.id
                   ) as specialties_concat,
                   (
                       SELECT GROUP_CONCAT(COALESCE(s.name_ar, s.name_en) SEPARATOR ', ')
                       FROM maid_specialties ms
                       JOIN specialties s ON ms.specialty_id = s.id
                       WHERE ms.maid_id = m.id
                   ) as specialties_concat_ar,
                   (CASE WHEN ? IS NOT NULL AND EXISTS(
                       SELECT 1 FROM favorite_maids fm 
                       WHERE fm.maid_id = m.id AND fm.customer_id = ?
                   ) THEN 1 ELSE 0 END) as is_favorited
            FROM maids m
            JOIN vendors v ON m.vendor_id = v.id
            LEFT JOIN nationalities n ON m.nationality_id = n.id
            LEFT JOIN service_models sm ON m.service_model_id = sm.id
            LEFT JOIN reviews r ON r.maid_id = m.id
        ";
        
        // 3. Recommended Maids
        $recommendedStmt = $db->prepare($maidQuery . " WHERE m.status = 'published' AND m.availability_status = 'available' AND v.status = 'approved' AND m.is_recommended = 1 GROUP BY m.id ORDER BY rating DESC, m.monthly_salary ASC LIMIT 6");
        $recommendedStmt->execute([$customerId, $customerId]);
        $recommendedMaids = $recommendedStmt->fetchAll();
        
        // 4. Recently Added Maids
        $recentlyAddedStmt = $db->prepare($maidQuery . " WHERE m.status = 'published' AND m.availability_status = 'available' AND v.status = 'approved' GROUP BY m.id ORDER BY m.created_at DESC LIMIT 6");
        $recentlyAddedStmt->execute([$customerId, $customerId]);
        $recentlyAddedMaids = $recentlyAddedStmt->fetchAll();
        
        // Helper to format maids lists
        $formatMaids = function(&$maidsList) {
            foreach ($maidsList as &$maid) {
                $maid['languages'] = !empty($maid['languages_concat']) 
                    ? array_map('trim', explode(',', $maid['languages_concat'])) 
                    : [];
                $maid['languages_ar'] = !empty($maid['languages_concat_ar']) 
                    ? array_map('trim', explode(',', $maid['languages_concat_ar'])) 
                    : [];
                $maid['specialties'] = !empty($maid['specialties_concat']) 
                    ? array_map('trim', explode(',', $maid['specialties_concat'])) 
                    : [];
                $maid['specialties_ar'] = !empty($maid['specialties_concat_ar']) 
                    ? array_map('trim', explode(',', $maid['specialties_concat_ar'])) 
                    : [];
                $maid['monthly_salary'] = floatval($maid['monthly_salary']);
                $maid['is_favorited'] = intval($maid['is_favorited']) === 1;
                $maid['is_recommended'] = intval($maid['is_recommended']) === 1;
                unset($maid['languages_concat']);
                unset($maid['languages_concat_ar']);
                unset($maid['specialties_concat']);
                unset($maid['specialties_concat_ar']);
            }
        };

        $formatMaids($recommendedMaids);
        $formatMaids($recentlyAddedMaids);

        // 5. Popular Specialties
        $specialties = $db->query("
            SELECT id, name_en, name_ar, icon 
            FROM specialties 
            WHERE status = 'active' 
            ORDER BY name_en ASC
        ")->fetchAll();

        // 6. Service Models
        $serviceModels = $db->query("
            SELECT id, name_en, name_ar 
            FROM service_models 
            WHERE status = 'active'
        ")->fetchAll();

        // 8. Snippets (Stories / Celebrate Heroes)
        $snippets = $db->query("
            SELECT id, title_en, title_ar, image 
            FROM app_snippets 
            WHERE status = 'active' 
            ORDER BY sort_order ASC, id DESC
        ")->fetchAll();

        sendResponse([
            'sliders' => $sliders,
            'featured_vendors' => $vendorsData,
            'recommended_maids' => $recommendedMaids,
            'recently_added_maids' => $recentlyAddedMaids,
            'specialties' => $specialties,
            'service_models' => $serviceModels,
            'snippets' => $snippets
        ], 'Marketplace home data loaded successfully');
    }
}
