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

class EtatDocumentDossierAdministratifService extends AbstractPdo {
    protected $table = 'etat_document_dossier_administratif';
    protected $primaryKey = 'id';

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

    public function search($searchData, $page = 1, $perPage = 10) {
        $filters = [];
        $searchFields = ['id', 'libelle', 'code', 'description'];

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

        $offset = ($page - 1) * $perPage;
        $etats = $this->findMultiple($filters, 'libelle ASC', $perPage, $offset);
        $total = $this->count($filters);

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

    public function getEtatDocument($id) {
        return $this->findOne($id);
    }

    public function createEtatDocument($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);
    }

    public function updateEtatDocument($id, $data) {
        $existing = $this->findOne($id);
        if (!$existing) {
            throw new Exception("État de document non trouvé");
        }

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

    private function checkDuplicates($data, $excludeId = null) {
        if (isset($data['code']) && !empty($data['code'])) {
            $existing = $this->findOneBy(['code' => $data['code']]);
            if ($existing && ($excludeId === null || $existing['id'] != $excludeId)) {
                throw new Exception("Le code '" . $data['code'] . "' est déjà utilisé par un autre état");
            }
        }
    }

    public function deleteEtatDocument($id) {
        // Optionnel : Vérifier si l'état est lié avant de supprimer
        $sql = "SELECT COUNT(*) as count FROM document_dossier_administratif WHERE etat_document_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

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

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

    public function getStats() {
        $sql = "SELECT COUNT(*) as total FROM {$this->table}";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        return ['total' => $stmt->fetchColumn()];
    }

    public function exportToCsv() {
        $etats = $this->findAll('libelle ASC');
        if (empty($etats)) return null;

        $csv = "ID,Libellé,Code,Description\n";
        foreach ($etats as $etat) {
            $csv .= implode(',', [
                $etat['id'],
                '"' . addslashes($etat['libelle']) . '"',
                '"' . addslashes($etat['code']) . '"',
                '"' . addslashes($etat['description'] ?? '') . '"'
            ]) . "\n";
        }
        return $csv;
    }
}