<?php

require_once ROOT_PATH . '/app/models/Setting.php';
require_once ROOT_PATH . '/app/models/Service.php';
require_once ROOT_PATH . '/app/models/Product.php';
require_once ROOT_PATH . '/app/models/Project.php';
require_once ROOT_PATH . '/app/models/Testimonial.php';
require_once ROOT_PATH . '/app/models/Faq.php';
require_once ROOT_PATH . '/app/models/TeamMember.php';
require_once ROOT_PATH . '/app/models/Client.php';
require_once ROOT_PATH . '/app/models/Recognition.php';
require_once ROOT_PATH . '/app/models/Industry.php';
require_once ROOT_PATH . '/app/models/Plan.php';
require_once ROOT_PATH . '/app/models/Career.php';
require_once ROOT_PATH . '/app/models/Page.php';
require_once ROOT_PATH . '/app/models/TechStack.php';
require_once ROOT_PATH . '/app/models/Differentiator.php';
require_once ROOT_PATH . '/app/models/MethodologyStep.php';
class ApiController
{
    private $db;

    public function __construct($db)
    {
        $this->db = $db;
    }
    private function decodeJsonField($field)
    {
        if (!empty($field) && is_string($field)) {
            // El segundo parámetro 'true' convierte el JSON en un array asociativo de PHP
            return json_decode($field, true);
        }
        // Si el campo es nulo, vacío o no es un string, devuelve un array vacío
        return [];
    }
    public function getAllData()
    {
        $data = [];

        // Fetch site_metadata
        $setting = new Setting($this->db);
        $setting->read();
        $data['siteMetadata'] = [
            'companyName' => $setting->company_name,
            'siteTitle' => $setting->site_title,
            'siteTitleTemplate' => $setting->site_title_template,
            'siteDescription' => $setting->site_description,
            'siteUrl' => $setting->site_url,
            'siteLogo' => $setting->site_logo,
            'siteLogoRQ' => $setting->site_logo_rq,
            'siteLogoSquare' => $setting->site_logo_square,
            'email' => $setting->email,
            'phone' => $setting->phone,
            'whatsappNumber' => $setting->whatsapp_number,
            'address' => $setting->address,
            'social' => $setting->social,
            'location' => $setting->location,
            'keywords' => $setting->keywords,
            'hiringContact' => [
                'name' => $setting->hiring_contact_name,
                'email' => $setting->hiring_contact_email,
                'whatsappMessage' => $setting->hiring_contact_whatsapp_message,
            ],
        ];

        // Fetch navigation (assuming it's static or managed differently)
        // For now, hardcode as it's not in DB schema
        $data['navigation'] = [
            ['name' => 'Inicio', 'href' => '/'],
            ['name' => 'Nosotros', 'href' => '/nosotros'],
            ['name' => 'Servicios', 'href' => '/servicios'],
            ['name' => 'Proyectos', 'href' => '/proyectos'],
            ['name' => 'Brochure', 'href' => '/brochure'],
            ['name' => 'Contacto', 'href' => '/contacto'],
        ];

        // Fetch pages
        $pageModel = new Page($this->db);
        $stmtPages = $pageModel->readAll();
        $pages = [];
        while ($row = $stmtPages->fetch(PDO::FETCH_ASSOC)) {
            $pages[$row['page_key']] = [
                'seo' => [
                    'title' => $row['seo_title'],
                    'description' => $row['seo_description'] ?? null,
                ],
                'hero' => [
                    'headline' => $row['hero_headline'] ?? null,
                    'subheadline' => $row['hero_subheadline'] ?? null,
                    'cta' => [
                        'primary' => ['text' => $row['hero_cta_primary_text'] ?? null, 'href' => $row['hero_cta_primary_href'] ?? null],
                        'secondary' => ['text' => $row['hero_cta_secondary_text'] ?? null, 'href' => $row['hero_cta_secondary_href'] ?? null],
                    ],
                ],
                'stats' => $this->decodeJsonField($row['stats'] ?? null),
                'mission' => $row['mission'] ?? null,
                'vision' => $row['vision'] ?? null,
                'timeline' => $this->decodeJsonField($row['timeline'] ?? null),
                'team' => $this->decodeJsonField($row['team'] ?? null),
            ];
        }
        $data['pages'] = $pages;

        // Fetch services
        $serviceModel = new Service($this->db);
        $stmtServices = $serviceModel->readAll();
        $services = [];
        while ($row = $stmtServices->fetch(PDO::FETCH_ASSOC)) {
            $services[] = [
                'id' => $row['id'],
                'seo' => [
                    'title' => $row['seo_title'],
                    'description' => $row['seo_description'],
                ],
                'title' => $row['title'],
                'icon' => $row['icon'],
                'image' => $row['image'],
                'video' => $row['video'],
                'shortDescription' => $row['short_description'],
                'detailedDescription' => $row['detailed_description'],
                'keyOfferings' => $this->decodeJsonField($row['key_offerings']),
                'cta' => [
                    'text' => $row['cta_text'],
                    'whatsappMessage' => $row['cta_whatsapp_message'],
                ],
            ];
        }
        $data['services'] = $services;

        // Fetch products
        $productModel = new Product($this->db);
        $stmtProducts = $productModel->readAll();
        $products = [];
        while ($row = $stmtProducts->fetch(PDO::FETCH_ASSOC)) {
            $products[] = [
                'id' => $row['id'],
                'title' => $row['title'],
                'price' => $row['price'],
                'shortDescription' => $row['short_description'],
                'idealFor' => $row['ideal_for'],
                'includedModules' => $this->decodeJsonField($row['included_modules']),
                'cta' => [
                    'text' => $row['cta_text'],
                    'whatsappMessage' => $row['cta_whatsapp_message'],
                ],
            ];
        }
        $data['products'] = $products;

        // Fetch projects
        $projectModel = new Project($this->db);
        $stmtProjects = $projectModel->readAll();
        $projects = [];
        while ($row = $stmtProjects->fetch(PDO::FETCH_ASSOC)) {
            $projects[] = [
                'id' => $row['id'],
                'title' => $row['title'],
                'client' => $row['client'],
                'category' => $row['category'],
                'serviceId' => $row['service_id'],
                'coverImage' => $row['cover_image'],
                'shortDescription' => $row['short_description'],
                'challenge' => $row['challenge'],
                'solution' => $row['solution'],
                'outcome' => $row['outcome'],
                'technologies' => $this->decodeJsonField($row['technologies']),
                'gallery' => $this->decodeJsonField($row['gallery']),
                'cta' => [
                    'text' => $row['cta_text'],
                    'whatsappMessage' => $row['cta_whatsapp_message'],
                ],
            ];
        }
        $data['projects'] = $projects;

        // Fetch testimonials
        $testimonialModel = new Testimonial($this->db);
        $stmtTestimonials = $testimonialModel->readAll();
        $testimonials = [];
        while ($row = $stmtTestimonials->fetch(PDO::FETCH_ASSOC)) {
            $testimonials[] = [
                'name' => $row['name'],
                'role' => $row['role'],
                'company' => $row['company'],
                'avatar' => $row['avatar'],
                'quote' => $row['quote'],
                'relatedProjectId' => $row['related_project_id'],
            ];
        }
        $data['testimonials'] = $testimonials;

        // Fetch faqs
        $faqModel = new Faq($this->db);
        $stmtFaqs = $faqModel->readAll();
        $faqs = [];
        while ($row = $stmtFaqs->fetch(PDO::FETCH_ASSOC)) {
            $faqs[] = [
                'q' => $row['question'],
                'a' => $row['answer'],
            ];
        }
        $data['optionalData']['faq'] = $faqs;

        // Fetch team_members
        $teamMemberModel = new TeamMember($this->db);
        $stmtTeamMembers = $teamMemberModel->readAll();
        $teamMembers = [];
        while ($row = $stmtTeamMembers->fetch(PDO::FETCH_ASSOC)) {
            $teamMembers[] = [
                'name' => $row['name'],
                'role' => $row['role'],
                'avatar' => $row['avatar'],
                'bio' => $row['bio'],
                'social' => $this->decodeJsonField($row['social']),
            ];
        }
        $data['pages']['about']['team'] = $teamMembers; // Assuming team is part of pages.about

        // Fetch tech_stack
        $techStackModel = new TechStack($this->db);
        $stmtTechStack = $techStackModel->readAll();
        $techStack = [];
        while ($row = $stmtTechStack->fetch(PDO::FETCH_ASSOC)) {
            $techStack[] = [
                'name' => $row['name'],
                'logo' => $row['logo'],
                'type' => $row['type'],
            ];
        }
        $data['optionalData']['techStack'] = $techStack;

        // Fetch clients
        $clientModel = new Client($this->db);
        $stmtClients = $clientModel->readAll();
        $clients = [];
        while ($row = $stmtClients->fetch(PDO::FETCH_ASSOC)) {
            $clients[] = [
                'name' => $row['name'],
                'logo' => $row['logo'],
            ];
        }
        $data['clients'] = $clients;

        // Fetch recognitions
        $recognitionModel = new Recognition($this->db);
        $stmtRecognitions = $recognitionModel->readAll();
        $recognitions = [];
        while ($row = $stmtRecognitions->fetch(PDO::FETCH_ASSOC)) {
            $recognitions[] = [
                'title' => $row['title'],
                'issuer' => $row['issuer'],
                'icon' => $row['icon'],
            ];
        }
        $data['optionalData']['recognitions'] = $recognitions;

        // Fetch industries
        $industryModel = new Industry($this->db);
        $stmtIndustries = $industryModel->readAll();
        $industries = [];
        while ($row = $stmtIndustries->fetch(PDO::FETCH_ASSOC)) {
            $industries[] = [
                'name' => $row['name'],
            ];
        }
        $data['optionalData']['industries'] = $industries;

        // Fetch plans
        $planModel = new Plan($this->db);
        $stmtPlans = $planModel->readAll();
        $plans = [];
        while ($row = $stmtPlans->fetch(PDO::FETCH_ASSOC)) {
            $plans[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'priceMonthly' => $row['price_monthly'],
                'priceAnnual' => $row['price_annual'],
                'features' => $this->decodeJsonField($row['features']),
                'badge' => $row['badge'],
                'highlight' => (bool)$row['highlight'],
            ];
        }
        $data['optionalData']['plans'] = $plans;

        // Fetch careers
        $careerModel = new Career($this->db);
        $stmtCareers = $careerModel->readAll();
        $careers = [];
        while ($row = $stmtCareers->fetch(PDO::FETCH_ASSOC)) {
            $careers[] = [
                'id' => $row['id'],
                'title' => $row['title'],
                'location' => $row['location'],
                'type' => $row['type'],
                'postedAt' => $row['posted_at'],
                'summary' => $row['summary'],
                'responsibilities' => $this->decodeJsonField($row['responsibilities']),
                'requirements' => $this->decodeJsonField($row['requirements']),
                'benefits' => $this->decodeJsonField($row['benefits']),
                'process' => $this->decodeJsonField($row['process']),
                'applyCta' => [
                    'text' => $row['apply_cta_text'],
                    'whatsappMessage' => $row['apply_cta_whatsapp_message'],
                ],
            ];
        }
        $data['careers'] = $careers;

        // Fetch contact_availability_defaults
        $contactAvailabilityDefaults = [];
        $stmtDefaults = $this->db->query("SELECT * FROM contact_availability_defaults");
        while ($row = $stmtDefaults->fetch(PDO::FETCH_ASSOC)) {
            $contactAvailabilityDefaults[$row['time']] = (bool)$row['is_available'];
        }
        $data['contactAvailability']['default'] = $contactAvailabilityDefaults;

        // Fetch contact_availability_by_date
        $contactAvailabilityByDate = [];
        $stmtByDate = $this->db->query("SELECT * FROM contact_availability_by_date");
        while ($row = $stmtByDate->fetch(PDO::FETCH_ASSOC)) {
            if (!isset($contactAvailabilityByDate[$row['date']])) {
                $contactAvailabilityByDate[$row['date']] = [];
            }
            $contactAvailabilityByDate[$row['date']][$row['time']] = (bool)$row['is_available'];
        }
        $data['contactAvailability']['byDate'] = $contactAvailabilityByDate;

        // Fetch contact_availability_by_service
        $contactAvailabilityByService = [];
        $stmtByService = $this->db->query("SELECT * FROM contact_availability_by_service");
        while ($row = $stmtByService->fetch(PDO::FETCH_ASSOC)) {
            if (!isset($contactAvailabilityByService[$row['service_id']])) {
                $contactAvailabilityByService[$row['service_id']] = [];
            }
            if (!isset($contactAvailabilityByService[$row['service_id']][$row['date']])) {
                $contactAvailabilityByService[$row['service_id']][$row['date']] = [];
            }
            $contactAvailabilityByService[$row['service_id']][$row['date']][$row['time']] = (bool)$row['is_available'];
        }
        $data['contactAvailability']['byService'] = $contactAvailabilityByService;

        header('Content-Type: application/json');
        echo json_encode($data);
    }

    public function getBrochureData(): void
    {
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');

        try {
            $data = [];

            // --- 1. Metadatos del Sitio ---
            $setting = new Setting($this->db);
            $setting->read();
            $data['siteMetadata'] = [
                'companyName' => $setting->company_name ?? null,
                'siteTitle' => $setting->site_title ?? null,
                'siteUrl' => $setting->site_url ?? null,
                'siteLogoRQ' => $setting->site_logo_rq ?? null,
                'email' => $setting->email ?? null,
                'phone' => $setting->phone ?? null,
                'whatsappNumber' => $setting->whatsapp_number ?? null,
                'address' => $setting->address ?? null,
            ];
  $data['navigation'] = [
            ['name' => 'Inicio', 'href' => '/'],
            ['name' => 'Nosotros', 'href' => '/nosotros'],
            ['name' => 'Servicios', 'href' => '/servicios'],
            ['name' => 'Proyectos', 'href' => '/proyectos'],
            ['name' => 'Brochure', 'href' => '/brochure'],
            ['name' => 'Contacto', 'href' => '/contacto'],
        ];
            // --- 2. Contenido de la Página "Nosotros" ---
            $pageModel = new Page($this->db);
            $pageModel->page_key = 'nosotros';
            if ($pageModel->readOne()) {
                $data['pages']['nosotros'] = [
                    'mission' => $pageModel->mission ?? null,
                    'vision' => $pageModel->vision ?? null,
                ];
            }

            // --- 3. Miembros del Equipo ---
            $teamMemberModel = new TeamMember($this->db);
            $teamMembersData = $teamMemberModel->readAll()->fetchAll(PDO::FETCH_ASSOC);
            foreach ($teamMembersData as &$member) {
                $member['social'] = json_decode($member['social'] ?? '{}', true);
            }
            $data['pages']['about']['team'] = $teamMembersData;

            // --- 4. Servicios ---
            $serviceModel = new Service($this->db);
            $servicesData = $serviceModel->readAll()->fetchAll(PDO::FETCH_ASSOC);
            foreach ($servicesData as &$service) {
                $service['keyOfferings'] = json_decode($service['key_offerings'] ?? '[]', true);
                $service['shortDescription'] = $service['short_description'] ?? null;
                unset($service['key_offerings'], $service['short_description']);
            }
            $data['services'] = $servicesData;

            // --- 5. Proyectos Destacados ---
            $projectModel = new Project($this->db);
            $stmtProjects = $this->db->query("SELECT * FROM projects ORDER BY id DESC LIMIT 2");
            $projectsData = $stmtProjects->fetchAll(PDO::FETCH_ASSOC);
            foreach ($projectsData as &$project) {
                $project['technologies'] = json_decode($project['technologies'] ?? '[]', true);
                $project['gallery'] = json_decode($project['gallery'] ?? '[]', true);
            }
            $data['projects'] = $projectsData;

            // --- 6. Datos Opcionales (FAQs, Planes, Diferenciadores, etc.) ---
            
            // FAQs
            $faqModel = new Faq($this->db);
            $faqsData = $faqModel->readAll()->fetchAll(PDO::FETCH_ASSOC);
            $formattedFaqs = [];
            foreach ($faqsData as $faq) {
                $formattedFaqs[] = ['q' => $faq['question'], 'a' => $faq['answer']];
            }
            $data['optionalData']['faq'] = $formattedFaqs;

            // Planes (CORREGIDO Y MEJORADO)
            $planModel = new Plan($this->db);
            $plansData = $planModel->readAll()->fetchAll(PDO::FETCH_ASSOC);
            foreach ($plansData as &$plan) {
                // CORRECCIÓN: Asegura que 'features' sea siempre un array
                $features_decoded = json_decode($plan['features'] ?? '[]', true);
                $plan['features'] = is_array($features_decoded) ? $features_decoded : [];

                // CORRECCIÓN: Renombra y convierte los precios a números
                $plan['priceMonthly'] = isset($plan['price_monthly']) ? (float)$plan['price_monthly'] : null;
                $plan['priceAnnual'] = isset($plan['price_annual']) ? (float)$plan['price_annual'] : null;
                
                $plan['highlight'] = (bool)($plan['highlight'] ?? false);

                // Limpia las claves antiguas
                unset($plan['price_monthly'], $plan['price_annual']);
            }
            $data['optionalData']['plans'] = $plansData;

            // Diferenciadores (AÑADIDO)
            $differentiatorModel = new Differentiator($this->db);
            $differentiatorsData = $differentiatorModel->readAll()->fetchAll(PDO::FETCH_ASSOC);
            $formattedDifferentiators = [];
            foreach ($differentiatorsData as $d) {
                $formattedDifferentiators[] = [
                    'title' => $d['title'],
                    'desc' => $d['description'], // El frontend espera 'desc'
                    'icon' => $d['icon']
                ];
            }
            $data['optionalData']['differentiators'] = $formattedDifferentiators;
            
            // Pasos Metodológicos (AÑADIDO)
            $methodologyStepModel = new MethodologyStep($this->db);
            $data['optionalData']['methodologySteps'] = $methodologyStepModel->readAll()->fetchAll(PDO::FETCH_ASSOC);


            // --- IMPRESIÓN FINAL ---
            echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Error al generar datos del brochure: ' . $e->getMessage()]);
        }
    }
}
