<?php
// get_student_registrations.php - AJAX endpoint for student registrations
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';

// Check if student_id is provided
$student_id = $_GET['student_id'] ?? '';
if (empty($student_id)) {
    die('<div class="alert alert-danger">لم يتم تحديد رقم الطالب</div>');
}

// Get student details
$student_stmt = $mysqli1->prepare("
    SELECT student_id, student_name, college_id, section_id, program_id
    FROM students 
    WHERE student_id = ?
");
$student_stmt->bind_param("s", $student_id);
$student_stmt->execute();
$student = $student_stmt->get_result()->fetch_assoc();
$student_stmt->close();

if (!$student) {
    die('<div class="alert alert-danger">الطالب غير موجود</div>');
}

// Get all registrations for the student
$registrations_stmt = $mysqli1->prepare("
    SELECT 
        r.*,
        s.name as semester_name,
        s.code as semester_code,
        u.name as registered_by_name
    FROM registrations r
    INNER JOIN semesters s ON r.semester_id = s.id
    LEFT JOIN users u ON r.user_id = u.id
    WHERE r.student_id = ? AND r.deleted_at IS NULL
    ORDER BY r.created_at DESC
");
$registrations_stmt->bind_param("s", $student_id);
$registrations_stmt->execute();
$registrations = $registrations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$registrations_stmt->close();

if (empty($registrations)) {
    echo '<div class="alert alert-info">لا توجد تسجيلات سابقة لهذا الطالب</div>';
    exit;
}
?>

<div class="container-fluid">
    <!-- Student Info -->
    <div class="alert alert-info mb-4">
        <div class="row">
            <div class="col-md-6">
                <strong>رقم الطالب:</strong> <?= e($student['student_id']) ?><br>
                <strong>اسم الطالب:</strong> <?= e($student['student_name']) ?>
            </div>
            <div class="col-md-6 text-end">
                <strong>عدد التسجيلات:</strong> <?= count($registrations) ?>
            </div>
        </div>
    </div>

    <!-- Registrations Table -->
    <div class="table-responsive">
        <table class="table table-hover table-sm">
            <thead>
                <tr>
                    <th>#</th>
                    <th>الفصل الدراسي</th>
                    <th>الرقم المرجعي</th>
                    <th>فترة التسجيل</th>
                    <th>الرسوم</th>
                    <th>الحالة</th>
                    <th>تم بواسطة</th>
                    <th>التاريخ</th>
                    <th>الإجراءات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($registrations as $index => $reg): ?>
                <?php
                $now = date('Y-m-d H:i:s');
                $start_date = $reg['start'];
                $end_date = $reg['end'];
                
                if ($now < $start_date) {
                    $status_class = 'badge bg-warning';
                    $status_text = 'قادم';
                } elseif ($now >= $start_date && $now <= $end_date) {
                    $status_class = 'badge bg-success';
                    $status_text = 'نشط';
                } else {
                    $status_class = 'badge bg-danger';
                    $status_text = 'منتهي';
                }
                
                $total_fees = $reg['study_fees'] + $reg['registration_fees'] + $reg['insurance_fees'];
                ?>
                <tr>
                    <td class="text-muted"><?= $index + 1 ?></td>
                    <td><?= e($reg['semester_name']) ?> (<?= e($reg['semester_code']) ?>)</td>
                    <td><span class="badge bg-secondary"><?= e($reg['payment_reference']) ?></span></td>
                    <td>
                        <?= date('Y-m-d', strtotime($reg['start'])) ?>
                        <br>
                        <small class="text-muted">إلى <?= date('Y-m-d', strtotime($reg['end'])) ?></small>
                    </td>
                    <td>
                        <div class="small">
                            <div>المجموع: <strong><?= number_format($total_fees, 2) ?></strong></div>
                            <div>المدفوع: <span class="text-success"><?= number_format($total_fees - $reg['due_amount'], 2) ?></span></div>
                            <div>المستحق: <span class="text-danger"><?= number_format($reg['due_amount'], 2) ?></span></div>
                        </div>
                    </td>
                    <td>
                        <span class="<?= $status_class ?>"><?= $status_text ?></span><br>
                        <?php if ($reg['is_paid']): ?>
                            <span class="badge bg-success">مدفوع</span>
                        <?php else: ?>
                            <span class="badge bg-danger">غير مدفوع</span>
                        <?php endif; ?>
                    </td>
                    <td><?= e($reg['registered_by_name'] ?? 'نظام') ?></td>
                    <td>
                        <?= date('Y-m-d', strtotime($reg['created_at'])) ?>
                        <br>
                        <small class="text-muted"><?= date('H:i', strtotime($reg['created_at'])) ?></small>
                    </td>
                    <td>
                        <div class="d-flex gap-1">
                            <!-- زر حذف التسجيل -->
                            <button type="button" 
                                    class="btn btn-sm btn-danger delete-registration-btn"
                                    data-id="<?= $reg['id'] ?>"
                                    data-semester="<?= e($reg['semester_name'] . ' (' . $reg['semester_code'] . ')') ?>"
                                    data-reference="<?= e($reg['payment_reference']) ?>"
                                    title="حذف التسجيل من الفصل الدراسي">
                                <i class="fas fa-trash"></i>
                            </button>
                            
                            <!-- زر التمديد -->
                            <a href="extend_registration.php?id=<?= $reg['id'] ?>" 
                               class="btn btn-sm btn-warning"
                               title="تمديد التسجيل">
                                <i class="fas fa-calendar-plus"></i>
                            </a>
                            
                            <!-- زر عرض التفاصيل -->
                            <a href="student_profile.php?student_id=<?= urlencode($reg['student_id']) ?>" 
                               class="btn btn-sm btn-info"
                               title="عرض ملف الطالب">
                                <i class="fas fa-eye"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
// Handle delete registration button click
document.addEventListener('DOMContentLoaded', function() {
    const deleteButtons = document.querySelectorAll('.delete-registration-btn');
    
    deleteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const registrationId = this.getAttribute('data-id');
            const semesterName = this.getAttribute('data-semester');
            const reference = this.getAttribute('data-reference');
            
            // Confirmation dialog
            if (confirm(`هل أنت متأكد من حذف التسجيل ${reference} من الفصل ${semesterName}؟\n\nملاحظة: هذا الإجراء لا يمكن التراجع عنه.`)) {
                // Show loading
                const originalHTML = this.innerHTML;
                this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                this.disabled = true;
                
                // Send AJAX request
                fetch('delete_registration.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        registration_id: registrationId,
                        student_id: '<?= $student_id ?>'
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message
                        alert(data.message);
                        // Reload the registrations table
                        location.reload();
                    } else {
                        // Show error message
                        alert('حدث خطأ: ' + (data.message || 'فشل حذف التسجيل'));
                        // Reset button
                        this.innerHTML = originalHTML;
                        this.disabled = false;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('حدث خطأ في الاتصال بالخادم');
                    // Reset button
                    this.innerHTML = originalHTML;
                    this.disabled = false;
                });
            }
        });
    });
});
</script>