<?php
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'))) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();
$message = '';

// فحص وإصلاح AUTO_INCREMENT إذا لزم الأمر
try {
    $zero_record = $db->fetchOne("SELECT id FROM majors WHERE id = 0");
    if ($zero_record) {
        $db->query("DELETE FROM majors WHERE id = 0");
    }
    
    $columns = $db->fetchAll("SHOW COLUMNS FROM majors WHERE Field = 'id'");
    $has_auto_increment = false;
    if (!empty($columns)) {
        $has_auto_increment = (strpos($columns[0]['Extra'], 'auto_increment') !== false);
    }
    
    if (!$has_auto_increment) {
        $max_id_result = $db->fetchOne("SELECT MAX(id) as max_id FROM majors WHERE id > 0");
        $max_id = $max_id_result['max_id'] ?? 0;
        $new_auto_increment = max($max_id + 1, 1);
        $db->getConnection()->exec("ALTER TABLE majors MODIFY id INT(11) NOT NULL AUTO_INCREMENT");
        $db->getConnection()->exec("ALTER TABLE majors AUTO_INCREMENT = " . (int)$new_auto_increment);
    }
} catch (PDOException $e) {
    error_log("Auto-increment check error: " . $e->getMessage());
}

// توسيع حقول اسم التخصص (عربي/إنجليزي) لاستيعاب الأسماء الطويلة
try {
    $cols = $db->fetchAll("SHOW COLUMNS FROM majors WHERE Field IN ('name_ar', 'name_en')");
    foreach ($cols as $col) {
        $field = $col['Field'];
        $type = $col['Type'];
        if (preg_match('/varchar\((\d+)\)/i', $type, $m) && (int)$m[1] < 80) {
            if ($field === 'name_ar') {
                $db->getConnection()->exec("ALTER TABLE majors MODIFY name_ar VARCHAR(80) NOT NULL");
            } else {
                $db->getConnection()->exec("ALTER TABLE majors MODIFY name_en VARCHAR(80) NULL");
            }
        }
    }
} catch (PDOException $e) {
    error_log("Majors name columns extend error: " . $e->getMessage());
}

// معالجة AJAX requests
if (isset($_GET['action']) && $_GET['action'] == 'get_majors' && isset($_GET['college_id'])) {
    header('Content-Type: application/json');
    $college_id = (int)$_GET['college_id'];
    $majors = $db->fetchAll(
        "SELECT id, name_ar FROM majors WHERE college_id = ? ORDER BY name_ar",
        [$college_id]
    );
    echo json_encode($majors);
    exit;
}

// معالجة الإضافة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_bulk') {
    $college_id = (int)($_POST['college_id'] ?? 0);
    
    // جلب بيانات التخصصات من النموذج
    $majors_data = [];
    if (isset($_POST['majors']) && is_array($_POST['majors'])) {
        foreach ($_POST['majors'] as $major) {
            if (!empty($major['name_ar']) && !empty($major['code'])) {
                $majors_data[] = [
                    'name_ar' => trim($major['name_ar']),
                    'name_en' => trim($major['name_en'] ?? ''),
                    'code' => trim($major['code']),
                    'total_semesters' => !empty($major['total_semesters']) ? (int)$major['total_semesters'] : 8,
                ];
            }
        }
    }
    
    if ($college_id && !empty($majors_data)) {
        // التحقق من الصلاحية
        if (!$auth->belongsToCollege($college_id) && !$auth->hasRole('admin')) {
            $message = '<div class="alert alert-error">ليس لديك صلاحية لإضافة تخصصات في هذه الكلية</div>';
        } else {
            try {
                $db->getConnection()->beginTransaction();
                
                $success_count = 0;
                $error_count = 0;
                $duplicate_count = 0;
                $errors = [];
                
                foreach ($majors_data as $index => $major_data) {
                    try {
                        // التحقق من عدم وجود تخصص بنفس الرمز في نفس الكلية
                        $existing = $db->fetchOne(
                            "SELECT * FROM majors WHERE code = ? AND college_id = ?",
                            [$major_data['code'], $college_id]
                        );
                        
                        if ($existing) {
                            $duplicate_count++;
                            continue;
                        }
                        
                        // التأكد من عدم وجود سجل ب id=0
                        $zero_record = $db->fetchOne("SELECT id FROM majors WHERE id = 0");
                        if ($zero_record) {
                            $db->query("DELETE FROM majors WHERE id = 0");
                        }
                        
                        // إضافة التخصص
                        $db->query(
                            "INSERT INTO majors (college_id, name_ar, name_en, code, total_semesters) 
                             VALUES (?, ?, ?, ?, ?)",
                            [
                                $college_id, 
                                $major_data['name_ar'], 
                                $major_data['name_en'], 
                                $major_data['code'], 
                                $major_data['total_semesters']
                            ]
                        );
                        
                        // الحصول على ID المولّد تلقائياً
                        $major_id = $db->getConnection()->lastInsertId();
                        
                        // إذا كان ID = 0، إصلاح المشكلة
                        if ($major_id == 0 || $major_id === false || $major_id === '0') {
                            $db->query("DELETE FROM majors WHERE id = 0");
                            $max_id_result = $db->fetchOne("SELECT MAX(id) as max_id FROM majors WHERE id > 0");
                            $max_id = $max_id_result['max_id'] ?? 0;
                            $new_auto_increment = max($max_id + 1, 1);
                            $db->getConnection()->exec("ALTER TABLE majors MODIFY id INT(11) NOT NULL AUTO_INCREMENT");
                            $db->getConnection()->exec("ALTER TABLE majors AUTO_INCREMENT = " . (int)$new_auto_increment);
                            
                            $db->query(
                                "INSERT INTO majors (college_id, name_ar, name_en, code, total_semesters) 
                                 VALUES (?, ?, ?, ?, ?)",
                                [
                                    $college_id, 
                                    $major_data['name_ar'], 
                                    $major_data['name_en'], 
                                    $major_data['code'], 
                                    $major_data['total_semesters']
                                ]
                            );
                            $major_id = $db->getConnection()->lastInsertId();
                        }
                        
                        $success_count++;
                    } catch (PDOException $e) {
                        $error_count++;
                        $error_msg = $e->getMessage();
                        if (strpos($error_msg, 'Duplicate entry') !== false || strpos($error_msg, '1062') !== false) {
                            $duplicate_count++;
                        } else {
                            $errors[] = "التخصص " . $major_data['code'] . ": " . $error_msg;
                        }
                    }
                }
                
                $db->getConnection()->commit();
                
                // بناء رسالة النتيجة
                if ($success_count > 0) {
                    $message = '<div class="alert alert-success">✓ تم إضافة ' . $success_count . ' تخصص بنجاح</div>';
                }
                if ($duplicate_count > 0) {
                    $message .= '<div class="alert alert-info">⚠ ' . $duplicate_count . ' تخصص موجود مسبقاً (تم تخطيه)</div>';
                }
                if ($error_count > 0) {
                    $message .= '<div class="alert alert-warning">⚠ ' . $error_count . ' خطأ في الإضافة</div>';
                    if (count($errors) > 0 && count($errors) <= 10) {
                        $message .= '<div class="alert alert-info" style="margin-top:10px;"><small>' . implode('<br>', array_map('htmlspecialchars', $errors)) . '</small></div>';
                    }
                }
            } catch (Exception $e) {
                $db->getConnection()->rollBack();
                $message = '<div class="alert alert-error">خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>';
            }
        }
    } else {
        $message = '<div class="alert alert-error">يرجى ملء جميع الحقول المطلوبة</div>';
    }
}

// جلب الكليات
$selected_college_id = isset($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
if ($auth->hasRole('admin')) {
    $colleges = $db->fetchAll("SELECT * FROM colleges ORDER BY name_ar");
} else {
    $college_id = $_SESSION['college_id'] ?? 0;
    $colleges = $db->fetchAll("SELECT * FROM colleges WHERE id = ? ORDER BY name_ar", [$college_id]);
    $selected_college_id = $college_id;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إضافة تخصصات - دفعة واحدة</title>
    <?php include __DIR__ . '/includes/compatibility.php'; ?>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px 0;
        }
        
        .main-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .page-header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .page-header h1 {
            color: #667eea;
            margin: 0 0 10px 0;
            font-size: 32px;
            font-weight: 700;
        }
        
        .page-header p {
            color: #666;
            margin: 0;
            font-size: 16px;
        }
        
        .form-card {
            background: white;
            border-radius: 15px;
            padding: 35px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            color: #333;
            font-weight: 600;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 15px;
            transition: all 0.3s ease;
            background: #fafafa;
        }
        
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .majors-table-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            overflow-x: auto;
        }
        
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .table-header h3 {
            color: #667eea;
            margin: 0;
            font-size: 22px;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(17, 153, 142, 0.4);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .btn-add-row {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 10px 20px;
            font-size: 14px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        table thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        table th {
            padding: 15px;
            text-align: right;
            font-weight: 600;
            font-size: 14px;
        }
        
        table td {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        table tbody tr {
            transition: background 0.2s ease;
        }
        
        table tbody tr:hover {
            background: #f8f9ff;
        }
        
        table input, table select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            background: white;
        }
        
        table input:focus, table select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
        }
        
        .btn-remove {
            background: #dc3545;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
        }
        
        .btn-remove:hover {
            background: #c82333;
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 15px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .info-box {
            background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
            border-right: 4px solid #667eea;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
        }
        
        .info-box p {
            margin: 5px 0;
            color: #555;
        }
        
        .info-box strong {
            color: #667eea;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="main-container">
        <div class="page-header">
            <h1>📚 إضافة تخصصات - دفعة واحدة</h1>
            <p>أضف عدة تخصصات دفعة واحدة بسهولة وسرعة</p>
        </div>
        
        <?php echo $message; ?>
        
        <form method="POST" id="addMajorsForm">
            <input type="hidden" name="action" value="add_bulk">
            
            <div class="form-card">
                <div class="form-group">
                    <label>الكلية *</label>
                    <select name="college_id" id="college_id" required>
                        <option value="">-- اختر الكلية --</option>
                        <?php foreach ($colleges as $college): ?>
                            <option value="<?php echo $college['id']; ?>" <?php echo ($selected_college_id && $college['id'] == $selected_college_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($college['name_ar']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div class="majors-table-container">
                <div class="table-header">
                    <h3>📋 بيانات التخصصات</h3>
                    <button type="button" class="btn btn-add-row" onclick="addMajorRow()">
                        ➕ إضافة صف جديد
                    </button>
                </div>
                
                <div class="info-box">
                    <p><strong>💡 ملاحظات:</strong></p>
                    <p>• الحقول المطلوبة: اسم التخصص (عربي) ورمز التخصص</p>
                    <p>• يمكنك إضافة عدة صفوف وإزالة أي صف غير مطلوب</p>
                    <p>• التخصصات المكررة (بنفس الرمز في نفس الكلية) سيتم تخطيها تلقائياً</p>
                </div>
                
                <table id="majorsTable">
                    <thead>
                        <tr>
                            <th style="width: 80px;">#</th>
                            <th>اسم التخصص (عربي) *</th>
                            <th>اسم التخصص (إنجليزي)</th>
                            <th>رمز التخصص *</th>
                            <th>عدد الفصول الدراسية</th>
                            <th style="width: 100px;">إجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="majorsTableBody">
                        <tr>
                            <td>1</td>
                            <td><input type="text" name="majors[0][name_ar]" maxlength="80" required placeholder="حتى 80 حرف"></td>
                            <td><input type="text" name="majors[0][name_en]" maxlength="80" placeholder="Up to 80 characters"></td>
                            <td><input type="text" name="majors[0][code]" required></td>
                            <td><input type="number" name="majors[0][total_semesters]" value="8" min="1" max="16"></td>
                            <td><button type="button" class="btn-remove" onclick="removeRow(this)" disabled>🗑️</button></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="form-card" style="text-align: center; margin-top: 30px;">
                <button type="submit" class="btn btn-success" style="padding: 15px 40px; font-size: 18px;">
                    ✅ حفظ جميع التخصصات
                </button>
                <a href="majors.php" class="btn btn-secondary" style="margin-right: 15px;">
                    🔙 العودة
                </a>
            </div>
        </form>
    </div>
    
    <script>
        let rowCount = 1;
        
        function addMajorRow() {
            const tbody = document.getElementById('majorsTableBody');
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${rowCount + 1}</td>
                <td><input type="text" name="majors[${rowCount}][name_ar]" maxlength="80" required placeholder="حتى 80 حرف"></td>
                <td><input type="text" name="majors[${rowCount}][name_en]" maxlength="80" placeholder="Up to 80 characters"></td>
                <td><input type="text" name="majors[${rowCount}][code]" required></td>
                <td><input type="number" name="majors[${rowCount}][total_semesters]" value="8" min="1" max="16"></td>
                <td><button type="button" class="btn-remove" onclick="removeRow(this)">🗑️</button></td>
            `;
            tbody.appendChild(row);
            rowCount++;
            updateRowNumbers();
        }
        
        function removeRow(button) {
            const row = button.closest('tr');
            const tbody = document.getElementById('majorsTableBody');
            if (tbody.children.length > 1) {
                row.remove();
                updateRowNumbers();
            }
        }
        
        function updateRowNumbers() {
            const rows = document.querySelectorAll('#majorsTableBody tr');
            rows.forEach((row, index) => {
                row.querySelector('td:first-child').textContent = index + 1;
                if (rows.length === 1) {
                    row.querySelector('.btn-remove').disabled = true;
                } else {
                    row.querySelector('.btn-remove').disabled = false;
                }
            });
        }
    </script>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>
