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

class EtatDemandeDocumentService extends AbstractPdo {
    protected $table = 'etat_demande_document';
    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 getEtatDemande($id) {
        return $this->findOne($id);
    }

    public function createEtatDemande($data) {
        if (empty($data['libelle']) || empty($data['code'])) {
            throw new Exception("Le libellé et le code sont obligatoires");
        }
        $this->checkDuplicates($data);
        return $this->insert($data);
    }

    public function updateEtatDemande($id, $data) {
        $existing = $this->findOne($id);
        if (!$existing) {
            throw new Exception("État de demande 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é");
            }
        }
    }

    public function deleteEtatDemande($id) {
        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()];
    }
}