<?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: committee_edit_student.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: committee_students.php");
        exit;
    }

    // Check access permissions
    if (!$canAll && $scopeCollege !== null && $studentData['college_id'] != $scopeCollege) {
        $_SESSION['error_message'] = "ليس لديك صلاحية لتعديل بيانات هذا الطالب";
        header("Location: committee_students.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;
    $interview_status = trim($_POST['interview_status'] ?? 'pending');
    $medically_fit = isset($_POST['medically_fit']) ? (int)$_POST['medically_fit'] : 2;
    $profile_completed = isset($_POST['profile_completed']) ? (int)$_POST['profile_completed'] : 0;
    $nationality = trim($_POST['nationality'] ?? '');
    $date_of_birth = trim($_POST['date_of_birth'] ?? '');
    $place_of_birth = trim($_POST['place_of_birth'] ?? '');
    $father_name = trim($_POST['father_name'] ?? '');
    $mother_name = trim($_POST['mother_name'] ?? '');
    $occupation = trim($_POST['occupation'] ?? '');
    
    // Get financial fields
    $registration_fees = isset($_POST['registration_fees']) ? (float)$_POST['registration_fees'] : 0.00;
    $program_fees = isset($_POST['program_fees']) ? (float)$_POST['program_fees'] : 0.00;
    $insurance_fees = isset($_POST['insurance_fees']) ? (float)$_POST['insurance_fees'] : 0.00;

    // Convert empty strings to NULL for database
    $email = empty($email) ? null : $email;
    $phone_number = empty($phone_number) ? null : $phone_number;
    $phone_number2 = empty($phone_number2) ? null : $phone_number2;
    $nationality = empty($nationality) ? null : $nationality;
    $date_of_birth = empty($date_of_birth) ? null : $date_of_birth;
    $place_of_birth = empty($place_of_birth) ? null : $place_of_birth;
    $father_name = empty($father_name) ? null : $father_name;
    $mother_name = empty($mother_name) ? null : $mother_name;
    $occupation = empty($occupation) ? null : $occupation;

    try {
        // Prepare the SQL query with all fields including financial ones
        $sql = "UPDATE students SET 
                student_name = ?, 
                student_name_eng = ?, 
                email = ?, 
                phone_number = ?, 
                phone_number2 = ?, 
                college_id = ?, 
                program_id = ?, 
                section_id = ?, 
                batch_id = ?, 
                gender = ?, 
                interview_status = ?, 
                medically_fit = ?, 
                profile_completed = ?, 
                nationality = ?, 
                date_of_birth = ?, 
                place_of_birth = ?, 
                father_name = ?, 
                mother_name = ?, 
                occupation = ?, 
                registration_fees = ?, 
                program_fees = ?,    
                insurance_fees = ?     
                WHERE student_id = ?";

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

        // Build type string dynamically to avoid counting errors
        $types = '';
        $types .= 'sssss';      // 5 strings: student_name to phone_number2
        $types .= 'iiii';       // 4 integers: college_id to batch_id
        $types .= 'i';          // 1 integer: gender
        $types .= 's';          // 1 string: interview_status
        $types .= 'ii';         // 2 integers: medically_fit, profile_completed
        $types .= 'ssssss';     // 6 strings: nationality to occupation
        $types .= 'ddd';        // 3 doubles: registration_fees to insurance_fees
        $types .= 's';          // 1 string: student_id (WHERE clause)
        
        // Verify we have 23 characters: 5+4+1+1+2+6+3+1 = 23
        if (strlen($types) !== 23) {
            throw new Exception("خطأ في بناء نوع البيانات. المتوقع 23 حرفاً، الحالي: " . strlen($types));
        }

        // Parameters array - MUST match the order in the SQL query (23 parameters)
        $params = [
            $student_name,      // 1 - s (string)
            $student_name_eng,  // 2 - s (string)
            $email,             // 3 - s (string or null)
            $phone_number,      // 4 - s (string or null)
            $phone_number2,     // 5 - s (string or null)
            $college_id,        // 6 - i (integer or null)
            $program_id,        // 7 - i (integer or null)
            $section_id,        // 8 - i (integer or null)
            $batch_id,          // 9 - i (integer or null)
            $gender,            // 10 - i (integer)
            $interview_status,  // 11 - s (string)
            $medically_fit,     // 12 - i (integer)
            $profile_completed, // 13 - i (integer)
            $nationality,       // 14 - s (string or null)
            $date_of_birth,     // 15 - s (string or null)
            $place_of_birth,    // 16 - s (string or null)
            $father_name,       // 17 - s (string or null)
            $mother_name,       // 18 - s (string or null)
            $occupation,        // 19 - s (string or null)
            $registration_fees, // 20 - d (double)
            $program_fees,      // 21 - d (double)
            $insurance_fees,    // 22 - d (double)
            $student_id         // 23 - s (string)
        ];

        // Debug: Check counts
        $placeholderCount = substr_count($sql, '?');
        $typeCount = strlen($types);
        $paramCount = count($params);
        
        error_log("==== DEBUG INFO ====");
        error_log("SQL Placeholders: $placeholderCount");
        error_log("Type string: $types (Length: $typeCount)");
        error_log("Parameters count: $paramCount");
        
        if ($placeholderCount !== $typeCount || $placeholderCount !== $paramCount) {
            error_log("MISMATCH DETECTED!");
            error_log("SQL: " . $sql);
            error_log("Parameters types: " . $types);
            error_log("Parameters array: " . print_r($params, true));
            throw new Exception("تعارض في عدد المعاملات! الأماكن: $placeholderCount, الأنواع: $typeCount, المعاملات: $paramCount");
        }

        // Bind parameters
        error_log("Attempting to bind parameters with type string: $types");
        $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: committee_edit_student.php?student_id=" . urlencode($student_id));
    exit;
    
} else {
    // Not a POST request - redirect to students list
    header("Location: committee_students.php");
    exit;
}
?>