<?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') && !$auth->hasRole('registrar'))) {
    header('Location: index.php');
    exit;
}

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

// فحص وإصلاح AUTO_INCREMENT إذا لزم الأمر
try {
    $zero_record = $db->fetchOne("SELECT id FROM students WHERE id = 0");
    if ($zero_record) {
        $db->query("DELETE FROM students WHERE id = 0");
    }
    
    $columns = $db->fetchAll("SHOW COLUMNS FROM students 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 students WHERE id > 0");
        $max_id = $max_id_result['max_id'] ?? 0;
        $new_auto_increment = max($max_id + 1, 1);
        $db->getConnection()->exec("ALTER TABLE students MODIFY id INT(11) NOT NULL AUTO_INCREMENT");
        $db->getConnection()->exec("ALTER TABLE students AUTO_INCREMENT = " . (int)$new_auto_increment);
    }
} catch (PDOException $e) {
    error_log("Auto-increment check 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 (isset($_GET['action']) && $_GET['action'] == 'get_semesters' && isset($_GET['major_id'])) {
    header('Content-Type: application/json');
    $major_id = (int)$_GET['major_id'];
    $semesters = $db->fetchAll(
        "SELECT id, semester_number, academic_year FROM semesters WHERE major_id = ? ORDER BY academic_year DESC, semester_number DESC",
        [$major_id]
    );
    echo json_encode($semesters);
    exit;
}

// معالجة الإضافة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_bulk') {
    $college_id = (int)($_POST['college_id'] ?? 0);
    $major_id = (int)($_POST['major_id'] ?? 0);
    $semester_id = (int)($_POST['semester_id'] ?? 0);
    $academic_year = trim($_POST['academic_year'] ?? '');
    
    // جلب بيانات الطلاب من النموذج
    $students_data = [];
    if (isset($_POST['students']) && is_array($_POST['students'])) {
        foreach ($_POST['students'] as $student) {
            if (!empty($student['student_number']) && !empty($student['full_name_ar'])) {
                $students_data[] = [
                    'student_number' => trim($student['student_number']),
                    'full_name_ar' => trim($student['full_name_ar']),
                    'full_name_en' => trim($student['full_name_en'] ?? ''),
                    'national_id' => trim($student['national_id'] ?? ''),
                    'email' => trim($student['email'] ?? ''),
                    'phone' => trim($student['phone'] ?? ''),
                ];
            }
        }
    }
    
    if ($college_id && $major_id && !empty($students_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 ($students_data as $index => $student_data) {
                    try {
                        // التحقق من عدم وجود طالب بنفس الرقم الجامعي
                        $existing = $db->fetchOne(
                            "SELECT * FROM students WHERE student_number = ?",
                            [$student_data['student_number']]
                        );
                        
                        if ($existing) {
                            $duplicate_count++;
                            continue;
                        }
                        
                        // التحقق من الرقم الوطني إذا كان موجوداً
                        if (!empty($student_data['national_id'])) {
                            $existing_nid = $db->fetchOne(
                                "SELECT * FROM students WHERE national_id = ? AND national_id != ''",
                                [$student_data['national_id']]
                            );
                            if ($existing_nid) {
                                $duplicate_count++;
                                continue;
                            }
                        }
                        
                        // التأكد من عدم وجود سجل ب id=0
                        $zero_record = $db->fetchOne("SELECT id FROM students WHERE id = 0");
                        if ($zero_record) {
                            $db->query("DELETE FROM students WHERE id = 0");
                        }
                        
                        // إنشاء مستخدم للطالب
                        $username = 'STU' . $student_data['student_number'];
                        $password = password_hash($student_data['student_number'], PASSWORD_DEFAULT);
                        
                        $db->query(
                            "INSERT INTO users (college_id, username, password, full_name_ar, full_name_en, email, role) 
                             VALUES (?, ?, ?, ?, ?, ?, 'student')",
                            [$college_id, $username, $password, $student_data['full_name_ar'], $student_data['full_name_en'], $student_data['email']]
                        );
                        
                        $user_id = $db->getConnection()->lastInsertId();
                        
                        // إضافة الطالب
                        $db->query(
                            "INSERT INTO students (college_id, major_id, student_number, national_id, full_name_ar, full_name_en, email, phone, enrollment_date, user_id, status) 
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')",
                            [
                                $college_id, 
                                $major_id, 
                                $student_data['student_number'], 
                                $student_data['national_id'], 
                                $student_data['full_name_ar'], 
                                $student_data['full_name_en'], 
                                $student_data['email'], 
                                $student_data['phone'], 
                                date('Y-m-d'),
                                $user_id
                            ]
                        );
                        
                        // الحصول على ID المولّد تلقائياً
                        $student_id = $db->getConnection()->lastInsertId();
                        
                        // إذا كان ID = 0، إصلاح المشكلة
                        if ($student_id == 0 || $student_id === false || $student_id === '0') {
                            $db->query("DELETE FROM students WHERE id = 0");
                            $max_id_result = $db->fetchOne("SELECT MAX(id) as max_id FROM students WHERE id > 0");
                            $max_id = $max_id_result['max_id'] ?? 0;
                            $new_auto_increment = max($max_id + 1, 1);
                            $db->getConnection()->exec("ALTER TABLE students MODIFY id INT(11) NOT NULL AUTO_INCREMENT");
                            $db->getConnection()->exec("ALTER TABLE students AUTO_INCREMENT = " . (int)$new_auto_increment);
                            
                            $db->query(
                                "INSERT INTO students (college_id, major_id, student_number, national_id, full_name_ar, full_name_en, email, phone, enrollment_date, user_id, status) 
                                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')",
                                [
                                    $college_id, 
                                    $major_id, 
                                    $student_data['student_number'], 
                                    $student_data['national_id'], 
                                    $student_data['full_name_ar'], 
                                    $student_data['full_name_en'], 
                                    $student_data['email'], 
                                    $student_data['phone'], 
                                    date('Y-m-d'),
                                    $user_id
                                ]
                            );
                            $student_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[] = "الطالب " . $student_data['student_number'] . ": " . $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>';
    }
}

// جلب الكليات
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]);
}
?>
<!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-section {
            margin-bottom: 30px;
        }
        
        .form-section-title {
            color: #667eea;
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 0;
        }
        
        .form-group label {
            display: block;
            color: #333;
            font-weight: 600;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .form-group input,
        .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 input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .students-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-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .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-danger {
            background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
            color: white;
        }
        
        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(235, 51, 73, 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 {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            background: white;
        }
        
        table input: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="addStudentsForm">
            <input type="hidden" name="action" value="add_bulk">
            
            <div class="form-card">
                <div class="form-section">
                    <h3 class="form-section-title">📋 معلومات الكلية والتخصص</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>الكلية *</label>
                            <select name="college_id" id="college_id" required onchange="loadMajors()">
                                <option value="">-- اختر الكلية --</option>
                                <?php foreach ($colleges as $college): ?>
                                    <option value="<?php echo $college['id']; ?>"><?php echo htmlspecialchars($college['name_ar']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>التخصص *</label>
                            <select name="major_id" id="major_id" required disabled onchange="loadSemesters()">
                                <option value="">-- اختر الكلية أولاً --</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>الفصل الدراسي</label>
                            <select name="semester_id" id="semester_id" disabled>
                                <option value="">-- اختر التخصص أولاً --</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>السنة الدراسية</label>
                            <input type="text" name="academic_year" id="academic_year" placeholder="مثال: 2024-2025">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="students-table-container">
                <div class="table-header">
                    <h3>👥 بيانات الطلاب</h3>
                    <button type="button" class="btn btn-add-row" onclick="addStudentRow()">
                        ➕ إضافة صف جديد
                    </button>
                </div>
                
                <div class="info-box">
                    <p><strong>💡 ملاحظات:</strong></p>
                    <p>• الحقول المطلوبة: الرقم الجامعي والاسم الكامل (عربي)</p>
                    <p>• يمكنك إضافة عدة صفوف وإزالة أي صف غير مطلوب</p>
                    <p>• الطلاب المكررون (بنفس الرقم الجامعي) سيتم تخطيهم تلقائياً</p>
                </div>
                
                <table id="studentsTable">
                    <thead>
                        <tr>
                            <th style="width: 80px;">#</th>
                            <th>الرقم الجامعي *</th>
                            <th>الاسم الكامل (عربي) *</th>
                            <th>الاسم الكامل (إنجليزي)</th>
                            <th>الرقم الوطني</th>
                            <th>البريد الإلكتروني</th>
                            <th>الهاتف</th>
                            <th style="width: 100px;">إجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="studentsTableBody">
                        <tr>
                            <td>1</td>
                            <td><input type="text" name="students[0][student_number]" required></td>
                            <td><input type="text" name="students[0][full_name_ar]" required></td>
                            <td><input type="text" name="students[0][full_name_en]"></td>
                            <td><input type="text" name="students[0][national_id]"></td>
                            <td><input type="email" name="students[0][email]"></td>
                            <td><input type="text" name="students[0][phone]"></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="students.php" class="btn btn-secondary" style="margin-right: 15px;">
                    🔙 العودة
                </a>
            </div>
        </form>
    </div>
    
    <script>
        let rowCount = 1;
        
        function addStudentRow() {
            const tbody = document.getElementById('studentsTableBody');
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${rowCount + 1}</td>
                <td><input type="text" name="students[${rowCount}][student_number]" required></td>
                <td><input type="text" name="students[${rowCount}][full_name_ar]" required></td>
                <td><input type="text" name="students[${rowCount}][full_name_en]"></td>
                <td><input type="text" name="students[${rowCount}][national_id]"></td>
                <td><input type="email" name="students[${rowCount}][email]"></td>
                <td><input type="text" name="students[${rowCount}][phone]"></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('studentsTableBody');
            if (tbody.children.length > 1) {
                row.remove();
                updateRowNumbers();
            }
        }
        
        function updateRowNumbers() {
            const rows = document.querySelectorAll('#studentsTableBody 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;
                }
            });
        }
        
        function loadMajors() {
            const collegeId = document.getElementById('college_id').value;
            const majorSelect = document.getElementById('major_id');
            const semesterSelect = document.getElementById('semester_id');
            
            majorSelect.innerHTML = '<option value="">-- اختر الكلية أولاً --</option>';
            majorSelect.disabled = !collegeId;
            semesterSelect.innerHTML = '<option value="">-- اختر التخصص أولاً --</option>';
            semesterSelect.disabled = true;
            
            if (!collegeId) return;
            
            fetch(`add_students_bulk.php?action=get_majors&college_id=${collegeId}`)
                .then(response => response.json())
                .then(data => {
                    data.forEach(major => {
                        const option = document.createElement('option');
                        option.value = major.id;
                        option.textContent = major.name_ar;
                        majorSelect.appendChild(option);
                    });
                    majorSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Error loading majors:', error);
                });
        }
        
        function loadSemesters() {
            const majorId = document.getElementById('major_id').value;
            const semesterSelect = document.getElementById('semester_id');
            
            semesterSelect.innerHTML = '<option value="">-- اختر التخصص أولاً --</option>';
            semesterSelect.disabled = !majorId;
            
            if (!majorId) return;
            
            fetch(`add_students_bulk.php?action=get_semesters&major_id=${majorId}`)
                .then(response => response.json())
                .then(data => {
                    data.forEach(semester => {
                        const option = document.createElement('option');
                        option.value = semester.id;
                        option.textContent = `فصل ${semester.semester_number} - ${semester.academic_year}`;
                        semesterSelect.appendChild(option);
                    });
                    semesterSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Error loading semesters:', error);
                });
        }
        
        // تحميل التخصصات عند فتح الصفحة إذا كانت الكلية محددة
        document.addEventListener('DOMContentLoaded', function() {
            <?php if (!$auth->hasRole('admin') && isset($_SESSION['college_id'])): ?>
            const collegeSelect = document.getElementById('college_id');
            if (collegeSelect && collegeSelect.value) {
                loadMajors();
            }
            <?php endif; ?>
        });
    </script>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>
