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

$committeeId   = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll        = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege  = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: Add-student.php');
    exit();
}

// Check if committee has permission to add students
if (!$canAll && $scopeCollege === null) {
    $_SESSION['error_message'] = "ليس لديك صلاحية لإضافة طلاب";
    header('Location: Add-student.php');
    exit();
}

// Collect and sanitize data
$student_id = trim($_POST['student_id'] ?? '');
$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 = isset($_POST['college_id']) && $_POST['college_id'] !== '' ? trim($_POST['college_id']) : null;
$program_id = isset($_POST['program_id']) && $_POST['program_id'] !== '' ? trim($_POST['program_id']) : null;
$section_id = isset($_POST['section_id']) && $_POST['section_id'] !== '' ? trim($_POST['section_id']) : null;
$batch_id = isset($_POST['batch_id']) && $_POST['batch_id'] !== '' ? trim($_POST['batch_id']) : null;
$gender = isset($_POST['gender']) ? (int)$_POST['gender'] : 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'] ?? '');
$guardian_name = trim($_POST['guardian_name'] ?? '');
$guardian_phone_number = trim($_POST['guardian_phone_number'] ?? '');
$guardian_address = trim($_POST['guardian_address'] ?? '');
$home_address = trim($_POST['home_address'] ?? '');
$interview_status = trim($_POST['interview_status'] ?? 'pending');
$medically_fit = isset($_POST['medically_fit']) && $_POST['medically_fit'] !== '' ? (int)$_POST['medically_fit'] : null;
$profile_completed = isset($_POST['profile_completed']) ? (int)$_POST['profile_completed'] : 0;
$notes = trim($_POST['notes'] ?? '');

// Financial fields
$program_fees = isset($_POST['program_fees']) && $_POST['program_fees'] !== '' ? (float)$_POST['program_fees'] : null;
$registration_fees = isset($_POST['registration_fees']) && $_POST['registration_fees'] !== '' ? (float)$_POST['registration_fees'] : 0.00;
$insurance_fees = isset($_POST['insurance_fees']) && $_POST['insurance_fees'] !== '' ? (float)$_POST['insurance_fees'] : 0;
$discount = isset($_POST['discount']) && $_POST['discount'] !== '' ? (float)$_POST['discount'] : 0;

// Additional fields
$admission_id = trim($_POST['admission_id'] ?? '');
$addmission_type = trim($_POST['addmission_type'] ?? '');
$certificate_type = trim($_POST['certificate_type'] ?? '');

// Validation - Only student_id is required
if (empty($student_id)) {
    $_SESSION['error_message'] = "رقم الطالب مطلوب!";
    header('Location: Add-student.php');
    exit();
}

// Check if student ID already exists
$check_stmt = $mysqli1->prepare("SELECT id FROM students WHERE student_id = ?");
$check_stmt->bind_param("s", $student_id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows > 0) {
    $_SESSION['error_message'] = "رقم الطالب هذا مسجل مسبقاً!";
    header('Location: Add-student.php');
    exit();
}

// If committee has restricted access, verify they're adding to their college
if (!$canAll && $scopeCollege !== null && $college_id != $scopeCollege) {
    $_SESSION['error_message'] = "ليس لديك صلاحية لإضافة طلاب في هذه الكلية";
    header('Location: Add-student.php');
    exit();
}

// Debug: Show what we're getting
error_log("=== DEBUG INFORMATION ===");
error_log("Student ID: " . $student_id);
error_log("Student Name: " . $student_name);
error_log("College ID: " . ($college_id ?? 'NULL'));

// Prepare insert statement - FIXED VERSION
$stmt = $mysqli1->prepare("
    INSERT INTO students (
        student_id, student_name, student_name_eng, email, phone_number, phone_number2,
        college_id, program_id, section_id, batch_id, gender, nationality,
        date_of_birth, place_of_birth, father_name, mother_name, occupation,
        guardian_name, guardian_phone_number, guardian_address, home_address,
        interview_status, medically_fit, profile_completed, notes,
        program_fees, registration_fees, insurance_fees, discount,
        admission_id, addmission_type, certificate_type,
        created_at, updated_at
    ) VALUES (
        ?, ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, ?, 
        ?, ?, ?, ?, 
        ?, ?, ?, ?, 
        ?, ?, ?, ?, 
        ?, ?, ?, 
        NOW(), NOW()
    )
");

if (!$stmt) {
    error_log("Prepare failed: " . $mysqli1->error);
    $_SESSION['error_message'] = "خطأ في إعداد الاستعلام: " . $mysqli1->error;
    header('Location: Add-student.php');
    exit();
}

// Prepare parameters - COUNT THEM CAREFULLY
// We have 31 parameters + 2 timestamps (NOW()) = 33 total placeholders
// But we're binding 31 parameters (the timestamps are handled by MySQL)

$params = [];
$types = "";

// Parameter 1-6
$params[] = $student_id;
$params[] = $student_name;
$params[] = $student_name_eng;
$params[] = $email;
$params[] = $phone_number;
$params[] = $phone_number2;
$types .= "ssssss";

// Parameter 7-10 (nullable strings)
$params[] = $college_id;
$params[] = $program_id;
$params[] = $section_id;
$params[] = $batch_id;
$types .= "ssss";

// Parameter 11-12
$params[] = $gender;
$params[] = $nationality;
$types .= "is";

// Parameter 13-17
$params[] = $date_of_birth !== '' ? $date_of_birth : null;
$params[] = $place_of_birth;
$params[] = $father_name;
$params[] = $mother_name;
$params[] = $occupation;
$types .= "sssss";

// Parameter 18-21
$params[] = $guardian_name;
$params[] = $guardian_phone_number;
$params[] = $guardian_address;
$params[] = $home_address;
$types .= "ssss";

// Parameter 22-25
$params[] = $interview_status;
$params[] = $medically_fit;
$params[] = $profile_completed;
$params[] = $notes;
$types .= "siis";

// Parameter 26-29 (floats/doubles)
$params[] = $program_fees;
$params[] = $registration_fees;
$params[] = $insurance_fees;
$params[] = $discount;
$types .= "dddd";

// Parameter 30-32
$params[] = $admission_id;
$params[] = $addmission_type;
$params[] = $certificate_type;
$types .= "sss";

// Debug: Count types and params
error_log("Type string length: " . strlen($types));
error_log("Number of params: " . count($params));
error_log("Type string: " . $types);
error_log("Params: " . print_r($params, true));

// Check if counts match
if (strlen($types) !== count($params)) {
    error_log("ERROR: Type string length (" . strlen($types) . ") doesn't match param count (" . count($params) . ")");
    $_SESSION['error_message'] = "خطأ في عدد المعاملات: " . strlen($types) . " أنواع vs " . count($params) . " معاملات";
    header('Location: Add-student.php');
    exit();
}

// Bind parameters
if (!$stmt->bind_param($types, ...$params)) {
    error_log("Bind param failed: " . $stmt->error);
    $_SESSION['error_message'] = "خطأ في ربط المعاملات: " . $stmt->error;
    header('Location: Add-student.php');
    exit();
}

if ($stmt->execute()) {
    $new_student_id = $student_id;
    
    // Create a log entry if committee_logs table exists
    try {
        $log_stmt = $mysqli1->prepare("
            INSERT INTO committee_logs 
            (committee_id, action_type, target_id, details, created_at)
            VALUES (?, 'add_student', ?, ?, NOW())
        ");
        
        if ($log_stmt) {
            $log_details = "تم إضافة طالب جديد: " . ($student_name ?: 'بدون اسم') . " ({$student_id})";
            $log_stmt->bind_param("iss", $committeeId, $new_student_id, $log_details);
            $log_stmt->execute();
        }
    } catch (Exception $e) {
        // Log table might not exist, ignore this error
        error_log("Could not create log entry: " . $e->getMessage());
    }
    
    $_SESSION['success_message'] = "تم إضافة الطالب بنجاح!";
    header("Location: committee_student_profile.php?student_id=" . urlencode($new_student_id));
    exit();
} else {
    error_log("Execute failed: " . $stmt->error);
    $_SESSION['error_message'] = "حدث خطأ أثناء إضافة الطالب: " . $stmt->error;
    header('Location: Add-student.php');
    exit();
}