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

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

if (empty($registration_id) || empty($student_id)) {
    die("Error: Missing parameters");
}

// Get registration data
$stmt = $mysqli1->prepare("
    SELECT r.*, sem.name as semester_name, sem.code as semester_code, sem.id as semester_id 
    FROM registrations r 
    LEFT JOIN semesters sem ON r.semester_id = sem.id 
    WHERE r.id = ? AND r.student_id = ? AND r.deleted_at IS NULL
");
$stmt->bind_param("is", $registration_id, $student_id);
$stmt->execute();
$registration = $stmt->get_result()->fetch_assoc();

if (!$registration) {
    die("Error: Registration not found");
}

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

// Get semesters for dropdown
$semesters = $mysqli1->query("SELECT id, name, code FROM semesters ORDER BY id DESC");

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-select:disabled {
            background-color: #e9ecef;
            opacity: 1;
        }
    </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="student_profile_admin.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']) ?> (<?= e($student['student_name_eng']) ?>)
                    </div>
                    <div class="mb-2">
                        <strong>رقم الطالب:</strong> <?= e($student_id) ?>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-2">
                        <strong>الفصل الدراسي:</strong> <?= e($registration['semester_name']) ?> (<?= e($registration['semester_code']) ?>)
                    </div>
                    <div class="mb-2">
                        <strong>المبلغ الأصلي:</strong> <span class="fw-bold text-primary"><?= number_format($registration['payment_amount']) ?> SDG</span>
                    </div>
                    <div class="mb-2">
                        <strong>رقم المرجع:</strong> <?= e($registration['payment_reference']) ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Installment Form -->
        <div class="card card-arabic p-4">
            <h4 class="rtl-heading mb-3">تقسيم المبلغ إلى أقساط</h4>
            
            <form method="post" action="process_installments.php" onsubmit="return validateForm()">
                <input type="hidden" name="original_registration_id" value="<?= e($registration_id) ?>">
                <input type="hidden" name="student_id" value="<?= e($student_id) ?>">
                <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="semester_id" value="<?= e($registration['semester_id']) ?>">
                
                <!-- Installment Configuration -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <label class="form-label">عدد الأقساط</label>
                        <select class="form-select" id="installment_count" name="installment_count" required>
                            <option value="2">2 أقساط</option>
                            <option value="3">3 أقساط</option>
                            <option value="4">4 أقساط</option>
                            <option value="6">6 أقساط</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">الفصل الدراسي للأقساط</label>
                        <div class="input-group">
                            <input type="text" 
                                   class="form-control" 
                                   value="<?= e($registration['semester_name']) ?> (<?= e($registration['semester_code']) ?>)" 
                                   disabled 
                                   readonly>
                            <span class="input-group-text">
                                <i class="fas fa-lock text-muted" title="الفصل الدراسي ثابت بناءً على التسجيل الأصلي"></i>
                            </span>
                        </div>
                        <div class="form-text text-muted mt-1">
                            <i class="fas fa-info-circle me-1"></i>
                            الفصل الدراسي هو نفسه الفصل الدراسي للتسجيل الأصلي ولا يمكن تغييره
                        </div>
                    </div>
                </div>
 
                <!-- Additional Options -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <label class="form-label">رسوم التسجيل (لكل قسط)</label>
                        <input type="number" class="form-control" name="registration_fees" value="0" step="1" min="0">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">رسوم التأمين (لكل قسط)</label>
                        <input type="number" class="form-control" name="insurance_fees" value="0" step="1" min="0">
                    </div>
                </div>

                <!-- 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 class="mt-2 small">
                        <button type="button" class="btn btn-sm btn-outline-warning" onclick="distributeRemainingAmount()">
                            <i class="fas fa-magic me-1"></i>تصحيح تلقائي
                        </button>
                    </div>
                </div>

                <!-- Auto-distribute button -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="distributeRemainingAmount()">
                            <i class="fas fa-balance-scale me-1"></i>توزيع المبلغ المتبقي تلقائياً
                        </button>
                    </div>
                    <div class="text-muted small">
                        المبلغ الأصلي: <strong><?= number_format($registration['payment_amount']) ?> SDG</strong>
                    </div>
                </div>

                <!-- Installments Preview -->
                <div id="installments_preview" class="mb-4">
                    <h5 class="mb-3">معاينة الأقساط</h5>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th>القسط</th>
                                    <th>المبلغ</th>
                                    <th>تاريخ البدء</th>
                                    <th>تاريخ الانتهاء</th>
                                    <th>رقم المرجع</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="3"></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>

                <div class="d-flex justify-content-between">
                    <a href="student_profile_admin.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>
const originalAmount = <?= $registration['payment_amount'] ?>;
const originalReference = '<?= e($registration['payment_reference']) ?>';

// Function to generate random 10-digit integer reference
function generateRandomReference() {
    // Generate random number between 1000000000 and 9999999999 (10 digits)
    const min = 1000000000;
    const max = 9999999999;
    return Math.floor(min + Math.random() * (max - min + 1)).toString();
}

// Function to ensure all references are unique
function generateUniqueReferences(count) {
    const references = new Set();
    
    while (references.size < count) {
        const newRef = generateRandomReference();
        references.add(newRef);
    }
    
    return Array.from(references);
}

function calculateInstallments() {
    const installmentCount = parseInt(document.getElementById('installment_count').value);
    const tableBody = document.getElementById('installments_table_body');
    
    // Clear previous content
    tableBody.innerHTML = '';
    
    const today = new Date();
    
    // Calculate base installment amount (integer division)
    const baseInstallment = Math.floor(originalAmount / installmentCount);
    const remainder = originalAmount % installmentCount;
    
    // Generate unique references for all installments
    const uniqueReferences = generateUniqueReferences(installmentCount);
    
    for (let i = 1; i <= installmentCount; i++) {
        const startDate = new Date(today);
        startDate.setMonth(today.getMonth() + (i - 1));
        
        const endDate = new Date(startDate);
        endDate.setMonth(startDate.getMonth() + 1);
        
        // Get unique reference for this installment
        const installmentRef = uniqueReferences[i - 1];
        
        // Distribute amount: first installments get base amount, last one gets base + remainder
        let installmentAmount = baseInstallment;
        if (i === installmentCount) {
            installmentAmount += remainder;
        }
        
        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="installments[${i-1}][amount]" 
                       value="${installmentAmount}" 
                       min="1" 
                       step="1"
                       required
                       onchange="updateTotalAmount()">
            </td>
            <td>
                <input type="date" class="form-control form-control-sm" 
                       name="installments[${i-1}][start_date]" 
                       value="${startDate.toISOString().split('T')[0]}" 
                       required>
            </td>
            <td>
                <input type="date" class="form-control form-control-sm" 
                       name="installments[${i-1}][end_date]" 
                       value="${endDate.toISOString().split('T')[0]}" 
                       required>
            </td>
            <td>
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control" 
                           name="installments[${i-1}][reference]" 
                           value="${installmentRef}" 
                           required 
                           readonly>
                    <button type="button" class="btn btn-outline-secondary" onclick="regenerateSingleReference(this)">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </td>
        `;
        
        tableBody.appendChild(row);
    }
    
    updateTotalAmount();
}

function updateTotalAmount() {
    const amountInputs = document.querySelectorAll('.installment-amount');
    let totalAmount = 0;
    
    amountInputs.forEach(input => {
        totalAmount += parseInt(input.value) || 0;
    });
    
    const totalDisplay = document.getElementById('total_amount_display');
    totalDisplay.textContent = totalAmount.toLocaleString() + ' SDG';
    
    // Update styling based on amount match
    if (totalAmount === originalAmount) {
        totalDisplay.className = 'fw-bold text-success';
    } else if (totalAmount > originalAmount) {
        totalDisplay.className = 'fw-bold text-danger';
    } else {
        totalDisplay.className = 'fw-bold text-warning';
    }
    
    // Show/hide warning message
    const warningMessage = document.getElementById('amount-warning');
    const warningText = document.getElementById('warning-text');
    
    if (totalAmount !== originalAmount) {
        const difference = originalAmount - totalAmount;
        warningMessage.style.display = 'block';
        warningMessage.className = totalAmount > originalAmount ? 'alert alert-danger mt-3' : 'alert alert-warning mt-3';
        warningText.textContent = `المبلغ الإجمالي ${totalAmount.toLocaleString()} SDG - ${difference > 0 ? 'ناقص' : 'زائد'} ${Math.abs(difference).toLocaleString()} SDG من المبلغ الأصلي`;
    } else {
        warningMessage.style.display = 'none';
    }
}

function distributeRemainingAmount() {
    const amountInputs = Array.from(document.querySelectorAll('.installment-amount'));
    let currentTotal = 0;
    
    amountInputs.forEach(input => {
        currentTotal += parseInt(input.value) || 0;
    });
    
    const remainingAmount = originalAmount - currentTotal;
    
    if (remainingAmount !== 0 && amountInputs.length > 0) {
        // Distribute remaining amount equally
        const baseDistribution = Math.floor(remainingAmount / amountInputs.length);
        const finalRemainder = remainingAmount % amountInputs.length;
        
        amountInputs.forEach((input, index) => {
            const currentAmount = parseInt(input.value) || 0;
            let newAmount = currentAmount + baseDistribution;
            
            // Add remainder to the last installment
            if (index === amountInputs.length - 1) {
                newAmount += finalRemainder;
            }
            
            input.value = newAmount;
        });
        
        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.toLocaleString()} SDG) بنجاح!`;
            warningMessage.style.display = 'block';
            
            // Hide after 3 seconds
            setTimeout(() => {
                updateTotalAmount(); // This will set the appropriate styling
            }, 3000);
        }
    }
}

// Function to regenerate a single reference
function regenerateSingleReference(button) {
    const input = button.parentElement.querySelector('input');
    const allReferenceInputs = document.querySelectorAll('input[name*="reference"]');
    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 = generateRandomReference();
    } while (existingReferences.has(newRef));
    
    input.value = newRef;
}

// Function to regenerate all references
function regenerateAllReferences() {
    const referenceInputs = document.querySelectorAll('input[name*="reference"]');
    const uniqueReferences = generateUniqueReferences(referenceInputs.length);
    
    referenceInputs.forEach((input, index) => {
        input.value = uniqueReferences[index];
    });
    
    // Show success message
    const warningMessage = document.getElementById('amount-warning');
    if (warningMessage) {
        warningMessage.className = 'alert alert-info mt-3';
        warningMessage.innerHTML = `<i class="fas fa-check me-2"></i>تم إعادة توليد جميع أرقام المراجع بنجاح!`;
        warningMessage.style.display = 'block';
        
        // Hide after 3 seconds
        setTimeout(() => {
            warningMessage.style.display = 'none';
        }, 3000);
    }
}

// Add regenerate button to the form
function addRegenerateButton() {
    const autoDistributeSection = document.querySelector('.d-flex.justify-content-between.align-items-center.mb-3');
    
    if (autoDistributeSection && !document.getElementById('regenerate-ref-btn')) {
        const regenerateBtn = document.createElement('button');
        regenerateBtn.type = 'button';
        regenerateBtn.className = 'btn btn-outline-info btn-sm ms-2';
        regenerateBtn.id = 'regenerate-ref-btn';
        regenerateBtn.innerHTML = '<i class="fas fa-sync-alt me-1"></i>إعادة توليد أرقام المراجع';
        regenerateBtn.onclick = regenerateAllReferences;
        
        autoDistributeSection.querySelector('div').appendChild(regenerateBtn);
    }
}

function validateForm() {
    const installmentCount = document.getElementById('installment_count').value;
    
    if (!installmentCount) {
        alert('يرجى اختيار عدد الأقساط');
        return false;
    }
    
    // Validate total amount
    const amountInputs = document.querySelectorAll('.installment-amount');
    let totalAmount = 0;
    let hasInvalidAmount = false;
    
    amountInputs.forEach(input => {
        const amount = parseInt(input.value) || 0;
        totalAmount += amount;
        
        if (amount <= 0) {
            hasInvalidAmount = true;
            input.classList.add('is-invalid');
        } else {
            input.classList.remove('is-invalid');
        }
    });
    
    if (hasInvalidAmount) {
        alert('يرجى إدخال مبالغ صحيحة لجميع الأقساط (أكبر من صفر)');
        return false;
    }
    
    if (totalAmount !== originalAmount) {
        const difference = originalAmount - totalAmount;
        const response = confirm(
            `المبلغ الإجمالي للأقساط (${totalAmount.toLocaleString()} SDG) لا يتطابق مع المبلغ الأصلي (${originalAmount.toLocaleString()} SDG).\n\n` +
            `الفرق: ${Math.abs(difference).toLocaleString()} SDG (${difference > 0 ? 'ناقص' : 'زائد'})\n\n` +
            `هل تريد تصحيح المبلغ تلقائياً؟`
        );
        
        if (response) {
            distributeRemainingAmount();
            return false; // Let user review and submit again
        } else {
            return false;
        }
    }
    
    // Validate references are unique
    const referenceInputs = document.querySelectorAll('input[name*="reference"]');
    const references = Array.from(referenceInputs).map(input => input.value);
    const uniqueReferences = new Set(references);
    
    if (references.length !== uniqueReferences.size) {
        alert('يوجد أرقام مراجع مكررة. يرجى إعادة توليد أرقام المراجع.');
        regenerateAllReferences();
        return false;
    }
    
    // Validate that references are 10 digits
    const invalidReferences = references.filter(ref => !/^\d{10}$/.test(ref));
    if (invalidReferences.length > 0) {
        alert('يجب أن تكون أرقام المراجع مكونة من 10 أرقام فقط.');
        regenerateAllReferences();
        return false;
    }
    
    // Validate dates
    const rows = document.querySelectorAll('#installments_table_body tr');
    for (let i = 0; i < rows.length; i++) {
        const startDateInput = rows[i].querySelector('input[name*="start_date"]');
        const endDateInput = rows[i].querySelector('input[name*="end_date"]');
        const startDate = startDateInput.value;
        const endDate = endDateInput.value;
        
        if (!startDate || !endDate) {
            alert('يرجى ملء جميع تواريخ البدء والانتهاء');
            return false;
        }
        
        if (new Date(startDate) >= new Date(endDate)) {
            alert('تاريخ البدء يجب أن يكون قبل تاريخ الانتهاء للقسط ' + (i + 1));
            startDateInput.focus();
            return false;
        }
    }
    
    return true;
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Calculate initial installments
    calculateInstallments();
    
    // Add event listener for installment count change
    document.getElementById('installment_count').addEventListener('change', calculateInstallments);
    
    // Add regenerate button after a short delay to ensure DOM is ready
    setTimeout(addRegenerateButton, 100);
});
</script>

</body>
</html>