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

class DepartementService extends AbstractPdo {
    protected $table = 'departement';
    protected $primaryKey = 'id';

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

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

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

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

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

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

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

        $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 département par ID
     */
    public function getDepartement($id) {
        return $this->findOne($id);
    }

    /**
     * Obtenir un département par code
     */
    public function getDepartementByCode($code) {
        return $this->findOneBy(['code' => $code]);
    }

    /**
     * Créer un nouveau département
     */
    public function createDepartement($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 est obligatoire");
        }

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

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

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

        // 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'];

        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 département");
                }
            }
        }
    }

    /**
     * Supprimer un département
     */
    public function deleteDepartement($id) {
        // Vérifier si le département est utilisé par des filières
        $sql = "SELECT COUNT(*) as count FROM filiere WHERE departement_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

        if ($result['count'] > 0) {
            throw new Exception("Ce département est utilisé par des filières et ne peut pas être supprimé");
        }

        // Vérifier si le département est utilisé par des modules
        $sql = "SELECT COUNT(*) as count FROM module 
                INNER JOIN filiere ON module.filiere = filiere.id 
                WHERE filiere.departement_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

        if ($result['count'] > 0) {
            throw new Exception("Ce département est utilisé par des modules 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 départements (CSV)
     */
    public function exportToCsv() {
        $departements = $this->findAll('libelle ASC');

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

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

        return $csv;
    }

    /**
     * Obtenir tous les départements (pour les selects)
     */
    public function getAllDepartements() {
        return $this->findAll('libelle ASC');
    }
}