<?php

namespace App\Services;

/**
 * Servicio de Plantillas de Contratos
 * Gestión de la librería de plantillas reutilizables
 */
class TemplateService
{
    private Database $db;
    private Logger $logger;
    private SecurityService $security;

    public function __construct()
    {
        $this->db = Database::getInstance();
        $this->logger = new Logger();
        $this->security = new SecurityService();
    }

    /**
     * Listar todas las plantillas activas
     */
    public function list(array $filters = []): array
    {
        $where = ['activo = 1'];
        $params = [];

        if (!empty($filters['categoria'])) {
            $where[] = 'categoria = :categoria';
            $params[':categoria'] = $filters['categoria'];
        }

        if (!empty($filters['search'])) {
            $where[] = '(nombre LIKE :search OR descripcion LIKE :search)';
            $params[':search'] = '%' . $filters['search'] . '%';
        }

        $whereSql = implode(' AND ', $where);
        $orderBy = $filters['order_by'] ?? 'nombre ASC';

        $sql = "SELECT * FROM contract_templates
                WHERE {$whereSql}
                ORDER BY {$orderBy}";

        return $this->db->fetchAll($sql, $params);
    }

    /**
     * Listar todas las plantillas (incluyendo inactivas) - solo para admin
     */
    public function listAll(array $filters = []): array
    {
        $where = ['1=1'];
        $params = [];

        if (isset($filters['activo'])) {
            $where[] = 'activo = :activo';
            $params[':activo'] = (int)$filters['activo'];
        }

        if (!empty($filters['categoria'])) {
            $where[] = 'categoria = :categoria';
            $params[':categoria'] = $filters['categoria'];
        }

        if (!empty($filters['search'])) {
            $where[] = '(nombre LIKE :search OR descripcion LIKE :search)';
            $params[':search'] = '%' . $filters['search'] . '%';
        }

        $whereSql = implode(' AND ', $where);
        $orderBy = $filters['order_by'] ?? 'created_at DESC';

        $sql = "SELECT * FROM contract_templates
                WHERE {$whereSql}
                ORDER BY {$orderBy}";

        return $this->db->fetchAll($sql, $params);
    }

    /**
     * Obtener plantilla por ID
     */
    public function getById(int $id): ?array
    {
        return $this->db->fetchOne(
            "SELECT * FROM contract_templates WHERE id = :id",
            [':id' => $id]
        );
    }

    /**
     * Crear nueva plantilla
     */
    public function create(array $data): array
    {
        // Validar datos requeridos
        $required = ['nombre', 'contenido'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                return [
                    'success' => false,
                    'message' => "El campo {$field} es requerido."
                ];
            }
        }

        // Sanitizar datos
        $nombre = $this->security->sanitizeString($data['nombre']);
        $descripcion = !empty($data['descripcion'])
            ? $this->security->sanitizeString($data['descripcion'])
            : null;
        $contenido = $this->security->cleanHTML($data['contenido']);
        $categoria = !empty($data['categoria'])
            ? $this->security->sanitizeString($data['categoria'])
            : 'general';
        $previewImagen = !empty($data['preview_imagen'])
            ? $this->security->sanitizeString($data['preview_imagen'])
            : null;

        try {
            $templateId = $this->db->insert('contract_templates', [
                'nombre' => $nombre,
                'descripcion' => $descripcion,
                'contenido' => $contenido,
                'categoria' => $categoria,
                'preview_imagen' => $previewImagen,
                'activo' => 1
            ]);

            $this->logger->info("Template created: {$nombre} (ID: {$templateId})");

            return [
                'success' => true,
                'message' => 'Plantilla creada exitosamente.',
                'template_id' => $templateId
            ];
        } catch (\Exception $e) {
            $this->logger->error('Error creating template: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => 'Error al crear la plantilla.'
            ];
        }
    }

    /**
     * Actualizar plantilla existente
     */
    public function update(int $id, array $data): array
    {
        $template = $this->getById($id);
        if (!$template) {
            return [
                'success' => false,
                'message' => 'Plantilla no encontrada.'
            ];
        }

        $updateData = [];

        if (isset($data['nombre'])) {
            $updateData['nombre'] = $this->security->sanitizeString($data['nombre']);
        }

        if (isset($data['descripcion'])) {
            $updateData['descripcion'] = $this->security->sanitizeString($data['descripcion']);
        }

        if (isset($data['contenido'])) {
            $updateData['contenido'] = $this->security->cleanHTML($data['contenido']);
        }

        if (isset($data['categoria'])) {
            $updateData['categoria'] = $this->security->sanitizeString($data['categoria']);
        }

        if (isset($data['preview_imagen'])) {
            $updateData['preview_imagen'] = $this->security->sanitizeString($data['preview_imagen']);
        }

        if (isset($data['activo'])) {
            $updateData['activo'] = (int)$data['activo'];
        }

        if (empty($updateData)) {
            return [
                'success' => false,
                'message' => 'No hay datos para actualizar.'
            ];
        }

        try {
            $this->db->update(
                'contract_templates',
                $updateData,
                'id = :id',
                [':id' => $id]
            );

            $this->logger->info("Template updated: {$template['nombre']} (ID: {$id})");

            return [
                'success' => true,
                'message' => 'Plantilla actualizada exitosamente.'
            ];
        } catch (\Exception $e) {
            $this->logger->error('Error updating template: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => 'Error al actualizar la plantilla.'
            ];
        }
    }

    /**
     * Eliminar plantilla (soft delete - marcar como inactiva)
     */
    public function delete(int $id): array
    {
        $template = $this->getById($id);
        if (!$template) {
            return [
                'success' => false,
                'message' => 'Plantilla no encontrada.'
            ];
        }

        try {
            $this->db->update(
                'contract_templates',
                ['activo' => 0],
                'id = :id',
                [':id' => $id]
            );

            $this->logger->info("Template deleted: {$template['nombre']} (ID: {$id})");

            return [
                'success' => true,
                'message' => 'Plantilla eliminada exitosamente.'
            ];
        } catch (\Exception $e) {
            $this->logger->error('Error deleting template: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => 'Error al eliminar la plantilla.'
            ];
        }
    }

    /**
     * Eliminar plantilla permanentemente
     */
    public function permanentDelete(int $id): array
    {
        $template = $this->getById($id);
        if (!$template) {
            return [
                'success' => false,
                'message' => 'Plantilla no encontrada.'
            ];
        }

        try {
            // Eliminar imagen de preview si existe
            if (!empty($template['preview_imagen'])) {
                $imagePath = storage_path($template['preview_imagen']);
                if (file_exists($imagePath)) {
                    unlink($imagePath);
                }
            }

            $this->db->delete('contract_templates', 'id = :id', [':id' => $id]);

            $this->logger->info("Template permanently deleted: {$template['nombre']} (ID: {$id})");

            return [
                'success' => true,
                'message' => 'Plantilla eliminada permanentemente.'
            ];
        } catch (\Exception $e) {
            $this->logger->error('Error permanently deleting template: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => 'Error al eliminar la plantilla.'
            ];
        }
    }

    /**
     * Incrementar contador de uso de plantilla
     */
    public function incrementUsage(int $id): void
    {
        try {
            $this->db->query(
                "UPDATE contract_templates SET uso_count = uso_count + 1 WHERE id = :id",
                [':id' => $id]
            );
        } catch (\Exception $e) {
            $this->logger->error('Error incrementing template usage: ' . $e->getMessage());
        }
    }

    /**
     * Obtener categorías únicas
     */
    public function getCategories(): array
    {
        $result = $this->db->fetchAll(
            "SELECT DISTINCT categoria FROM contract_templates WHERE activo = 1 ORDER BY categoria ASC"
        );

        return array_column($result, 'categoria');
    }

    /**
     * Obtener estadísticas de plantillas
     */
    public function getStats(): array
    {
        return $this->db->fetchOne(
            "SELECT
                COUNT(*) as total,
                SUM(CASE WHEN activo = 1 THEN 1 ELSE 0 END) as activas,
                SUM(CASE WHEN activo = 0 THEN 1 ELSE 0 END) as inactivas,
                SUM(uso_count) as total_usos
             FROM contract_templates"
        ) ?: [
            'total' => 0,
            'activas' => 0,
            'inactivas' => 0,
            'total_usos' => 0
        ];
    }
}
