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

class FiliereService extends AbstractPdo {
    protected $table = 'filiere';
    protected $primaryKey = 'id';

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

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

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

        // Filtre par departement_id (recherche exacte avec select)
        if (!empty($searchData['departement_id'])) {
            $filters['departement_id'] = [
                'value' => $searchData['departement_id'],
                'like' => false
            ];
        }

        $offset = ($page - 1) * $perPage;
        $filieres = $this->findWithDepartement($filters, $perPage, $offset);
        $total = $this->countWithDepartement($filters);

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

    /**
     * Find filieres with departement information
     */
    public function findWithDepartement($filters = [], $limit = null, $offset = null) {
        $sql = "SELECT f.*, d.libelle as departement_libelle, d.code as departement_code 
                FROM filiere f 
                LEFT JOIN departement d ON f.departement_id = d.id";

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

        foreach ($filters as $key => $filter) {
            $field = "f.{$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 f.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 filieres with departement information
     */
    public function countWithDepartement($filters = []) {
        $sql = "SELECT COUNT(*) as count 
                FROM filiere f 
                LEFT JOIN departement d ON f.departement_id = d.id";

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

        foreach ($filters as $key => $filter) {
            $field = "f.{$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 une filière par ID avec son département
     */
    public function getFiliere($id) {
        $sql = "SELECT f.*, d.libelle as departement_libelle, d.code as departement_code 
                FROM filiere f 
                LEFT JOIN departement d ON f.departement_id = d.id 
                WHERE f.id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        return $stmt->fetch();
    }

    /**
     * Obtenir une filière par code
     */
    public function getFiliereByCode($code) {
        return $this->findOneBy(['code' => $code]);
    }

    /**
     * Créer une nouvelle filière
     */
    public function createFiliere($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");
        }
        if (empty($data['departement_id'])) {
            throw new Exception("Le département est obligatoire");
        }

        // Vérifier que le departement existe
        $this->checkDepartementExists($data['departement_id']);

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

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

    /**
     * Mettre à jour une filière
     */
    public function updateFiliere($id, $data) {
        // Vérifier si la filière existe
        $existing = $this->findOne($id);
        if (!$existing) {
            throw new Exception("Filière non trouvée");
        }

        // Vérifier que le departement existe si fourni
        if (isset($data['departement_id']) && !empty($data['departement_id'])) {
            $this->checkDepartementExists($data['departement_id']);
        }

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

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

    /**
     * Vérifier que le departement existe
     */
    private function checkDepartementExists($departementId) {
        $sql = "SELECT id FROM departement WHERE id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $departementId]);
        if (!$stmt->fetch()) {
            throw new Exception("Le département spécifié n'existe pas");
        }
    }

    /**
     * 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 une autre filière");
                }
            }
        }
    }

    /**
     * Supprimer une filière
     */
    public function deleteFiliere($id) {
        // Vérifier si la filière est utilisée par des modules
        $sql = "SELECT COUNT(*) as count FROM module WHERE filiere = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

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

        // Vérifier si la filière est utilisée dans des affectations
        $sql = "SELECT COUNT(*) as count FROM affectation_module WHERE filiere_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

        if ($result['count'] > 0) {
            throw new Exception("Cette filière est utilisée dans des affectations et ne peut pas être supprimée");
        }

        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 filières (CSV)
     */
    public function exportToCsv() {
        $filieres = $this->findWithDepartement([], null, null);

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

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

        return $csv;
    }

    /**
     * Obtenir toutes les filières (pour les selects)
     */
    public function getAllFiliere() {
        return $this->findAll('libelle ASC');
    }

    /**
     * Obtenir les filières par département
     */
    public function getFiliereByDepartement($departementId) {
        return $this->findAllBy(['departement_id' => $departementId], 'libelle ASC');
    }
}