<?php
// app/model/service/MimeDocumentDossierAdminService.php
require_once __DIR__ . '/../core/AbstractPdo.php';

class MimeDocumentDossierAdminService extends AbstractPdo {
    protected $table = 'mime_document_dossier_admin';
    protected $primaryKey = 'id';

    public function __construct() {
        parent::__construct();
    }

    /**
     * Rechercher des types MIME avec critères
     */
    public function search($searchData, $page = 1, $perPage = 10) {
        $filters = [];

        // Filtres sur les champs
        $searchFields = ['id', 'libelle', 'code', 'description', 'badge'];
        foreach ($searchFields as $field) {
            if (!empty($searchData[$field])) {
                $filters[$field] = [
                    'value' => $searchData[$field],
                    'like' => true
                ];
            }
        }

        $offset = ($page - 1) * $perPage;
        $mimeTypes = $this->findWithFilters($filters, $perPage, $offset);
        $total = $this->countWithFilters($filters);

        return [
            'data' => $mimeTypes,
            'total' => $total,
            'page' => $page,
            'perPage' => $perPage,
            'totalPages' => ceil($total / $perPage)
        ];
    }

    /**
     * Find mime types with filters
     */
    public function findWithFilters($filters = [], $limit = null, $offset = null) {
        $sql = "SELECT * FROM {$this->table}";

        $where = [];
        $params = [];

        foreach ($filters as $key => $filter) {
            $field = $key;

            if (isset($filter['like']) && $filter['like'] && !empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} LIKE :{$paramKey}";
                $params[":{$paramKey}"] = '%' . $filter['value'] . '%';
            } elseif (!empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} = :{$paramKey}";
                $params[":{$paramKey}"] = $filter['value'];
            }
        }

        if (!empty($where)) {
            $sql .= " WHERE " . implode(' AND ', $where);
        }

        $sql .= " ORDER BY libelle ASC";

        if ($limit !== null) {
            $sql .= " LIMIT " . (int)$limit;
            if ($offset !== null) {
                $sql .= " OFFSET " . (int)$offset;
            }
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    /**
     * Count mime types with filters
     */
    public function countWithFilters($filters = []) {
        $sql = "SELECT COUNT(*) as count FROM {$this->table}";

        $where = [];
        $params = [];

        foreach ($filters as $key => $filter) {
            $field = $key;

            if (isset($filter['like']) && $filter['like'] && !empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} LIKE :{$paramKey}";
                $params[":{$paramKey}"] = '%' . $filter['value'] . '%';
            } elseif (!empty($filter['value'])) {
                $paramKey = str_replace('.', '_', $key);
                $where[] = "{$field} = :{$paramKey}";
                $params[":{$paramKey}"] = $filter['value'];
            }
        }

        if (!empty($where)) {
            $sql .= " WHERE " . implode(' AND ', $where);
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        $result = $stmt->fetch();
        return (int)$result['count'];
    }

    /**
     * Obtenir un type MIME par ID
     */
    public function getMimeType($id) {
        return $this->findOne($id);
    }

    /**
     * Obtenir un type MIME par code
     */
    public function getMimeTypeByCode($code) {
        return $this->findOneBy(['code' => $code]);
    }

    /**
     * Créer un nouveau type MIME
     */
    public function createMimeType($data) {
        // Valider les données
        if (empty($data['libelle'])) {
            throw new Exception("Le libellé est obligatoire");
        }
        if (empty($data['code'])) {
            throw new Exception("Le code MIME est obligatoire");
        }
        if (empty($data['badge'])) {
            throw new Exception("Le badge est obligatoire");
        }

        // Valider le format du code MIME
        if (!strpos($data['code'], '/')) {
            throw new Exception("Le code MIME doit être au format 'type/sous-type' (ex: application/pdf, image/jpeg)");
        }

        // Vérifier les doublons
        $this->checkDuplicates($data);

        return $this->insert($data);
    }

    /**
     * Mettre à jour un type MIME
     */
    public function updateMimeType($id, $data) {
        // Vérifier si le type MIME existe
        $existing = $this->findOne($id);
        if (!$existing) {
            throw new Exception("Type MIME non trouvé");
        }

        // Si le code est modifié, vérifier son format
        if (isset($data['code']) && !strpos($data['code'], '/')) {
            throw new Exception("Le code MIME doit être au format 'type/sous-type' (ex: application/pdf, image/jpeg)");
        }

        // Vérifier les doublons (exclure l'ID actuel)
        $this->checkDuplicates($data, $id);

        return $this->update($id, $data);
    }

    /**
     * Vérifier les doublons
     */
    private function checkDuplicates($data, $excludeId = null) {
        $uniqueFields = ['code', 'libelle'];

        foreach ($uniqueFields as $field) {
            if (isset($data[$field]) && !empty($data[$field])) {
                $criteria = [$field => $data[$field]];
                $existing = $this->findOneBy($criteria);

                if ($existing && ($excludeId === null || $existing['id'] != $excludeId)) {
                    throw new Exception("Le champ '$field' est déjà utilisé par un autre type MIME");
                }
            }
        }
    }

    /**
     * Supprimer un type MIME
     */
    public function deleteMimeType($id) {
        // Vérifier si le type MIME est utilisé par des documents
        $sql = "SELECT COUNT(*) as count FROM document_dossier_admin WHERE mime_type_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

        if ($result['count'] > 0) {
            throw new Exception("Ce type MIME est utilisé par des documents et ne peut pas être supprimé");
        }

        return $this->delete($id);
    }

    /**
     * Obtenir les statistiques
     */
    public function getStats() {
        $sql = "SELECT COUNT(*) as total FROM {$this->table}";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->fetch();
    }

    /**
     * Obtenir tous les types MIME (pour les selects)
     */
    public function getAllMimeTypes() {
        return $this->findAll('libelle ASC');
    }

    /**
     * Obtenir les badges disponibles
     */
    public function getAvailableBadges() {
        return ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark'];
    }

    /**
     * Exporter les types MIME (CSV)
     */
    public function exportToCsv() {
        $mimeTypes = $this->findAll('libelle ASC');

        if (empty($mimeTypes)) {
            return null;
        }

        $csv = "ID,Libellé,Code MIME,Description,Badge,Date de création\n";
        foreach ($mimeTypes as $m) {
            $csv .= implode(',', [
                    $m['id'],
                    '"' . addslashes($m['libelle']) . '"',
                    '"' . addslashes($m['code']) . '"',
                    '"' . addslashes($m['description'] ?? '') . '"',
                    '"' . addslashes($m['badge'] ?? '') . '"',
                    $m['created_at'] ?? ''
                ]) . "\n";
        }

        return $csv;
    }
}