<?php
// model/service/AdminService.php
require_once __DIR__ . '/../core/AbstractPdo.php';
require_once __DIR__ . '/../util/SessionManager.php';

class AdminService extends AbstractPdo {
    protected $table = 'admin';
    protected $primaryKey = 'id';

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

    /**
     * Get dashboard statistics
     */
    public function getDashboardStats() {
        try {
            // Get total students
            $studentsCount = $this->countStudents();

            // Get total concours
            $concoursCount = $this->countConcours();

            // Get total inscriptions
            $inscriptionsCount = $this->countInscriptions();

            // Get total demandes de documents
            $demandesCount = $this->countDemandes();

            // Get total avancements
            $avancementsCount = $this->countAvancements();

            // Get pending avancements
            $pendingAvancements = $this->countPendingAvancements();

            // Get total professeurs
            $professeursCount = $this->countProfesseurs();

            // Get recent inscriptions (last 7 days)
            $recentInscriptions = $this->countRecentInscriptions();

            return [
                'students' => $studentsCount,
                'concours' => $concoursCount,
                'inscriptions' => $inscriptionsCount,
                'demandes' => $demandesCount,
                'avancements' => $avancementsCount,
                'pendingAvancements' => $pendingAvancements,
                'professeurs' => $professeursCount,
                'recentInscriptions' => $recentInscriptions
            ];
        } catch (Exception $e) {
            throw new Exception('Error getting dashboard stats: ' . $e->getMessage());
        }
    }

    /**
     * Count total students
     */
    private function countStudents() {
        $sql = "SELECT COUNT(*) as total FROM student";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Count total concours
     */
    private function countConcours() {
        $sql = "SELECT COUNT(*) as total FROM concours";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Count total inscriptions (inscription_concours)
     */
    private function countInscriptions() {
        $sql = "SELECT COUNT(*) as total FROM inscription_concours";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Count total demandes (demande_document)
     */
    private function countDemandes() {
        $sql = "SELECT COUNT(*) as total FROM demande_document";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Count total avancements
     */
    private function countAvancements() {
        $sql = "SELECT COUNT(*) as total FROM avancement";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Count pending avancements (etat_avancement_id = 1 for 'En attente')
     */
    private function countPendingAvancements() {
        $sql = "SELECT COUNT(*) as total FROM avancement WHERE etat_avancement_id = 1";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Count total professeurs
     */
    private function countProfesseurs() {
        $sql = "SELECT COUNT(*) as total FROM professeur";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Count recent inscriptions (last 7 days)
     */
    private function countRecentInscriptions() {
        $sql = "SELECT COUNT(*) as total FROM inscription_concours WHERE date_inscription >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        $stmt = $this->pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return (int)$result['total'];
    }

    /**
     * Get inscriptions data for chart (by concours)
     */
    public function getInscriptionsData() {
        try {
            $sql = "SELECT
                        c.label as concours,
                        COUNT(i.id) as total
                    FROM concours c
                    LEFT JOIN inscription_concours i ON c.id = i.concours_id
                    GROUP BY c.id
                    ORDER BY total DESC
                    LIMIT 10";

            $stmt = $this->pdo->query($sql);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // If no results, return empty data
            if (empty($results)) {
                return ['labels' => [], 'values' => []];
            }

            return [
                'labels' => array_column($results, 'concours'),
                'values' => array_map('intval', array_column($results, 'total'))
            ];
        } catch (Exception $e) {
            throw new Exception('Error getting inscriptions data: ' . $e->getMessage());
        }
    }

    /**
     * Get demandes data for chart (by month - last 6 months)
     */
    public function getDemandesData() {
        try {
            $sql = "SELECT
                        DATE_FORMAT(date_creation, '%Y-%m') as mois,
                        COUNT(*) as total
                    FROM demande_document
                    WHERE date_creation >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
                    GROUP BY DATE_FORMAT(date_creation, '%Y-%m')
                    ORDER BY mois ASC";

            $stmt = $this->pdo->query($sql);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Format months for display
            $months = [];
            $counts = [];

            // If no results, generate empty data for last 6 months
            if (empty($results)) {
                $currentMonth = new DateTime();
                for ($i = 5; $i >= 0; $i--) {
                    $date = new DateTime();
                    $date->modify("-$i months");
                    $months[] = $date->format('M Y');
                    $counts[] = 0;
                }
                return ['labels' => $months, 'values' => $counts];
            }

            foreach ($results as $row) {
                $date = DateTime::createFromFormat('Y-m', $row['mois']);
                $months[] = $date->format('M Y');
                $counts[] = (int)$row['total'];
            }

            return [
                'labels' => $months,
                'values' => $counts
            ];
        } catch (Exception $e) {
            throw new Exception('Error getting demandes data: ' . $e->getMessage());
        }
    }

    /**
     * Get avancements data for chart (by month - last 6 months)
     */
    public function getAvancementsData() {
        try {
            $sql = "SELECT
                        DATE_FORMAT(date_creation, '%Y-%m') as mois,
                        COUNT(*) as total
                    FROM avancement
                    WHERE date_creation >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
                    GROUP BY DATE_FORMAT(date_creation, '%Y-%m')
                    ORDER BY mois ASC";

            $stmt = $this->pdo->query($sql);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Format months for display
            $months = [];
            $counts = [];

            if (empty($results)) {
                $currentMonth = new DateTime();
                for ($i = 5; $i >= 0; $i--) {
                    $date = new DateTime();
                    $date->modify("-$i months");
                    $months[] = $date->format('M Y');
                    $counts[] = 0;
                }
                return ['labels' => $months, 'values' => $counts];
            }

            foreach ($results as $row) {
                $date = DateTime::createFromFormat('Y-m', $row['mois']);
                $months[] = $date->format('M Y');
                $counts[] = (int)$row['total'];
            }

            return [
                'labels' => $months,
                'values' => $counts
            ];
        } catch (Exception $e) {
            throw new Exception('Error getting avancements data: ' . $e->getMessage());
        }
    }

    /**
     * Get concours data with statistics
     */
    public function getConcoursData() {
        try {
            $sql = "SELECT
                        c.*,
                        (SELECT COUNT(*) FROM inscription_concours WHERE concours_id = c.id) as inscriptions_count,
                        (SELECT COUNT(*) FROM concours_detail WHERE concours_id = c.id) as details_count
                    FROM concours c
                    ORDER BY c.id DESC
                    LIMIT 10";

            $stmt = $this->pdo->query($sql);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return $results;
        } catch (Exception $e) {
            throw new Exception('Error getting concours data: ' . $e->getMessage());
        }
    }

    /**
     * Get admin by ID
     */
    public function getAdmin($id) {
        return $this->findOne($id);
    }

    /**
     * Create a new admin
     */
    public function createAdmin($data) {
        // Hash password if provided
        if (isset($data['password']) && !empty($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        return $this->insert($data);
    }

    /**
     * Update an admin
     */
    public function updateAdmin($id, $data) {
        // Hash password if provided and not empty
        if (isset($data['password']) && !empty($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        } else {
            // Remove password field if empty (don't update)
            unset($data['password']);
        }
        return $this->update($id, $data);
    }

    /**
     * Delete an admin
     */
    public function deleteAdmin($id) {
        return $this->delete($id);
    }

    /**
     * Search admins with criteria
     */
    public function search($searchData, $page = 1, $perPage = 10) {
        $filters = [];
        $searchFields = ['nom', 'prenom', 'email'];

        foreach ($searchFields as $field) {
            if (!empty($searchData[$field])) {
                $filters[$field] = [
                    'value' => $searchData[$field],
                    'like' => true
                ];
            }
        }

        $offset = ($page - 1) * $perPage;
        $admins = $this->findMultiple($filters, 'id DESC', $perPage, $offset);
        $total = $this->count($filters);

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

    /**
     * Authenticate admin
     */
    public function authenticate($email, $password) {
        try {
            $sql = "SELECT * FROM admin WHERE email = :email LIMIT 1";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute(['email' => $email]);
            $admin = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($admin && password_verify($password, $admin['password'])) {
                unset($admin['password']); // Remove password from result
                return $admin;
            }
            return null;
        } catch (Exception $e) {
            throw new Exception('Error during authentication: ' . $e->getMessage());
        }
    }
}
?>