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

class GradeService extends AbstractPdo {
    protected $table = 'grade';
    protected $primaryKey = 'id';

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


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

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

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

        $offset = ($page - 1) * $perPage;
        $grades = $this->findWithTypeGrade($filters, $perPage, $offset);
        $total = $this->countWithTypeGrade($filters);

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

    /**
     * Find grades with type_grade information
     */
    public function findWithTypeGrade($filters = [], $limit = null, $offset = null) {
        $sql = "SELECT g.*, tg.libelle as type_grade_libelle, tg.code as type_grade_code 
                FROM grade g 
                LEFT JOIN type_grade tg ON g.type_grade_id = tg.id";

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

        foreach ($filters as $key => $filter) {
            $field = "g.{$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 g.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 grades with type_grade information
     */
    public function countWithTypeGrade($filters = []) {
        $sql = "SELECT COUNT(*) as count 
                FROM grade g 
                LEFT JOIN type_grade tg ON g.type_grade_id = tg.id";

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

        foreach ($filters as $key => $filter) {
            $field = "g.{$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 grade par ID avec son type de grade
     */
    public function getGrade($id) {
        $sql = "SELECT g.*, tg.libelle as type_grade_libelle, tg.code as type_grade_code 
                FROM grade g 
                LEFT JOIN type_grade tg ON g.type_grade_id = tg.id 
                WHERE g.id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        return $stmt->fetch();
    }

    /**
     * Obtenir un grade par code
     */
    public function getGradeByCode($code) {
        return $this->findOneBy(['code' => $code]);
    }

    /**
     * Créer un nouveau grade
     */
    public function createGrade($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['type_grade_id'])) {
            throw new Exception("Le type de grade est obligatoire");
        }

        // Vérifier que le type_grade existe
        $this->checkTypeGradeExists($data['type_grade_id']);

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

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


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

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

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

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

    /**
     * Vérifier que le type_grade existe
     */
    private function checkTypeGradeExists($typeGradeId) {
        $sql = "SELECT id FROM type_grade WHERE id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $typeGradeId]);
        if (!$stmt->fetch()) {
            throw new Exception("Le type de grade 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 un autre grade");
                }
            }
        }
    }

    /**
     * Supprimer un grade
     */
    public function deleteGrade($id) {
        // Vérifier si le grade est utilisé par des professeurs
        $sql = "SELECT COUNT(*) as count FROM professeur WHERE grade_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

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

        // Vérifier si le grade est utilisé dans des échelles
        $sql = "SELECT COUNT(*) as count FROM echelle WHERE grade_id = :id";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([':id' => $id]);
        $result = $stmt->fetch();

        if ($result['count'] > 0) {
            throw new Exception("Ce grade est utilisé dans des échelles 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 grades (CSV)
     */
    public function exportToCsv() {
        $grades = $this->findWithTypeGrade([], null, null);

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

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

        return $csv;
    }

    /**
     * Obtenir tous les grades (pour les selects)
     */
    public function getAllGrades() {
        return $this->findAll('libelle ASC');
    }

    /**
     * Obtenir les grades par type de grade
     */
    public function getGradesByType($typeGradeId) {
        return $this->findAllBy(['type_grade_id' => $typeGradeId], 'libelle ASC');
    }
}
