<?php
// committee_update_student.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = $_POST['student_id'] ?? '';
    
    if (empty($student_id)) {
        $_SESSION['error_message'] = "رقم الطالب مطلوب";
        header("Location: edit_student_admin.php?student_id=" . $student_id);
        exit;
    }

    // Check committee permissions
    $committeeId = (int)($_SESSION['committee_id'] ?? 0);
    $canAll = (bool)($_SESSION['committee_can_all'] ?? false);
    $scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

    // Verify committee has access to this student
    $accessCheck = $mysqli1->prepare("SELECT college_id FROM students WHERE student_id = ?");
    $accessCheck->bind_param("s", $student_id);
    $accessCheck->execute();
    $studentData = $accessCheck->get_result()->fetch_assoc();
    $accessCheck->close();

    if (!$studentData) {
        $_SESSION['error_message'] = "الطالب غير موجود";
        header("Location: admin_dashboard.php");
        exit;
    }

    // Check access permissions
    if (!$canAll && $scopeCollege !== null && $studentData['college_id'] != $scopeCollege) {
        $_SESSION['error_message'] = "ليس لديك صلاحية لتعديل بيانات هذا الطالب";
        header("Location: admin_dashboard.php");
        exit;
    }

    // Collect all form data with proper sanitization
    $student_name = trim($_POST['student_name'] ?? '');
    $student_name_eng = trim($_POST['student_name_eng'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone_number = trim($_POST['phone_number'] ?? '');
    $phone_number2 = trim($_POST['phone_number2'] ?? '');
    $college_id = !empty($_POST['college_id']) ? (int)$_POST['college_id'] : null;
    $program_id = !empty($_POST['program_id']) ? (int)$_POST['program_id'] : null;
    $section_id = !empty($_POST['section_id']) ? (int)$_POST['section_id'] : null;
    $batch_id = !empty($_POST['batch_id']) ? (int)$_POST['batch_id'] : null;
    $gender = isset($_POST['gender']) ? (int)$_POST['gender'] : 0;
    $admission_id = !empty($_POST['admission_id']) ? (int)$_POST['admission_id'] : null; // Added admissions field

    // Convert empty strings to NULL for database
    $student_name_eng = empty($student_name_eng) ? null : $student_name_eng;
    $email = empty($email) ? null : $email;
    $phone_number = empty($phone_number) ? null : $phone_number;
    $phone_number2 = empty($phone_number2) ? null : $phone_number2;

    // Validate required fields
    if (empty($student_name)) {
        $_SESSION['error_message'] = "الاسم بالعربية مطلوب";
        header("Location: edit_student_admin.php?student_id=" . urlencode($student_id));
        exit;
    }

    if (empty($college_id)) {
        $_SESSION['error_message'] = "الكلية مطلوبة";
        header("Location: edit_student_admin.php?student_id=" . urlencode($student_id));
        exit;
    }

    if (empty($program_id)) {
        $_SESSION['error_message'] = "البرنامج مطلوب";
        header("Location: edit_student_admin.php?student_id=" . urlencode($student_id));
        exit;
    }

    if (empty($section_id)) {
        $_SESSION['error_message'] = "القسم مطلوب";
        header("Location: edit_student_admin.php?student_id=" . urlencode($student_id));
        exit;
    }

    if (empty($batch_id)) {
        $_SESSION['error_message'] = "الدفعة مطلوبة";
        header("Location: edit_student_admin.php?student_id=" . urlencode($student_id));
        exit;
    }

    if (empty($admission_id)) {
        $_SESSION['error_message'] = "نوع القبول مطلوب";
        header("Location: edit_student_admin.php?student_id=" . urlencode($student_id));
        exit;
    }

    try {
        // Prepare the SQL query with only fields that exist in the form
        $sql = "UPDATE students SET 
                student_name = ?, 
                student_name_eng = ?, 
                email = ?, 
                phone_number = ?, 
                phone_number2 = ?, 
                college_id = ?, 
                program_id = ?, 
                section_id = ?, 
                batch_id = ?, 
                gender = ?, 
                admission_id = ?, 
                updated_at = NOW() 
                WHERE student_id = ?";

        $stmt = $mysqli1->prepare($sql);
        
        if (!$stmt) {
            throw new Exception("خطأ في إعداد الاستعلام: " . $mysqli1->error);
        }

        // Define types and parameters - 12 parameters total (11 fields + 1 WHERE)
        // s = string, i = integer
        $types = 'sssssiiiiiss';
        
        $params = [
            $student_name,      // 1 - s (string)
            $student_name_eng,  // 2 - s (string)
            $email,             // 3 - s (string)
            $phone_number,      // 4 - s (string)
            $phone_number2,     // 5 - s (string)
            $college_id,        // 6 - i (integer)
            $program_id,        // 7 - i (integer)
            $section_id,        // 8 - i (integer)
            $batch_id,          // 9 - i (integer)
            $gender,            // 10 - i (integer)
            $admission_id,      // 11 - i (integer) - Added admission_id
            $student_id         // 12 - s (string - WHERE condition)
        ];

        // Debug: Check counts
        $placeholderCount = substr_count($sql, '?');
        $typeCount = strlen($types);
        $paramCount = count($params);
        
        error_log("Debug - Placeholders: $placeholderCount, Types: $typeCount, Params: $paramCount");
        
        if ($placeholderCount !== $typeCount || $placeholderCount !== $paramCount) {
            throw new Exception("تعارض في عدد المعاملات! الأماكن: $placeholderCount, الأنواع: $typeCount, المعاملات: $paramCount");
        }

        // Bind parameters
        $bindResult = $stmt->bind_param($types, ...$params);
        if (!$bindResult) {
            throw new Exception("خطأ في ربط المعاملات: " . $stmt->error);
        }
        
        // Execute the query
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                $_SESSION['success_message'] = "تم تحديث بيانات الطالب بنجاح";
            } else {
                $_SESSION['info_message'] = "لم يتم تغيير أي بيانات";
            }
        } else {
            throw new Exception("خطأ في تنفيذ الاستعلام: " . $stmt->error);
        }
        
        $stmt->close();
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = "خطأ في تحديث البيانات: " . $e->getMessage();
        error_log("Update error for student $student_id: " . $e->getMessage());
    }

    header("Location: edit_student_admin.php?student_id=" . urlencode($student_id));
    exit;
    
} else {
    // Not a POST request - redirect to students list
    header("Location: admin_dashboard.php");
    exit;
}
?>