<?php
/**
 * صفحة تحميل القوالب
 * Download Templates Page
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';

$auth = new Auth();
if (!$auth->isLoggedIn() || (!$auth->hasRole('admin') && !$auth->hasRole('college_admin') && !$auth->hasRole('registrar') && !$auth->hasPermission('enter_grades') && !$auth->hasPermission('manage_grades'))) {
    header('Location: index.php');
    exit;
}

$template_type = isset($_GET['type']) ? $_GET['type'] : '';

// تحديد نوع القالب
if ($template_type === 'students') {
    // قالب رفع الطلاب (إنجليزي) - يطابق حقول جدول students
    $filename = 'template_students.csv';
    $filepath = __DIR__ . '/templates/template_students.csv';
    $template_dir = dirname($filepath);
    if (!is_dir($template_dir)) {
        mkdir($template_dir, 0755, true);
    }
    if (!file_exists($filepath)) {
        $template_content = "student_number,full_name_ar,full_name_en,national_id,email,phone,address,enrollment_date,graduation_date,status,major_code\n";
        $template_content .= "2023001,أحمد محمد علي,Ahmed Mohammed Ali,123456789012,ahmed@example.com,0501234567,الرياض - حي الجامعة,2023-09-01,,active,CS001\n";
        $template_content .= "2023002,فاطمة أحمد حسن,Fatima Ahmed Hassan,234567890123,fatima@example.com,0502345678,,2023-09-01,,active,CS001\n";
        $template_content .= "2023003,محمد خالد إبراهيم,Mohammed Khalid Ibrahim,345678901234,mohammed@example.com,0503456789,,2023-09-01,,active,CS002\n";
        if (!mb_check_encoding($template_content, 'UTF-8')) {
            $template_content = mb_convert_encoding($template_content, 'UTF-8', 'auto');
        }
        file_put_contents($filepath, "\xEF\xBB\xBF" . $template_content, LOCK_EX);
    }
    $content = file_get_contents($filepath);
    if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
        $content = substr($content, 3);
    }
    if (!mb_check_encoding($content, 'UTF-8')) {
        $content = mb_convert_encoding($content, 'UTF-8', 'auto');
    }
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Transfer-Encoding: binary');
    echo "\xEF\xBB\xBF" . $content;
    exit;
}

elseif ($template_type === 'students_ar') {
    // قالب رفع الطلاب (عناوين عربية) - نفس الحقول بأسماء عربية
    $filename = 'قالب_استيراد_الطلاب.csv';
    $filepath = __DIR__ . '/templates/template_students_ar.csv';
    $template_dir = dirname($filepath);
    if (!is_dir($template_dir)) {
        mkdir($template_dir, 0755, true);
    }
    if (!file_exists($filepath)) {
        $template_content = "الرقم الجامعي,الاسم العربي,الاسم الإنجليزي,الرقم الوطني,البريد الإلكتروني,الهاتف,العنوان,تاريخ التسجيل,تاريخ التخرج,الحالة,رمز التخصص\n";
        $template_content .= "2023001,أحمد محمد علي,Ahmed Mohammed Ali,123456789012,ahmed@example.com,0501234567,الرياض - حي الجامعة,2023-09-01,,active,CS001\n";
        $template_content .= "2023002,فاطمة أحمد حسن,Fatima Ahmed Hassan,234567890123,fatima@example.com,0502345678,,2023-09-01,,active,CS001\n";
        $template_content .= "2023003,محمد خالد إبراهيم,Mohammed Khalid Ibrahim,345678901234,mohammed@example.com,0503456789,,2023-09-01,,active,CS002\n";
        if (!mb_check_encoding($template_content, 'UTF-8')) {
            $template_content = mb_convert_encoding($template_content, 'UTF-8', 'auto');
        }
        file_put_contents($filepath, "\xEF\xBB\xBF" . $template_content, LOCK_EX);
    }
    $content = file_get_contents($filepath);
    if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
        $content = substr($content, 3);
    }
    if (!mb_check_encoding($content, 'UTF-8')) {
        $content = mb_convert_encoding($content, 'UTF-8', 'auto');
    }
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Transfer-Encoding: binary');
    echo "\xEF\xBB\xBF" . $content;
    exit;
    
} elseif ($template_type === 'students_law') {
    // قالب جاهز لـ كلية القانون: دمج الطلاب من law_students.csv إن وُجد، ثم حفظ في template وتقديمه
    $filename = 'قالب_طلاب_كلية_القانون.csv';
    $filepath = __DIR__ . '/templates/template_students_law.csv';
    $law_file = __DIR__ . '/law_students.csv';
    $template_dir = dirname($filepath);
    if (!is_dir($template_dir)) {
        mkdir($template_dir, 0755, true);
    }
    
    $template_content = "student_number,full_name_ar,college_id,major_id,status\n";
    
    if (is_readable($law_file)) {
        $raw = file_get_contents($law_file);
        if (substr($raw, 0, 3) === "\xEF\xBB\xBF") {
            $raw = substr($raw, 3);
        }
        if (!mb_check_encoding($raw, 'UTF-8')) {
            $raw = mb_convert_encoding($raw, 'UTF-8', 'auto');
        }
        $lines = preg_split('/\r\n|\r|\n/', trim($raw));
        $header = null;
        foreach ($lines as $i => $line) {
            $row = str_getcsv($line);
            if (empty($row)) continue;
            if ($i === 0 && preg_match('/student_number|رقم|number/i', $row[0] ?? '')) {
                $header = array_map('trim', $row);
                continue;
            }
            $num = isset($row[0]) ? trim((string)$row[0]) : '';
            $name = isset($row[1]) ? trim((string)$row[1]) : '';
            if ($num === '' && $name === '') continue;
            $template_content .= sprintf("%s,%s,,,active\n", $num, str_replace(',', ' ', $name));
        }
    }
    
    if (substr_count($template_content, "\n") <= 1) {
        $template_content .= "23-11064571,هبه الله سليمان محمد سليمان,,,active\n";
        $template_content .= "23-11015654,موسى احمد اونور محمد,,,active\n";
        $template_content .= "23-11070385,منية علي محمد ابو القاسم,,,active\n";
        $template_content .= "32-31004806,,,active\n";
    }
    
    if (!mb_check_encoding($template_content, 'UTF-8')) {
        $template_content = mb_convert_encoding($template_content, 'UTF-8', 'auto');
    }
    file_put_contents($filepath, "\xEF\xBB\xBF" . $template_content, LOCK_EX);
    $content = file_get_contents($filepath);
    if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
        $content = substr($content, 3);
    }
    if (!mb_check_encoding($content, 'UTF-8')) {
        $content = mb_convert_encoding($content, 'UTF-8', 'auto');
    }
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Transfer-Encoding: binary');
    echo "\xEF\xBB\xBF" . $content;
    exit;

} elseif ($template_type === 'grades') {
    $filename = 'قالب_رفع_الدرجات.csv';
    $major_id = isset($_GET['major_id']) ? (int)$_GET['major_id'] : 0;
    $semester_id = isset($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;

    $headers = ['student_number'];
    if ($major_id > 0 && $semester_id > 0) {
        try {
            $db = Database::getInstance();
            $courses = $db->fetchAll("SELECT code FROM courses WHERE major_id = ? AND semester_id = ? ORDER BY code", [$major_id, $semester_id]);
            foreach ($courses as $c) {
                $headers[] = trim($c['code']);
            }
        } catch (Exception $e) { }
    }
    if (count($headers) <= 1) {
        $headers = array_merge($headers, ['CS101', 'MATH101', 'ENG101']);
    }

    $template_content = implode(',', $headers) . "\n";
    $template_content .= "11079388-23,85,90,75\n";
    $template_content .= "11079100-23,80,بد,غياب\n";

    if (!mb_check_encoding($template_content, 'UTF-8')) {
        $template_content = mb_convert_encoding($template_content, 'UTF-8', 'auto');
    }
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Transfer-Encoding: binary');
    echo "\xEF\xBB\xBF" . $template_content;
    exit;
}

// إذا لم يتم تحديد نوع القالب أو حدث خطأ، إعادة توجيه للصفحة الرئيسية
header('Location: dashboard.php');
exit;

