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

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

$original_registration_id = (int)($_POST['original_registration_id'] ?? 0);
$student_id = $_POST['student_id'] ?? '';
$installment_count = (int)($_POST['installment_count'] ?? 0);
$semester_id = (int)($_POST['semester_id'] ?? 0);
$registration_fees = (int)($_POST['registration_fees'] ?? 0);
$insurance_fees = (int)($_POST['insurance_fees'] ?? 0);

if (empty($original_registration_id) || empty($student_id) || empty($installment_count) || empty($semester_id)) {
    $_SESSION['error_message'] = "بيانات ناقصة. يرجى التأكد من ملء جميع الحقول المطلوبة.";
    header('Location: create_installments.php?registration_id=' . $original_registration_id . '&student_id=' . urlencode($student_id));
    exit;
}

// Get original registration data
$stmt = $mysqli1->prepare("SELECT * FROM registrations WHERE id = ? AND student_id = ? AND deleted_at IS NULL");
$stmt->bind_param("is", $original_registration_id, $student_id);
$stmt->execute();
$original_registration = $stmt->get_result()->fetch_assoc();

if (!$original_registration) {
    $_SESSION['error_message'] = "لم يتم العثور على التسجيل الأصلي أو تم حذفه مسبقاً.";
    header('Location: student_profile_admin.php?student_id=' . urlencode($student_id));
    exit;
}

// Get student data
$student_stmt = $mysqli1->prepare("SELECT student_name, phone_number FROM students WHERE student_id = ?");
$student_stmt->bind_param("s", $student_id);
$student_stmt->execute();
$student = $student_stmt->get_result()->fetch_assoc();

if (!$student) {
    $_SESSION['error_message'] = "لم يتم العثور على بيانات الطالب.";
    header('Location: admin_dashboard.php');
    exit;
}

// Begin transaction
$mysqli1->begin_transaction();

try {
    // Mark original registration as deleted
    $delete_stmt = $mysqli1->prepare("UPDATE registrations SET deleted_at = NOW() WHERE id = ?");
    $delete_stmt->bind_param("i", $original_registration_id);
    
    if (!$delete_stmt->execute()) {
        throw new Exception("فشل في تحديث التسجيل الأصلي: " . $delete_stmt->error);
    }
    $delete_stmt->close();
    
    // Process each installment
    $installments = $_POST['installments'] ?? [];
    $total_amount = 0;
    $created_installments = 0;
    
    foreach ($installments as $index => $installment) {
        $amount = (int)($installment['amount'] ?? 0);
        $reference = $mysqli1->real_escape_string($installment['reference'] ?? '');
        $start_date = $mysqli1->real_escape_string($installment['start_date'] ?? '');
        $end_date = $mysqli1->real_escape_string($installment['end_date'] ?? '');
        
        if (empty($amount) || empty($reference) || empty($start_date) || empty($end_date)) {
            throw new Exception("بيانات ناقصة للقسط " . ($index + 1));
        }
        
        // Validate dates
        if (strtotime($start_date) >= strtotime($end_date)) {
            throw new Exception("تاريخ البدء يجب أن يكون قبل تاريخ الانتهاء للقسط " . ($index + 1));
        }
        
        // Create installment registration - CORRECTED VERSION
        // Check if student_name column exists in registrations table
        $check_column = $mysqli1->query("SHOW COLUMNS FROM registrations LIKE 'student_name'");
        $student_name_exists = $check_column->num_rows > 0;
        
        if ($student_name_exists) {
            // If student_name column exists, include it in the insert
            $insert_stmt = $mysqli1->prepare("
                INSERT INTO registrations (
                    student_id, student_name, semester_id, payment_amount, payment_reference, 
                    registration_fees, insurance_fees, study_fees, is_paid,
                    start, end, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");
            
            $is_paid = 0;
            $study_fees = $amount;
            
            $insert_stmt->bind_param(
                "ssiisiiiiss",
                $student_id,
                $student['student_name'],
                $semester_id,
                $amount,
                $reference,
                $registration_fees,
                $insurance_fees,
                $study_fees,
                $is_paid,
                $start_date,
                $end_date
            );
        } else {
            // If student_name column doesn't exist, use the standard insert
            $insert_stmt = $mysqli1->prepare("
                INSERT INTO registrations (
                    student_id, semester_id, payment_amount, payment_reference, 
                    registration_fees, insurance_fees, study_fees, is_paid,
                    start, end, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");
            
            $is_paid = 0;
            $study_fees = $amount;
            
            $insert_stmt->bind_param(
                "siisiiiiss",
                $student_id,
                $semester_id,
                $amount,
                $reference,
                $registration_fees,
                $insurance_fees,
                $study_fees,
                $is_paid,
                $start_date,
                $end_date
            );
        }
        
        if (!$insert_stmt->execute()) {
            throw new Exception("فشل في إنشاء القسط: " . $insert_stmt->error);
        }
        
        $total_amount += $amount;
        $created_installments++;
        $insert_stmt->close();
    }
    
    // Verify total amount matches original and correct number of installments created
    $original_amount = $original_registration['payment_amount'];
    if ($total_amount != $original_amount) {
        throw new Exception("المبلغ الإجمالي للأقساط ($total_amount) لا يتطابق مع المبلغ الأصلي ($original_amount)");
    }
    
    if ($created_installments != $installment_count) {
        throw new Exception("عدد الأقساط المنشأة ($created_installments) لا يتطابق مع العدد المطلوب ($installment_count)");
    }
    
    // Commit transaction
    $mysqli1->commit();
    
    // Redirect back to student profile with success message
    $_SESSION['success_message'] = "تم إنشاء " . $installment_count . " أقساط بنجاح بمبلغ إجمالي " . number_format($total_amount) . " SDG";
    header('Location: student_profile_admin.php?student_id=' . urlencode($student_id));
    exit;
    
} catch (Exception $e) {
    // Rollback transaction on error
    $mysqli1->rollback();
    
    // Log error
    error_log("Installment creation error: " . $e->getMessage());
    
    // Redirect back with error message
    $_SESSION['error_message'] = "حدث خطأ أثناء إنشاء الأقساط: " . $e->getMessage();
    header('Location: create_installments.php?registration_id=' . $original_registration_id . '&student_id=' . urlencode($student_id));
    exit;
}
?>