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

class TypeGradeService extends AbstractPdo {
    protected $table = 'type_grade';
    protected $primaryKey = 'id';

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

    /**
     * Rechercher des grades avec critères
     */
    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;
        $grades = $this->findMultiple($filters, 'libelle ASC', $perPage, $offset);
        $total = $this->count($filters);

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

    /**
     * Obtenir un grade par ID
     */
    public function getGrade($id) {
        return $this->findOne($id);
    }

    /**
     * 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");
        }

        // 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 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 grade");
                }
            }
        }
    }

    /**
     * Supprimer un grade
     */
    public function deleteGrade($id) {
        $sql = "SELECT COUNT(*) as count FROM professeur WHERE grade_id  = (SELECT id FROM type_grade WHERE 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é");
        }

        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->findAll('libelle ASC');

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

        $csv = "ID,Libellé,Code,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['description'] ?? '') . '"',
                    $g['created_at'],
                    $g['updated_at'] ?? ''
                ]) . "\n";
        }

        return $csv;
    }

    /**
     * Importer des grades (CSV)
     */
    public function importFromCsv($csvData) {
        $lines = explode("\n", trim($csvData));
        $headers = str_getcsv(array_shift($lines));

        $imported = 0;
        $errors = [];

        foreach ($lines as $line) {
            if (empty(trim($line))) continue;

            $data = array_combine($headers, str_getcsv($line));

            try {
                // Vérifier si le code existe déjà
                $existing = $this->findOneBy(['code' => $data['Code']]);
                if ($existing) {
                    // Mettre à jour
                    $this->update($existing['id'], [
                        'libelle' => $data['Libellé'],
                        'description' => $data['Description'] ?? null
                    ]);
                } else {
                    // Créer
                    $this->createGrade([
                        'libelle' => $data['Libellé'],
                        'code' => $data['Code'],
                        'description' => $data['Description'] ?? null
                    ]);
                }
                $imported++;
            } catch (Exception $e) {
                $errors[] = "Erreur ligne " . ($imported + 1) . ": " . $e->getMessage();
            }
        }

        return [
            'imported' => $imported,
            'errors' => $errors
        ];
    }

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