<?php
/**
 * نسخة مبسطة من كود إضافة الكليات
 * يمكن استخدامها كمرجع
 */

// معالجة الإضافة - نسخة مبسطة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add' && $auth->hasRole('admin')) {
    $name_ar = trim($_POST['name_ar'] ?? '');
    $name_en = trim($_POST['name_en'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $specialization_year = !empty($_POST['specialization_year']) ? (int)$_POST['specialization_year'] : null;
    
    if ($name_ar && $code) {
        try {
            // 1. إصلاح السجل ب ID = 0 أولاً (إذا كان موجوداً)
            $zero_college = $db->fetchOne("SELECT * FROM colleges WHERE id = 0");
            if ($zero_college) {
                // التحقق من وجود رمز مكرر
                $code_exists = $db->fetchOne("SELECT id FROM colleges WHERE code = ? AND id > 0", [$zero_college['code']]);
                
                if ($code_exists) {
                    // الرمز موجود، حذف السجل ب ID = 0
                    $db->query("DELETE FROM majors WHERE college_id = 0");
                    $db->query("DELETE FROM users WHERE college_id = 0");
                    $db->query("DELETE FROM students WHERE college_id = 0");
                    $db->query("DELETE FROM colleges WHERE id = 0");
                } else {
                    // نقل السجل إلى ID جديد
                    $max_id = $db->fetchOne("SELECT MAX(id) as max_id FROM colleges WHERE id > 0");
                    $new_id = ($max_id['max_id'] ?? 0) + 1;
                    
                    $db->query(
                        "INSERT INTO colleges (id, name_ar, name_en, code, specialization_year, created_at, updated_at) 
                         VALUES (?, ?, ?, ?, ?, ?, ?)",
                        [$new_id, $zero_college['name_ar'], $zero_college['name_en'], $zero_college['code'], 
                         $zero_college['specialization_year'], $zero_college['created_at'], $zero_college['updated_at']]
                    );
                    
                    $db->query("UPDATE majors SET college_id = ? WHERE college_id = 0", [$new_id]);
                    $db->query("UPDATE users SET college_id = ? WHERE college_id = 0", [$new_id]);
                    $db->query("UPDATE students SET college_id = ? WHERE college_id = 0", [$new_id]);
                    $db->query("DELETE FROM colleges WHERE id = 0");
                }
                
                // إصلاح AUTO_INCREMENT
                $max_id = $db->fetchOne("SELECT MAX(id) as max_id FROM colleges WHERE id > 0");
                $new_auto_increment = ($max_id['max_id'] ?? 0) + 1;
                $db->getConnection()->exec("ALTER TABLE colleges AUTO_INCREMENT = " . (int)$new_auto_increment);
            }
            
            // 2. التحقق من عدم وجود رمز مكرر
            $existing = $db->fetchOne("SELECT id, name_ar FROM colleges WHERE code = ? AND id > 0", [$code]);
            if ($existing) {
                $message = '<div class="alert alert-error">رمز الكلية "'.htmlspecialchars($code).'" موجود مسبقاً (الكلية: '.htmlspecialchars($existing['name_ar']).', ID: '.$existing['id'].')</div>';
            } else {
                // 3. إضافة الكلية
                $db->query(
                    "INSERT INTO colleges (name_ar, name_en, code, specialization_year) VALUES (?, ?, ?, ?)",
                    [$name_ar, $name_en, $code, $specialization_year]
                );
                $message = '<div class="alert alert-success">تم إضافة الكلية بنجاح</div>';
                header('Location: colleges.php');
                exit;
            }
        } catch (PDOException $e) {
            $message = '<div class="alert alert-error">خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    } else {
        $message = '<div class="alert alert-error">يرجى ملء جميع الحقول المطلوبة</div>';
    }
}

