<?php

require_once ROOT_PATH . '/app/models/Service.php';

class ServiceController
{
    private $db;
    private $service;

    public function __construct($db)
    {
        $this->db = $db;
        $this->service = new Service($this->db);
    }

    private function renderAdminLayout($content, $pageTitle)
    {
        ob_start();
        echo $content;
        $content = ob_get_clean();
        require_once ROOT_PATH . '/app/views/admin/layout.php';
    }

    // --- FUNCIÓN REUTILIZADA PARA MANEJAR SUBIDA DE IMÁGENES ---
    private function handleImageUpload(string $fileInputName, ?string $oldImagePath = null): array
    {
        if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] === UPLOAD_ERR_NO_FILE) {
            return ['success' => true, 'path' => null, 'error' => null];
        }

        $file = $_FILES[$fileInputName];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'path' => null, 'error' => 'Error al subir el archivo.'];
        }

        $uploadDir = ROOT_PATH . '/public/images/services/';
        if (!is_dir($uploadDir)) {
            if (!mkdir($uploadDir, 0775, true)) {
                return ['success' => false, 'path' => null, 'error' => 'Error: No se pudo crear el directorio de subida.'];
            }
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);
        $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (!in_array($mimeType, $allowedMimeTypes)) {
            return ['success' => false, 'path' => null, 'error' => 'Formato de archivo no permitido.'];
        }

        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $newFileName = uniqid('service_', true) . '.' . $fileExtension;
        $destPath = $uploadDir . $newFileName;

        if (!move_uploaded_file($file['tmp_name'], $destPath)) {
            return ['success' => false, 'path' => null, 'error' => 'No se pudo mover el archivo subido.'];
        }

        if ($oldImagePath && file_exists(ROOT_PATH . '/public' . $oldImagePath)) {
            @unlink(ROOT_PATH . '/public' . $oldImagePath);
        }

        return ['success' => true, 'path' => '/images/services/' . $newFileName, 'error' => null];
    }

    public function index()
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        $stmt = $this->service->readAll();
        $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/services/index.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Gestionar Servicios");
    }

    public function create()
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }
        $error = null;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $uploadResult = $this->handleImageUpload('image');

            if ($uploadResult['success']) {
                $this->service->id = $_POST['id'] ?? '';
                $this->service->seo_title = $_POST['seo_title'] ?? '';
                $this->service->seo_description = $_POST['seo_description'] ?? '';
                $this->service->title = $_POST['title'] ?? '';
                $this->service->icon = $_POST['icon'] ?? '';
                $this->service->video = $_POST['video'] ?? null;
                $this->service->short_description = $_POST['short_description'] ?? '';
                $this->service->detailed_description = $_POST['detailed_description'] ?? '';
                $this->service->cta_text = $_POST['cta_text'] ?? '';
                $this->service->cta_whatsapp_message = $_POST['cta_whatsapp_message'] ?? '';

                $this->service->image = $uploadResult['path'];

                $key_offerings_string = $_POST['key_offerings'] ?? '';
                $key_offerings_array = array_filter(array_map('trim', explode("\n", $key_offerings_string)));
                $this->service->key_offerings = json_encode(array_values($key_offerings_array));

                if ($this->service->create()) {
                    $_SESSION['message'] = "¡Servicio creado exitosamente!";
                    redirect('admin/services');
                } else {
                    $error = "Falló al crear el servicio. Verifica que el ID no esté repetido.";
                    if ($uploadResult['path'] && file_exists(ROOT_PATH . '/public' . $uploadResult['path'])) {
                        @unlink(ROOT_PATH . '/public' . $uploadResult['path']);
                    }
                }
            } else {
                $error = $uploadResult['error'];
            }
        }

        ob_start();
        // Usamos una única vista para crear y editar
        require_once ROOT_PATH . '/app/views/admin/services/form.php'; 
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Crear Nuevo Servicio");
    }

    public function edit()
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }
        $error = null;

        $id = $_POST['id'] ?? $_GET['id'] ?? null;
        if (!$id) {
            $_SESSION['error'] = "No se especificó un ID de servicio.";
            redirect('admin/services');
        }
        $this->service->id = $id;

        if (!$this->service->readOne()) {
            $_SESSION['error'] = "Servicio no encontrado.";
            redirect('admin/services');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->service->seo_title = $_POST['seo_title'] ?? '';
            $this->service->seo_description = $_POST['seo_description'] ?? '';
            $this->service->title = $_POST['title'] ?? '';
            $this->service->icon = $_POST['icon'] ?? '';
            $this->service->video = $_POST['video'] ?? null;
            $this->service->short_description = $_POST['short_description'] ?? '';
            $this->service->detailed_description = $_POST['detailed_description'] ?? '';
            $this->service->cta_text = $_POST['cta_text'] ?? '';
            $this->service->cta_whatsapp_message = $_POST['cta_whatsapp_message'] ?? '';

            $key_offerings_string = $_POST['key_offerings'] ?? '';
            $key_offerings_array = array_filter(array_map('trim', explode("\n", $key_offerings_string)));
            $this->service->key_offerings = json_encode(array_values($key_offerings_array));
            
            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $oldImage = $_POST['current_image'] ?? $this->service->image;
                $uploadResult = $this->handleImageUpload('image', $oldImage);
                if ($uploadResult['success']) {
                    $this->service->image = $uploadResult['path'];
                } else {
                    $error = $uploadResult['error'];
                }
            }
            
            if ($error === null) {
                if ($this->service->update()) {
                    $_SESSION['message'] = "¡Servicio actualizado exitosamente!";
                    redirect('admin/services');
                } else {
                    $error = "Falló al actualizar el servicio.";
                }
            }
        }
        
        if (!is_array($this->service->key_offerings)) {
            $this->service->key_offerings = json_decode($this->service->key_offerings, true) ?? [];
        }

        ob_start();
        // Usamos la misma vista, que ahora se llama form.php
        require_once ROOT_PATH . '/app/views/admin/services/edit.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Editar Servicio");
    }

    public function delete()
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->service->id = $_POST['id'] ?? '';

            if ($this->service->readOne()) {
                $imageToDelete = $this->service->image;

                if ($this->service->delete()) {
                    if ($imageToDelete && file_exists(ROOT_PATH . '/public' . $imageToDelete)) {
                        @unlink(ROOT_PATH . '/public' . $imageToDelete);
                    }
                    $_SESSION['message'] = "¡Servicio eliminado exitosamente!";
                } else {
                    $_SESSION['error'] = "Falló al eliminar el servicio.";
                }
            } else {
                $_SESSION['error'] = "No se encontró el servicio a eliminar.";
            }
        }
        redirect('admin/services');
    }
}