<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';

if (!function_exists('adminStats')) {
    function adminStats(PDO $pdo): array
    {
        $joinTable = tableExists($pdo, 'core_course_join_requests') ? 'core_course_join_requests' : 'core_join_requests';
        return [
            'students' => safeCount($pdo, 'SELECT COUNT(*) FROM students'),
            'teachers' => safeCount($pdo, 'SELECT COUNT(*) FROM core_teachers'),
            'courses' => safeCount($pdo, 'SELECT COUNT(*) FROM core_courses'),
            'exams' => safeCount($pdo, 'SELECT COUNT(*) FROM core_exams'),
            'homework' => safeCount($pdo, 'SELECT COUNT(*) FROM core_homework'),
            'pending_join_requests' => safeCount($pdo, "SELECT COUNT(*) FROM {$joinTable} WHERE LOWER(COALESCE(status,'pending'))='pending'"),
            'certificates' => safeCount($pdo, 'SELECT COUNT(*) FROM core_certificates'),
        ];
    }
}
if (!function_exists('preventDuplicateEnrollment')) {
    function preventDuplicateEnrollment(PDO $pdo, int $studentId, int $courseId): bool
    {
        return safeCount($pdo, 'SELECT COUNT(*) FROM core_course_students WHERE student_id=? AND course_id=?', [$studentId,$courseId]) > 0;
    }
}
if (!function_exists('enrollStudentInCourse')) {
    function enrollStudentInCourse(PDO $pdo, int $studentId, int $courseId, string $status = 'active'): bool
    {
        if ($studentId <= 0 || $courseId <= 0) return false;
        $stmt = $pdo->prepare(
            "INSERT INTO core_course_students (student_id,course_id,status,archive_status,joined_at,created_at,updated_at)
             VALUES (?, ?, ?, 'active', NOW(), NOW(), NOW())
             ON DUPLICATE KEY UPDATE status=VALUES(status),archive_status='active',archived_at=NULL,updated_at=NOW()"
        );
        $ok = $stmt->execute([$studentId,$courseId,$status]);
        if (tableExists($pdo,'core_enrollments')) {
            safeExecute($pdo,
                "INSERT INTO core_enrollments (student_id,course_id,status,enrolled_at) VALUES (?,?,'active',NOW())
                 ON DUPLICATE KEY UPDATE status='active',completed_at=NULL",
                [$studentId,$courseId]
            );
        }
        safeExecute($pdo, "UPDATE students SET core_status='active', updated_at=NOW() WHERE id=?", [$studentId]);
        return $ok;
    }
}
if (!function_exists('approveJoinRequest')) {
    function approveJoinRequest(PDO $pdo, int $requestId, int $adminId = 0): bool
    {
        $table = tableExists($pdo,'core_course_join_requests') ? 'core_course_join_requests' : 'core_join_requests';
        $request = safeFetch($pdo,"SELECT * FROM {$table} WHERE id=? LIMIT 1",[$requestId]);
        if (!$request) return false;
        beginTransaction($pdo);
        try {
            if (!enrollStudentInCourse($pdo,(int)$request['student_id'],(int)$request['course_id'])) throw new RuntimeException('Enrollment failed');
            if ($table === 'core_course_join_requests') {
                $stmt=$pdo->prepare("UPDATE {$table} SET status='approved',approved_by=?,reviewed_at=NOW(),approved_at=NOW(),updated_at=NOW() WHERE id=?");
            } else {
                $stmt=$pdo->prepare("UPDATE {$table} SET status='approved',reviewed_by=?,reviewed_at=NOW(),updated_at=NOW() WHERE id=?");
            }
            $stmt->execute([$adminId ?: null,$requestId]);
            commitTransaction($pdo);
            return true;
        } catch (Throwable $e) {
            rollbackTransaction($pdo);
            error_log('[SMI approveJoinRequest] '.$e->getMessage());
            return false;
        }
    }
}
if (!function_exists('rejectJoinRequest')) {
    function rejectJoinRequest(PDO $pdo, int $requestId, int $adminId = 0, string $reason = ''): bool
    {
        $table = tableExists($pdo,'core_course_join_requests') ? 'core_course_join_requests' : 'core_join_requests';
        if ($table === 'core_course_join_requests') {
            return safeExecute($pdo,"UPDATE {$table} SET status='rejected',admin_notes=?,approved_by=?,reviewed_at=NOW(),rejected_at=NOW(),updated_at=NOW() WHERE id=?",[$reason,$adminId ?: null,$requestId]);
        }
        return safeExecute($pdo,"UPDATE {$table} SET status='rejected',review_note=?,reviewed_by=?,reviewed_at=NOW(),updated_at=NOW() WHERE id=?",[$reason,$adminId ?: null,$requestId]);
    }
}
