<?php
// committee_update_registration.php
require 'db.php';
require 'helpers.php';
require_committee();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("الوصول غير مسموح");
}

$registrationId = (int)$_POST['registration_id'];
$studentId = $_POST['student_id'] ?? '';
$start = $_POST['start'] ?? '';
$end = $_POST['end'] ?? '';
$paymentAmount = (float)($_POST['payment_amount'] ?? 0);
$paymentReference = $_POST['payment_reference'] ?? '';
$isPaid = (int)($_POST['is_paid'] ?? 0);
$semesterId = (int)($_POST['semester_id'] ?? 0);
$notes = $_POST['notes'] ?? '';

if (empty($registrationId) || empty($studentId) || empty($start) || empty($end)) {
    $_SESSION['error_message'] = 'بيانات غير مكتملة';
    header("Location: committee_student_profile.php?student_id=" . urlencode($studentId));
    exit;
}

// التحقق من وجود التسجيل
$checkStmt = $mysqli1->prepare("SELECT id FROM registrations WHERE id = ? AND deleted_at IS NULL");
$checkStmt->bind_param("i", $registrationId);
$checkStmt->execute();
$checkStmt->store_result();

if ($checkStmt->num_rows == 0) {
    $_SESSION['error_message'] = 'التسجيل غير موجود';
    header("Location: committee_student_profile.php?student_id=" . urlencode($studentId));
    exit;
}

// تحديث بيانات التسجيل
$updateStmt = $mysqli1->prepare("
    UPDATE registrations 
    SET 
        start = ?,
        end = ?,
        payment_amount = ?,
        payment_reference = ?,
        is_paid = ?,
        semester_id = ?,
        notes = ?,
        updated_at = NOW()
    WHERE id = ?
");

$updateStmt->bind_param(
    "ssdsiisi",
    $start,
    $end,
    $paymentAmount,
    $paymentReference,
    $isPaid,
    $semesterId,
    $notes,
    $registrationId
);

if ($updateStmt->execute()) {
    $_SESSION['success_message'] = 'تم تحديث بيانات التسجيل بنجاح';
} else {
    $_SESSION['error_message'] = 'حدث خطأ أثناء تحديث البيانات';
}

$updateStmt->close();

header("Location: committee_student_profile.php?student_id=" . urlencode($studentId));
exit;
?>