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

$student_id = $_GET['student_id'] ?? '';

if (empty($student_id)) {
    die("Error: No student ID provided");
}

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

if (!$student) {
    die("Error: Student not found");
}

// Check access permissions
$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 (!$canAll && $scopeCollege !== null && $student['college_id'] != $scopeCollege) {
    die("Error: You don't have permission to add registration for this student");
}

// Get fee types
$fee_types_result = $mysqli1->query("SELECT id, name, code FROM fee_types   ORDER BY name");
$fee_types = [];
while ($row = $fee_types_result->fetch_assoc()) {
    $fee_types[] = $row;
}

// Get semesters
$semesters_result = $mysqli1->query("SELECT id, name, code FROM semesters   ORDER BY created_at DESC");
$semesters = [];
while ($row = $semesters_result->fetch_assoc()) {
    $semesters[] = $row;
}

// CSRF Token functions
function generate_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validate_csrf_token($token) {
    if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
        // Regenerate token on failure
        unset($_SESSION['csrf_token']);
        return false;
    }
    return true;
}

// Generate CSRF token for this session
$csrf_token = generate_csrf_token();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submitted_csrf_token = $_POST['csrf'] ?? '';
    
    if (!validate_csrf_token($submitted_csrf_token)) {
        $_SESSION['error_message'] = 'رمز التحقق غير صالح أو منتهي الصلاحية';
        header("Location: committee_add_registration.php?student_id=" . urlencode($student_id));
        exit();
    }
    
    // Regenerate CSRF token after successful validation
    unset($_SESSION['csrf_token']);
    $csrf_token = generate_csrf_token();
    
    // Get form data
    $semester_id = (int)($_POST['semester_id'] ?? 0);
    $fee_type_id = (int)($_POST['fee_type_id'] ?? 0);
    $payment_amount = (float)($_POST['payment_amount'] ?? 0);
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $payment_reference = trim($_POST['payment_reference'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $is_paid = isset($_POST['is_paid']) ? 1 : 0;
    $create_installments = isset($_POST['create_installments']) ? 1 : 0;
    $installment_count = (int)($_POST['installment_count'] ?? 0);
    
    // Validation
    $errors = [];
    
    if ($semester_id <= 0) {
        $errors[] = 'يرجى اختيار الفصل الدراسي';
    }
    
    if ($fee_type_id <= 0) {
        $errors[] = 'يرجى اختيار نوع الرسوم';
    }
    
    if ($payment_amount <= 0) {
        $errors[] = 'يرجى إدخال مبلغ صحيح أكبر من الصفر';
    }
    
    if (empty($start_date)) {
        $errors[] = 'يرجى إدخال تاريخ البدء';
    }
    
    if (empty($end_date)) {
        $errors[] = 'يرجى إدخال تاريخ الانتهاء';
    }
    
    if (!empty($start_date) && !empty($end_date) && strtotime($start_date) >= strtotime($end_date)) {
        $errors[] = 'تاريخ البدء يجب أن يكون قبل تاريخ الانتهاء';
    }
    
    if (empty($payment_reference)) {
        $errors[] = 'يرجى إدخال رقم المرجع';
    }
    
    if ($create_installments && $installment_count <= 1) {
        $errors[] = 'يرجى اختيار عدد الأقساط (2 أو أكثر) عند تفعيل خيار الأقساط';
    }
    
    // Check for duplicate reference
    $check_stmt = $mysqli1->prepare("SELECT id FROM registrations WHERE payment_reference = ? AND deleted_at IS NULL");
    $check_stmt->bind_param("s", $payment_reference);
    $check_stmt->execute();
    if ($check_stmt->get_result()->num_rows > 0) {
        $errors[] = 'رقم المرجع مستخدم مسبقاً';
    }
    
    if (empty($errors)) {
        // Begin transaction
        $mysqli1->begin_transaction();
        
        try {
            // Insert registration
            $insert_stmt = $mysqli1->prepare("
                INSERT INTO registrations 
                (student_id, semester_id, fee_type_id, payment_amount, start, end, payment_reference, notes, is_paid, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");
            
            $insert_stmt->bind_param(
                "siidssssi",
                $student_id,
                $semester_id,
                $fee_type_id,
                $payment_amount,
                $start_date,
                $end_date,
                $payment_reference,
                $notes,
                $is_paid
            );
            
            if (!$insert_stmt->execute()) {
                throw new Exception("فشل في إضافة التسجيل: " . $insert_stmt->error);
            }
            
            $new_registration_id = $mysqli1->insert_id;
            
            // If create_installments is selected and registration is NOT paid
            if ($create_installments && $is_paid == 0) {
                // Get installment data
                $installment_amounts = $_POST['installment_amounts'] ?? [];
                $installment_start_dates = $_POST['installment_start_dates'] ?? [];
                $installment_end_dates = $_POST['installment_end_dates'] ?? [];
                $installment_references = $_POST['installment_references'] ?? [];
                
                // Validate installments
                $installment_total = 0;
                $installment_references_set = [];
                
                for ($i = 0; $i < $installment_count; $i++) {
                    $amount = (float)($installment_amounts[$i] ?? 0);
                    $start = $installment_start_dates[$i] ?? '';
                    $end = $installment_end_dates[$i] ?? '';
                    $reference = trim($installment_references[$i] ?? '');
                    
                    if ($amount <= 0) {
                        throw new Exception("المبلغ للقسط " . ($i + 1) . " غير صحيح");
                    }
                    
                    if (empty($start) || empty($end)) {
                        throw new Exception("تواريخ القسط " . ($i + 1) . " غير مكتملة");
                    }
                    
                    if (empty($reference)) {
                        throw new Exception("رقم المرجع للقسط " . ($i + 1) . " مطلوب");
                    }
                    
                    // Check for duplicate installment reference
                    if (in_array($reference, $installment_references_set)) {
                        throw new Exception("رقم المرجع للقسط " . ($i + 1) . " مكرر");
                    }
                    
                    $installment_references_set[] = $reference;
                    
                    // Check if reference already exists in registrations table
                    $check_ref_stmt = $mysqli1->prepare("SELECT id FROM registrations WHERE payment_reference = ? AND deleted_at IS NULL");
                    $check_ref_stmt->bind_param("s", $reference);
                    $check_ref_stmt->execute();
                    if ($check_ref_stmt->get_result()->num_rows > 0) {
                        throw new Exception("رقم المرجع للقسط " . ($i + 1) . " مستخدم مسبقاً");
                    }
                    
                    $installment_total += $amount;
                }
                
                // Verify total matches original amount
                if (abs($installment_total - $payment_amount) > 0.01) {
                    throw new Exception("مجموع الأقساط (" . $installment_total . ") لا يتطابق مع المبلغ الأصلي (" . $payment_amount . ")");
                }
                
                // Create installments (as separate registrations)
                for ($i = 0; $i < $installment_count; $i++) {
                    $amount = (float)$installment_amounts[$i];
                    $start = $installment_start_dates[$i];
                    $end = $installment_end_dates[$i];
                    $reference = trim($installment_references[$i]);
                    $installment_notes = "قسط " . ($i + 1) . " من " . $installment_count . " - المرجع الأصلي: " . $payment_reference;
                    
                    $installment_stmt = $mysqli1->prepare("
                        INSERT INTO registrations 
                        (student_id, semester_id, fee_type_id, payment_amount, start, end, payment_reference, notes, is_paid, parent_registration_id, created_at, updated_at) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, NOW(), NOW())
                    ");
                    
                    $installment_stmt->bind_param(
                        "siidssssi",
                        $student_id,
                        $semester_id,
                        $fee_type_id,
                        $amount,
                        $start,
                        $end,
                        $reference,
                        $installment_notes,
                        $new_registration_id
                    );
                    
                    if (!$installment_stmt->execute()) {
                        throw new Exception("فشل في إنشاء القسط " . ($i + 1) . ": " . $installment_stmt->error);
                    }
                }
                
                // Update original registration to mark it as having installments
                $update_stmt = $mysqli1->prepare("UPDATE registrations SET has_installments = 1 WHERE id = ?");
                $update_stmt->bind_param("i", $new_registration_id);
                $update_stmt->execute();
            }
            
            // Commit transaction
            $mysqli1->commit();
            
            $_SESSION['success_message'] = $create_installments ? 
                'تم إضافة التسجيل وإنشاء الأقساط بنجاح' : 
                'تم إضافة التسجيل بنجاح';
            
            header("Location: committee_student_profile.php?student_id=" . urlencode($student_id));
            exit();
            
        } catch (Exception $e) {
            // Rollback transaction
            $mysqli1->rollback();
            $_SESSION['error_message'] = $e->getMessage();
        }
    } else {
        $_SESSION['error_message'] = implode('<br>', $errors);
    }
}

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إضافة تسجيل جديد - لوحة اللجنة</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', system-ui, -apple-system, sans-serif !important; 
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .rtl-heading {
            text-align: right;
            font-weight: 700;
            color: #1F3A2E;
        }
        .installment-row:hover {
            background-color: #f8f9fa;
        }
        .form-check-label {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 fw-bold">إضافة تسجيل جديد</h3>
            <div class="ms-auto">
                <a class="btn btn-outline-secondary" href="committee_student_profile.php?student_id=<?= e($student_id) ?>">
                    <i class="fas fa-arrow-right me-2"></i>العودة لملف الطالب
                </a>
            </div>
        </div>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?= $_SESSION['error_message'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Student Info -->
        <div class="card card-arabic p-4 mb-4">
            <h4 class="rtl-heading mb-3">معلومات الطالب</h4>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-2">
                        <strong>الطالب:</strong> <?= e($student['student_name']) ?>
                    </div>
                    <div class="mb-2">
                        <strong>الاسم بالإنجليزية:</strong> <?= e($student['student_name_eng']) ?>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-2">
                        <strong>رقم الطالب:</strong> <?= e($student_id) ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Registration Form -->
        <div class="card card-arabic p-4">
            <form method="post" action="" id="registrationForm">
                <input type="hidden" name="csrf" value="<?= e($csrf_token) ?>">
                
                <h4 class="rtl-heading mb-3">بيانات التسجيل</h4>
                
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">الفصل الدراسي <span class="text-danger">*</span></label>
                        <select class="form-select" name="semester_id" required>
                            <option value="">-- اختر الفصل الدراسي --</option>
                            <?php foreach ($semesters as $semester): ?>
                                <option value="<?= $semester['id'] ?>" <?= isset($_POST['semester_id']) && $_POST['semester_id'] == $semester['id'] ? 'selected' : '' ?>>
                                    <?= e($semester['name']) ?> (<?= e($semester['code']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">نوع الرسوم <span class="text-danger">*</span></label>
                        <select class="form-select" name="fee_type_id" required>
                            <option value="">-- اختر نوع الرسوم --</option>
                            <?php foreach ($fee_types as $fee_type): ?>
                                <option value="<?= $fee_type['id'] ?>" <?= isset($_POST['fee_type_id']) && $_POST['fee_type_id'] == $fee_type['id'] ? 'selected' : '' ?>>
                                    <?= e($fee_type['name']) ?> (<?= e($fee_type['code']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="row mb-3">
                    <div class="col-md-4">
                        <label class="form-label">المبلغ <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="payment_amount" 
                                   value="<?= e($_POST['payment_amount'] ?? '') ?>" 
                                   step="0.01" min="0" required>
                            <span class="input-group-text">SDG</span>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <label class="form-label">تاريخ البدء <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" name="start_date" 
                               value="<?= e($_POST['start_date'] ?? '') ?>" required>
                    </div>
                    
                    <div class="col-md-4">
                        <label class="form-label">تاريخ الانتهاء <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" name="end_date" 
                               value="<?= e($_POST['end_date'] ?? '') ?>" required>
                    </div>
                </div>
                
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">رقم المرجع <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="payment_reference" 
                                   value="<?= e($_POST['payment_reference'] ?? '') ?>" required>
                            <button type="button" class="btn btn-outline-secondary" onclick="generateReference()">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        </div>
                        <small class="text-muted">رقم مرجعي فريد للدفعة</small>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">ملاحظات</label>
                        <textarea class="form-control" name="notes" rows="2"><?= e($_POST['notes'] ?? '') ?></textarea>
                    </div>
                </div>
                
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" role="switch" 
                                   id="is_paid" name="is_paid" value="1" 
                                   <?= isset($_POST['is_paid']) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="is_paid">
                                حالة الدفع: مدفوع
                            </label>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" role="switch" 
                                   id="create_installments" name="create_installments" value="1"
                                   <?= isset($_POST['create_installments']) ? 'checked' : '' ?>
                                   onchange="toggleInstallments()">
                            <label class="form-check-label" for="create_installments">
                                تقسيم إلى أقساط
                            </label>
                        </div>
                    </div>
                </div>
                
                <!-- Installments Section (hidden by default) -->
                <div id="installments_section" style="display: none;">
                    <h4 class="rtl-heading mb-3 border-top pt-3">تقسيم المبلغ إلى أقساط</h4>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">عدد الأقساط</label>
                            <select class="form-select" id="installment_count" name="installment_count" onchange="generateInstallments()">
                                <option value="2">2 أقساط</option>
                                <option value="3" selected>3 أقساط</option>
                                <option value="4">4 أقساط</option>
                                <option value="6">6 أقساط</option>
                            </select>
                        </div>
                        <div class="col-md-6 d-flex align-items-end">
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="generateInstallments()">
                                <i class="fas fa-redo me-1"></i>إعادة توليد الأقساط
                            </button>
                            <button type="button" class="btn btn-outline-info btn-sm ms-2" onclick="distributeRemainingAmount()">
                                <i class="fas fa-balance-scale me-1"></i>تصحيح المبلغ
                            </button>
                        </div>
                    </div>
                    
                    <!-- Installment Amount Warning -->
                    <div id="amount-warning" class="alert alert-warning mt-3" style="display: none;">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <span id="warning-text"></span>
                    </div>
                    
                    <!-- Installments Table -->
                    <div id="installments_preview" class="mb-4">
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th width="10%">القسط</th>
                                        <th width="20%">المبلغ</th>
                                        <th width="20%">تاريخ البدء</th>
                                        <th width="20%">تاريخ الانتهاء</th>
                                        <th width="25%">رقم المرجع</th>
                                        <th width="5%"></th>
                                    </tr>
                                </thead>
                                <tbody id="installments_table_body">
                                    <!-- Installments will be generated here by JavaScript -->
                                </tbody>
                                <tfoot>
                                    <tr class="table-success">
                                        <td><strong>المجموع</strong></td>
                                        <td id="total_amount_display" class="fw-bold">0 SDG</td>
                                        <td colspan="4"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between mt-4">
                    <a href="committee_student_profile.php?student_id=<?= e($student_id) ?>" class="btn btn-secondary">
                        <i class="fas fa-times me-2"></i>إلغاء
                    </a>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>حفظ التسجيل
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Bootstrap & jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Function to generate random 10-digit reference
    function generateReference() {
        const min = 1000000000;
        const max = 9999999999;
        const randomRef = Math.floor(min + Math.random() * (max - min + 1)).toString();
        document.querySelector('input[name="payment_reference"]').value = randomRef;
    }
    
    // Function to generate unique 10-digit reference
    function generateUniqueReference() {
        const min = 1000000000;
        const max = 9999999999;
        return Math.floor(min + Math.random() * (max - min + 1)).toString();
    }
    
    // Function to generate unique references for installments
    function generateUniqueReferences(count) {
        const references = new Set();
        while (references.size < count) {
            references.add(generateUniqueReference());
        }
        return Array.from(references);
    }
    
    // Toggle installments section
    function toggleInstallments() {
        const createInstallments = document.getElementById('create_installments').checked;
        const isPaid = document.getElementById('is_paid').checked;
        const installmentsSection = document.getElementById('installments_section');
        
        if (createInstallments && !isPaid) {
            installmentsSection.style.display = 'block';
            generateInstallments();
        } else {
            installmentsSection.style.display = 'none';
        }
    }
    
    // Generate installments
    function generateInstallments() {
        const installmentCount = parseInt(document.getElementById('installment_count').value);
        const tableBody = document.getElementById('installments_table_body');
        const paymentAmount = parseFloat(document.querySelector('input[name="payment_amount"]').value) || 0;
        const startDate = document.querySelector('input[name="start_date"]').value;
        
        // Clear previous content
        tableBody.innerHTML = '';
        
        if (paymentAmount <= 0 || !startDate) {
            return;
        }
        
        // Calculate base installment amount
        const baseInstallment = Math.floor(paymentAmount / installmentCount);
        const remainder = paymentAmount % installmentCount;
        
        // Generate unique references
        const uniqueReferences = generateUniqueReferences(installmentCount);
        
        // Parse start date
        const startDateObj = new Date(startDate);
        
        for (let i = 1; i <= installmentCount; i++) {
            // Calculate dates
            const installmentStartDate = new Date(startDateObj);
            installmentStartDate.setMonth(startDateObj.getMonth() + (i - 1));
            
            const installmentEndDate = new Date(installmentStartDate);
            installmentEndDate.setMonth(installmentStartDate.getMonth() + 1);
            
            // Calculate amount
            let installmentAmount = baseInstallment;
            if (i === installmentCount) {
                installmentAmount += remainder;
            }
            
            // Format dates for input
            const formattedStart = installmentStartDate.toISOString().split('T')[0];
            const formattedEnd = installmentEndDate.toISOString().split('T')[0];
            
            const row = document.createElement('tr');
            row.className = 'installment-row';
            row.innerHTML = `
                <td>القسط ${i}</td>
                <td>
                    <input type="number" 
                           class="form-control form-control-sm installment-amount" 
                           name="installment_amounts[]" 
                           value="${installmentAmount.toFixed(2)}" 
                           min="0" 
                           step="0.01"
                           required
                           onchange="updateTotalAmount()">
                </td>
                <td>
                    <input type="date" class="form-control form-control-sm" 
                           name="installment_start_dates[]" 
                           value="${formattedStart}" 
                           required>
                </td>
                <td>
                    <input type="date" class="form-control form-control-sm" 
                           name="installment_end_dates[]" 
                           value="${formattedEnd}" 
                           required>
                </td>
                <td>
                    <div class="input-group input-group-sm">
                        <input type="text" class="form-control" 
                               name="installment_references[]" 
                               value="${uniqueReferences[i-1]}" 
                               required>
                        <button type="button" class="btn btn-outline-secondary" onclick="regenerateSingleReference(this)">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </td>
                <td>
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeInstallment(this)">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            `;
            
            tableBody.appendChild(row);
        }
        
        updateTotalAmount();
    }
    
    // Update total amount display
    function updateTotalAmount() {
        const amountInputs = document.querySelectorAll('.installment-amount');
        let totalAmount = 0;
        
        amountInputs.forEach(input => {
            totalAmount += parseFloat(input.value) || 0;
        });
        
        const paymentAmount = parseFloat(document.querySelector('input[name="payment_amount"]').value) || 0;
        const totalDisplay = document.getElementById('total_amount_display');
        totalDisplay.textContent = totalAmount.toFixed(2) + ' SDG';
        
        // Update styling based on amount match
        if (Math.abs(totalAmount - paymentAmount) < 0.01) {
            totalDisplay.className = 'fw-bold text-success';
            document.getElementById('amount-warning').style.display = 'none';
        } else {
            totalDisplay.className = 'fw-bold text-danger';
            const warningMessage = document.getElementById('amount-warning');
            const warningText = document.getElementById('warning-text');
            const difference = paymentAmount - totalAmount;
            warningText.textContent = `المبلغ الإجمالي ${totalAmount.toFixed(2)} SDG - ${difference > 0 ? 'ناقص' : 'زائد'} ${Math.abs(difference).toFixed(2)} SDG من المبلغ الأصلي`;
            warningMessage.style.display = 'block';
        }
    }
    
    // Distribute remaining amount
    function distributeRemainingAmount() {
        const amountInputs = Array.from(document.querySelectorAll('.installment-amount'));
        const paymentAmount = parseFloat(document.querySelector('input[name="payment_amount"]').value) || 0;
        let currentTotal = 0;
        
        amountInputs.forEach(input => {
            currentTotal += parseFloat(input.value) || 0;
        });
        
        const remainingAmount = paymentAmount - currentTotal;
        
        if (Math.abs(remainingAmount) > 0.01 && amountInputs.length > 0) {
            // Distribute remaining amount equally
            const baseDistribution = Math.floor(remainingAmount / amountInputs.length * 100) / 100; // Round to 2 decimals
            let finalRemainder = Math.round((remainingAmount - baseDistribution * amountInputs.length) * 100) / 100;
            
            amountInputs.forEach((input, index) => {
                const currentAmount = parseFloat(input.value) || 0;
                let newAmount = currentAmount + baseDistribution;
                
                // Add remainder to the last installment
                if (index === amountInputs.length - 1) {
                    newAmount += finalRemainder;
                }
                
                input.value = newAmount.toFixed(2);
            });
            
            updateTotalAmount();
            
            // Show success message
            const warningMessage = document.getElementById('amount-warning');
            if (warningMessage) {
                warningMessage.className = 'alert alert-success mt-3';
                warningMessage.innerHTML = `<i class="fas fa-check me-2"></i>تم توزيع المبلغ المتبقي (${remainingAmount.toFixed(2)} SDG) بنجاح!`;
                warningMessage.style.display = 'block';
                
                // Hide after 3 seconds
                setTimeout(() => {
                    updateTotalAmount();
                }, 3000);
            }
        }
    }
    
    // Regenerate single reference
    function regenerateSingleReference(button) {
        const input = button.parentElement.querySelector('input');
        const allReferenceInputs = document.querySelectorAll('input[name*="installment_references"]');
        const existingReferences = new Set();
        
        // Collect all current references except the one we're regenerating
        allReferenceInputs.forEach(refInput => {
            if (refInput !== input) {
                existingReferences.add(refInput.value);
            }
        });
        
        // Generate a new unique reference
        let newRef;
        do {
            newRef = generateUniqueReference();
        } while (existingReferences.has(newRef));
        
        input.value = newRef;
    }
    
    // Remove installment (not implemented - would require regenerating all installments)
    function removeInstallment(button) {
        const row = button.closest('tr');
        if (row && confirm('هل تريد حذف هذا القسط؟')) {
            // Instead of removing, regenerate all installments with new count
            const currentRows = document.querySelectorAll('#installments_table_body tr').length;
            if (currentRows > 2) { // Minimum 2 installments
                document.getElementById('installment_count').value = currentRows - 1;
                generateInstallments();
            } else {
                alert('يجب أن يكون هناك على الأقل قسطين');
            }
        }
    }
    
    // Form validation
    document.getElementById('registrationForm').addEventListener('submit', function(e) {
        const createInstallments = document.getElementById('create_installments').checked;
        const isPaid = document.getElementById('is_paid').checked;
        
        // If installments are selected but registration is paid, show error
        if (createInstallments && isPaid) {
            e.preventDefault();
            alert('لا يمكن تقسيم التسجيل إلى أقساط إذا كان حالة الدفع "مدفوع". يرجى إلغاء خيار "تقسيم إلى أقساط" أو تغيير حالة الدفع إلى "معلق".');
            return false;
        }
        
        // Validate installments if enabled
        if (createInstallments && !isPaid) {
            const paymentAmount = parseFloat(document.querySelector('input[name="payment_amount"]').value) || 0;
            const amountInputs = document.querySelectorAll('.installment-amount');
            let totalAmount = 0;
            let hasInvalidAmount = false;
            
            // Validate amounts
            amountInputs.forEach(input => {
                const amount = parseFloat(input.value) || 0;
                totalAmount += amount;
                
                if (amount <= 0) {
                    hasInvalidAmount = true;
                    input.classList.add('is-invalid');
                } else {
                    input.classList.remove('is-invalid');
                }
            });
            
            if (hasInvalidAmount) {
                e.preventDefault();
                alert('يرجى إدخال مبالغ صحيحة لجميع الأقساط (أكبر من صفر)');
                return false;
            }
            
            // Check if total matches
            if (Math.abs(totalAmount - paymentAmount) > 0.01) {
                e.preventDefault();
                const response = confirm(
                    `المبلغ الإجمالي للأقساط (${totalAmount.toFixed(2)} SDG) لا يتطابق مع المبلغ الأصلي (${paymentAmount.toFixed(2)} SDG).\n\n` +
                    `الفرق: ${Math.abs(paymentAmount - totalAmount).toFixed(2)} SDG\n\n` +
                    `هل تريد تصحيح المبلغ تلقائياً؟`
                );
                
                if (response) {
                    distributeRemainingAmount();
                }
                return false;
            }
            
            // Validate references are unique
            const referenceInputs = document.querySelectorAll('input[name*="installment_references"]');
            const references = Array.from(referenceInputs).map(input => input.value);
            const uniqueReferences = new Set(references);
            
            if (references.length !== uniqueReferences.size) {
                e.preventDefault();
                alert('يوجد أرقام مراجع مكررة في الأقساط. يرجى إعادة توليد أرقام المراجع.');
                return false;
            }
            
            // Validate main reference is not duplicated in installments
            const mainReference = document.querySelector('input[name="payment_reference"]').value;
            if (references.includes(mainReference)) {
                e.preventDefault();
                alert('رقم المرجع الرئيسي مكرر في أحد الأقساط. يرجى تغييره.');
                return false;
            }
        }
    });
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        // Generate initial reference
        generateReference();
        
        // Check if installments should be shown
        toggleInstallments();
        
        // Add event listeners
        document.getElementById('is_paid').addEventListener('change', toggleInstallments);
        
        // Update installments when payment amount changes
        document.querySelector('input[name="payment_amount"]').addEventListener('change', function() {
            if (document.getElementById('create_installments').checked) {
                generateInstallments();
            }
        });
    });
    </script>
</body>
</html>