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

class TypeDemandeDocumentService extends AbstractPdo {
    protected $table = 'type_demande_document';
    protected $primaryKey = 'id';

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

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

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

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

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

    /**
     * Find types with filters
     */
    public function findWithFilters($filters = [], $limit = null, $offset = null) {
        $sql = "SELECT * FROM type_demande_document";

        $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 types with filters
     */
    public function countWithFilters($filters = []) {
        $sql = "SELECT COUNT(*) as count FROM type_demande_document";

        $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 de document par ID
     */
    public function getTypeDemandeDocument($id) {
        return $this->findOne($id);
    }

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

    /**
     * Créer un nouveau type de document
     */
    public function createTypeDemandeDocument($data) {
        if (empty($data['libelle'])) {
            throw new Exception("Le libellé est obligatoire");
        }
        if (empty($data['code'])) {
            throw new Exception("Le code est obligatoire");
        }

        $this->checkDuplicates($data);

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

    /**
     * Mettre à jour un type de document
     */
    public function updateTypeDemandeDocument($id, $data) {
        $existing = $this->findOne($id);
        if (!$existing) {
            throw new Exception("Type de document document non trouvé");
        }

        $this->checkDuplicates($data, $id);

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

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

        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 de document");
                }
            }
        }
    }

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

        if ($result['count'] > 0) {
            throw new Exception("Ce type de document est utilisé par des demandes 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();
    }

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

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

        $csv = "ID,Libellé,Code,Description,Template,Date de création,Date de mise à jour\n";
        foreach ($types as $t) {
            $csv .= implode(',', [
                $t['id'],
                '"' . addslashes($t['libelle']) . '"',
                '"' . addslashes($t['code']) . '"',
                '"' . addslashes($t['description'] ?? '') . '"',
                '"' . addslashes($t['template_document'] ?? '') . '"',
                $t['created_at'] ?? '',
                $t['updated_at'] ?? ''
            ]) . "\n";
        }

        return $csv;
    }

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


}
