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

$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;

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

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

// Debug: Check what student_id we're receiving and what's in database
error_log("Searching for student_id: " . $student_id);

// First try exact match
$accessCheck = $mysqli1->prepare("SELECT student_id, college_id, phone_number FROM students WHERE student_id = ?");
$accessCheck->bind_param("s", $student_id);
$accessCheck->execute();
$studentData = $accessCheck->get_result()->fetch_assoc();

if (!$studentData) {
    // Try alternative formats
    $alternative_formats = [
        $student_id,
        str_replace('-', '', $student_id), // Remove dashes
        str_replace('23-', '', $student_id), // Remove year prefix if present
        '23-' . $student_id, // Add year prefix
        substr($student_id, 0, 2) . '-' . substr($student_id, 2), // Add dash if missing
        ltrim($student_id, '0'), // Remove leading zeros
        '0' . $student_id // Add leading zero
    ];
    
    // Remove duplicates
    $alternative_formats = array_unique($alternative_formats);
    
    foreach ($alternative_formats as $format) {
        if ($format === $student_id) continue; // Skip the original we already tried
        
        $accessCheck->bind_param("s", $format);
        $accessCheck->execute();
        $studentData = $accessCheck->get_result()->fetch_assoc();
        if ($studentData) {
            $student_id = $studentData['student_id']; // Use the correct format from database
            error_log("Found student with alternative format: " . $format . " -> " . $student_id);
            break;
        }
    }
}

if (!$studentData) {
    // Show comprehensive error with debugging info
    echo "<div class='container py-4'>";
    echo "<div class='alert alert-danger'>";
    echo "<h4>Error: Student not found</h4>";
    echo "<p><strong>Student ID searched:</strong> " . htmlspecialchars($student_id) . "</p>";
    
    // Show some sample student IDs from database for reference
    $sample_query = "SELECT student_id, student_name FROM students LIMIT 10";
    $sample_result = $mysqli1->query($sample_query);
    
    if ($sample_result && $sample_result->num_rows > 0) {
        echo "<p><strong>Sample student IDs in database:</strong></p>";
        echo "<ul>";
        while ($sample = $sample_result->fetch_assoc()) {
            echo "<li><a href='committee_student_profile.php?student_id=" . urlencode($sample['student_id']) . "'>" . 
                 htmlspecialchars($sample['student_id']) . " - " . htmlspecialchars($sample['student_name']) . "</a></li>";
        }
        echo "</ul>";
    }
    
    echo "<p>Please check:</p>";
    echo "<ul>";
    echo "<li>The student ID format</li>";
    echo "<li>If the student exists in the system</li>";
    echo "<li>Your access permissions</li>";
    echo "</ul>";
    echo "<a href='committee_dashboard.php' class='btn btn-secondary'>Return to Dashboard</a>";
    echo "</div>";
    echo "</div>";
    include 'footer.php';
    die();
}

// Check access permissions
if (!$canAll && $scopeCollege !== null && $studentData['college_id'] != $scopeCollege) {
    die("Error: You don't have permission to access this student's profile");
}

// Use the correct student_id from database
$correct_student_id = $studentData['student_id'];

// Get complete student data
$stmt = $mysqli1->prepare("
    SELECT 
        s.*,
        c.name AS college_name,
        p.name AS program_name,
        sec.name AS section_name,
        co.name AS country_name,
        st.name AS state_name,
        l.name AS locality_name
    FROM students s
    LEFT JOIN colleges c ON s.college_id = c.id
    LEFT JOIN programs p ON s.program_id = p.id
    LEFT JOIN sections sec ON s.section_id = sec.id
    LEFT JOIN countries co ON s.country_id = co.id
    LEFT JOIN states st ON s.state_id = st.id
    LEFT JOIN localities l ON s.locality_id = l.id
    WHERE s.student_id = ?
");

$stmt->bind_param("s", $correct_student_id);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();

if (!$data) {
    die("Error: Student data not found after access check passed");
}

// Get registration data
$registrations_stmt = $mysqli1->prepare("
    SELECT 
        r.*,
        sem.name as semester_name,
        sem.code as semester_code
    FROM registrations r
    LEFT JOIN semesters sem ON r.semester_id = sem.id
    WHERE r.student_id = ? 
    AND r.deleted_at IS NULL
    ORDER BY r.created_at DESC
");
$registrations_stmt->bind_param("s", $correct_student_id);
$registrations_stmt->execute();
$registrations = $registrations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get payment data
$payment_stmt = $mysqli1->prepare("
    SELECT 
        p.*,
        ft.name as fee_type_name,
        b.name as bank_name,
        sem.name as semester_name,
        sem.code as semester_code
    FROM payments p
    LEFT JOIN fee_types ft ON p.fee_type_id = ft.id
    LEFT JOIN banks b ON p.bank_id = b.id
    LEFT JOIN semesters sem ON p.semester_id = sem.id
    WHERE p.student_id = ? 
    AND p.deleted_at IS NULL
    ORDER BY p.created_at DESC
");
$payment_stmt->bind_param("s", $correct_student_id);
$payment_stmt->execute();
$payments = $payment_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get other_fees data
$other_fees_stmt = $mysqli1->prepare("
    SELECT 
        of.*,
        ft.name as fee_type_name,
        u.name as user_name
    FROM other_fees of
    LEFT JOIN fee_types ft ON of.fee_type_id = ft.id
    LEFT JOIN users u ON of.user_id = u.id
    WHERE of.phone_number = ? 
    AND of.deleted_at IS NULL
    ORDER BY of.created_at DESC
");
$other_fees_stmt->bind_param("s", $studentData['phone_number']);
$other_fees_stmt->execute();
$other_fees = $other_fees_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get other_payments data
$other_payments_stmt = $mysqli1->prepare("
    SELECT 
        op.*,
        ft.name as fee_type_name,
        b.name as bank_name,
        of.reference as fee_reference
    FROM other_payments op
    LEFT JOIN fee_types ft ON op.fee_type_id = ft.id
    LEFT JOIN banks b ON op.bank_id = b.id
    LEFT JOIN other_fees of ON op.other_fee_id = of.id
    WHERE op.phone_number = ? 
    AND op.deleted_at IS NULL
    ORDER BY op.created_at DESC
");
$other_payments_stmt->bind_param("s", $studentData['phone_number']);
$other_payments_stmt->execute();
$other_payments = $other_payments_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

include 'header.php';

// Check if student has any payment records - CHECK PAYMENTS TABLE ONLY
$hasPayments = false;

// Check payments table ONLY - هذا هو الشرط الوحيد
$checkPayments = $mysqli1->prepare("SELECT COUNT(*) as count FROM payments WHERE student_id = ? AND deleted_at IS NULL");
$checkPayments->bind_param("s", $correct_student_id);
$checkPayments->execute();
$paymentsResult = $checkPayments->get_result()->fetch_assoc();

// ONLY payments table prevents deletion
$hasPayments = ($paymentsResult['count'] > 0);

// Check other tables for display only
$checkRegistrations = $mysqli1->prepare("SELECT COUNT(*) as count FROM registrations WHERE student_id = ? AND deleted_at IS NULL");
$checkRegistrations->bind_param("s", $correct_student_id);
$checkRegistrations->execute();
$registrationsResult = $checkRegistrations->get_result()->fetch_assoc();

// جدول installments غير موجود، لذلك نتجاهله
$installmentsResult = ['count' => 0];
?>

<!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', 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;
        }
        .info-row {
            border-bottom: 1px solid #f1f1f1;
            padding: 12px 0;
        }
        .info-row:last-child {
            border-bottom: none;
        }
        .status-badge {
            font-size: 0.8rem;
            padding: 0.4rem 0.8rem;
        }
        .table th {
            font-weight: 600;
            background-color: #f8f9fa;
        }
        .btn-group-sm > .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
    </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_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

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

        <?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; ?>
        
        <!-- Card 1: Student Information -->
        <div class="card card-arabic p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="rtl-heading mb-0">البيانات الأساسية للطالب</h4>
                <div class="btn-group" role="group">
                    <a href="committee_edit_student.php?student_id=<?= e($correct_student_id) ?>" class="btn btn-outline-primary">
                        <i class="fas fa-cog me-2"></i>تعديل البيانات
                    </a>
                    <?php if (!$hasPayments): ?>
                        <button type="button" class="btn btn-outline-danger" onclick="deleteStudent()">
                            <i class="fas fa-trash me-2"></i>حذف الطالب
                        </button>
                    <?php else: ?>
                        <button type="button" class="btn btn-outline-danger" disabled title="لا يمكن حذف الطالب لأنه لديه مدفوعات مرتبطة">
                            <i class="fas fa-trash me-2"></i>حذف الطالب
                        </button>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Show linked records info -->
            <div class="mb-3">
                <small class="text-muted">
                    السجلات المرتبطة: 
                    <?php if ($paymentsResult['count'] > 0): ?>
                        <span class="badge bg-danger">مدفوعات: <?= $paymentsResult['count'] ?></span>
                    <?php endif; ?>
                    <?php if ($registrationsResult['count'] > 0): ?>
                        <span class="badge bg-warning">تسجيلات: <?= $registrationsResult['count'] ?></span>
                    <?php endif; ?>
                    <?php if ($installmentsResult['count'] > 0): ?>
                        <span class="badge bg-info">أقساط: <?= $installmentsResult['count'] ?></span>
                    <?php endif; ?>
                    <?php if ($paymentsResult['count'] == 0 && $registrationsResult['count'] == 0 && $installmentsResult['count'] == 0): ?>
                        <span class="badge bg-success">لا توجد سجلات مرتبطة</span>
                    <?php endif; ?>
                </small>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="info-row">
                        <strong>رقم الطالب:</strong> 
                        <?= e($correct_student_id) ?>
                    </div>
                    <div class="info-row">
                        <strong>الاسم:</strong> <?= e($data['student_name']) ?>
                    </div>
                    <div class="info-row">
                        <strong>الاسم بالإنجليزية:</strong> <?= e($data['student_name_eng']) ?>
                    </div>
                    <div class="info-row">
                        <strong>البريد الإلكتروني:</strong> <?= e($data['email']) ?>
                    </div>
                    <div class="info-row">
                        <strong>رقم الهاتف:</strong> <?= e($data['phone_number']) ?>
                    </div>
                    <div class="info-row">
                        <strong>رقم الهاتف البديل:</strong> <?= e($data['phone_number2']) ?>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-row">
                        <strong>الكلية:</strong> <?= e($data['college_name']) ?>
                    </div>
                    <div class="info-row">
                        <strong>البرنامج:</strong> <?= e($data['program_name']) ?>
                    </div>
                    <div class="info-row">
                        <strong>القسم:</strong> <?= e($data['section_name']) ?>
                    </div>
                    <div class="info-row">
                        <strong>حالة المقابلة:</strong>
                        <span class="badge <?= $data['interview_status'] === 'accepted' ? 'bg-success' : ($data['interview_status'] === 'rejected' ? 'bg-danger' : 'bg-warning') ?> status-badge">
                            <?= e($data['interview_status'] === 'accepted' ? 'مقبول' : ($data['interview_status'] === 'rejected' ? 'مرفوض' : 'قيد الانتظار')) ?>
                        </span>
                    </div>
                    <div class="info-row">
                        <strong>الحالة الطبية:</strong>
                        <span class="badge <?= $data['medically_fit'] == 1 ? 'bg-success' : ($data['medically_fit'] == 0 ? 'bg-danger' : 'bg-warning') ?> status-badge">
                            <?= e($data['medically_fit'] == 1 ? 'لائق' : ($data['medically_fit'] == 0 ? 'غير لائق' : 'بانتظار الفحص')) ?>
                        </span>
                    </div>
                    <div class="info-row">
                        <strong>حالة الملف:</strong>
                        <span class="badge <?= $data['profile_completed'] == 1 ? 'bg-success' : 'bg-warning' ?> status-badge">
                            <?= e($data['profile_completed'] == 1 ? 'مكتمل' : 'غير مكتمل') ?>
                        </span>
                    </div>
                </div>
            </div>
        </div>

 <!-- Card 2: Registrations -->
<div class="card card-arabic p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="rtl-heading mb-0">سجل التسجيلات</h4>
        <div>
            <span class="badge bg-primary"><?= count($registrations) ?> تسجيل</span>
            <?php if ($_SESSION['committee_role_id'] != 2): ?>
                <a href="committee_add_registration.php?student_id=<?= e($correct_student_id) ?>" class="btn btn-sm btn-primary">
                    <i class="fas fa-plus me-2"></i>إضافة تسجيل جديد
                </a>
            <?php endif; ?>
        </div>
    </div>

    <?php if (empty($registrations)): ?>
        <div class="text-center text-muted py-4">
            <i class="fas fa-clipboard-list fa-2x mb-3"></i>
            <p>لا توجد تسجيلات</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>الفصل الدراسي</th>
                        <th>بداية التسجيل</th>
                        <th>نهاية التسجيل</th>
                        <th>المبلغ</th>
                        <th>رقم المرجع</th>
                        <th>حالة الدفع</th>
                        <th>تاريخ التسجيل</th>
                        <th>ملاحظات</th>
                        <?php if ($_SESSION['committee_role_id'] != 2): ?>
                            <th>الإجراءات</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($registrations as $registration): 
                        // تحويل التواريخ إلى تنسيق عربي
                        $start_date = !empty($registration['start']) ? 
                            date('Y/m/d', strtotime($registration['start'])) : '—';
                        $end_date = !empty($registration['end']) ? 
                            date('Y/m/d', strtotime($registration['end'])) : '—';
                    ?>
                        <tr>
                            <td>
                                <strong><?= e($registration['semester_name'] ?? '—') ?></strong>
                                <?php if ($registration['semester_code']): ?>
                                    <br><small class="text-muted"><?= e($registration['semester_code']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?= $start_date ?>
                            </td>
                            <td>
                                <?= $end_date ?>
                            </td>
                            <td>
                                <span class="fw-bold <?= $registration['is_paid'] == 1 ? 'text-success' : 'text-danger' ?>">
                                    <?= number_format($registration['payment_amount']) ?> SDG
                                </span>
                            </td>
                            <td><?= e($registration['payment_reference'] ?? '—') ?></td>
                            <td>
                                <span class="badge <?= $registration['is_paid'] == 1 ? 'bg-success' : 'bg-warning' ?> status-badge">
                                    <?= $registration['is_paid'] == 1 ? 'مدفوع' : 'معلق' ?>
                                </span>
                            </td>
                            <td><?= e($registration['created_at']) ?></td>
                            <td><?= e($registration['notes'] ?? '—') ?></td>
                            <?php if ($_SESSION['committee_role_id'] != 2): ?>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <!-- زر تعديل التسجيل -->
                                        <?php if ($registration['is_paid'] == 1): ?>
                                            <button class="btn btn-outline-warning" onclick="editRegistration(<?= $registration['id'] ?>)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                        <?php endif; ?>
                                        
                                        <?php if ($registration['is_paid'] == 0): ?>
                                            <button class="btn btn-outline-success" onclick="printReceipt(<?= $registration['id'] ?>, 'registration')">
                                                <i class="fas fa-print"></i>
                                            </button>
                                        <?php else: ?>
                                            <!-- Management gear icon for unpaid registrations -->
                                            <a class="btn btn-outline-info" href="committee_create_installments.php?registration_id=<?= $registration['id'] ?>&student_id=<?= e($correct_student_id) ?>" title="إدارة الأقساط">
                                                <i class="fas fa-cog"></i>
                                            </a>
                                        <?php endif; ?>
                                        
                                        <!-- Show delete button only for unpaid registrations -->
                                        <?php if ($registration['is_paid'] == 1): ?>
                                            <button class="btn btn-outline-danger" onclick="deleteRegistration(<?= $registration['id'] ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
<!-- Modal لتعديل التسجيل -->
<div class="modal fade" id="editRegistrationModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">تعديل بيانات التسجيل</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editRegistrationForm" action="committee_update_registration.php" method="POST" onsubmit="return submitEditForm(event)">
                <div class="modal-body">
                    <input type="hidden" id="registration_id" name="registration_id">
                    <input type="hidden" name="student_id" value="<?= e($correct_student_id) ?>">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="start" class="form-label">تاريخ بداية التسجيل</label>
                            <input type="date" class="form-control" id="start" name="start" required>
                        </div>
                        <div class="col-md-6">
                            <label for="end" class="form-label">تاريخ نهاية التسجيل</label>
                            <input type="date" class="form-control" id="end" name="end" required>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="payment_amount" class="form-label">المبلغ</label>
                            <input type="number" class="form-control" id="payment_amount" name="payment_amount" step="0.01" min="0" required>
                        </div>
                        <div class="col-md-6">
                            <label for="payment_reference" class="form-label">رقم المرجع</label>
                            <input type="text" class="form-control" id="payment_reference" name="payment_reference">
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="is_paid" class="form-label">حالة الدفع</label>
                            <select class="form-select" id="is_paid" name="is_paid">
                                <option value="0">معلق</option>
                                <option value="1">مدفوع</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="semester_id" class="form-label">الفصل الدراسي</label>
                            <select class="form-select" id="semester_id" name="semester_id">
                                <option value="">-- اختر الفصل --</option>
                                <?php
                                // جلب قائمة الفصول الدراسية
                                $semesters_query = $mysqli1->query("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY created_at DESC");
                                while ($semester = $semesters_query->fetch_assoc()):
                                ?>
                                    <option value="<?= $semester['id'] ?>"><?= e($semester['name']) ?> (<?= e($semester['code']) ?>)</option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="notes" class="form-label">ملاحظات</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                </div>
            </form>
        </div>
    </div>
</div>
 <!-- Card 3: Payments -->
<div class="card card-arabic p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="rtl-heading mb-0">سجل المدفوعات</h4>
        <span class="badge bg-success"><?= count($payments) ?> دفعة</span>
    </div>

    <?php if (empty($payments)): ?>
        <div class="text-center text-muted py-4">
            <i class="fas fa-credit-card fa-2x mb-3"></i>
            <p>لا توجد مدفوعات مسجلة</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>نوع الدفعة</th>
                        <th>المبلغ</th>
                        <th>رقم المرجع</th>
                        <th>رقم المعاملة</th>
                        <th>البنك</th>
                        <th>الفصل</th>
                        <th>التاريخ</th>
                        <?php if ($_SESSION['committee_role_id'] != 2): ?>
                            <th>الإجراءات</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td>
                                <strong><?= e($payment['fee_type_name'] ?? 'غير محدد') ?></strong>
                                <?php if ($payment['registration_fees'] > 0): ?>
                                    <br><small class="text-muted">تسجيل: <?= number_format($payment['registration_fees']) ?></small>
                                <?php endif; ?>
                                <?php if ($payment['insurance_fees'] > 0): ?>
                                    <br><small class="text-muted">تأمين: <?= number_format($payment['insurance_fees']) ?></small>
                                <?php endif; ?>
                                <?php if ($payment['study_fees'] > 0): ?>
                                    <br><small class="text-muted">دراسية: <?= number_format($payment['study_fees']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="fw-bold text-success"><?= number_format($payment['payment_amount']) ?> SDG</span>
                                <?php if ($payment['discount'] > 0): ?>
                                    <br><small class="text-success">خصم: <?= number_format($payment['discount']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?= e($payment['payment_reference']) ?></td>
                            <td><?= e($payment['transaction_ref'] ?? '—') ?></td>
                            <td><?= e($payment['bank_name'] ?? '—') ?></td>
                            <td>
                                <?= e($payment['semester_name'] ?? '—') ?>
                                <?php if ($payment['semester_code']): ?>
                                    <br><small class="text-muted"><?= e($payment['semester_code']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?= e($payment['created_at']) ?></td>
                            <?php if ($_SESSION['committee_role_id'] != 2): ?>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <!-- Always show print button for payments -->
                                        <button class="btn btn-outline-success" onclick="printReceipt(<?= $payment['id'] ?>, 'payment')">
                                            <i class="fas fa-print"></i>
                                        </button>
                                        <!-- Hide delete button for payments since they are already paid -->
                                        <!-- Payments cannot be deleted once created -->
                                    </div>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
        <!-- Card 4: Other Fees -->
        <div class="card card-arabic p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="rtl-heading mb-0">الرسوم الأخرى</h4>
                <span class="badge bg-info"><?= count($other_fees) ?> رسوم</span>
            </div>

            <?php if (empty($other_fees)): ?>
                <div class="text-center text-muted py-4">
                    <i class="fas fa-file-invoice-dollar fa-2x mb-3"></i>
                    <p>لا توجد رسوم أخرى</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>نوع الرسوم</th>
                                <th>المبلغ</th>
                                <th>رقم المرجع</th>
                                <th>حالة الدفع</th>
                                <th>تاريخ الإنشاء</th>
                                <th>حالة الطلب</th>
                                <th>تم الإنشاء بواسطة</th>
                                <?php if ($_SESSION['committee_role_id'] != 2): ?>
                                    <th>الإجراءات</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($other_fees as $fee): ?>
                                <tr>
                                    <td>
                                        <strong><?= e($fee['fee_type_name'] ?? 'غير محدد') ?></strong>
                                        <?php if ($fee['name']): ?>
                                            <br><small class="text-muted"><?= e($fee['name']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="fw-bold <?= $fee['is_paid'] == 1 ? 'text-success' : 'text-danger' ?>">
                                            <?= number_format($fee['amount']) ?> SDG
                                        </span>
                                        <?php if ($fee['stamp'] > 0): ?>
                                            <br><small class="text-muted">دمغة: <?= number_format($fee['stamp']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($fee['reference']) ?></td>
                                    <td>
                                        <span class="badge <?= $fee['is_paid'] == 1 ? 'bg-success' : 'bg-warning' ?> status-badge">
                                            <?= $fee['is_paid'] == 1 ? 'مدفوع' : 'معلق' ?>
                                        </span>
                                    </td>
                                    <td><?= e($fee['created_at']) ?></td>
                                    <td>
                                        <span class="badge <?= $fee['order_status'] === 'completed' ? 'bg-success' : 'bg-warning' ?> status-badge">
                                            <?= e($fee['order_status'] ?? 'معلق') ?>
                                        </span>
                                    </td>
                                    <td><?= e($fee['user_name'] ?? '—') ?></td>
                                    <?php if ($_SESSION['committee_role_id'] != 2): ?>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <?php if ($fee['is_paid'] == 1): ?>
                                                    <button class="btn btn-outline-success" onclick="printReceipt(<?= $fee['id'] ?>, 'other_fee')">
                                                        <i class="fas fa-print"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <button class="btn btn-outline-danger" onclick="deleteOtherFee(<?= $fee['id'] ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Card 5: Other Payments -->
        <div class="card card-arabic p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="rtl-heading mb-0">مدفوعات الرسوم الأخرى</h4>
                <span class="badge bg-warning"><?= count($other_payments) ?> دفعة</span>
            </div>

            <?php if (empty($other_payments)): ?>
                <div class="text-center text-muted py-4">
                    <i class="fas fa-money-bill-wave fa-2x mb-3"></i>
                    <p>لا توجد مدفوعات للرسوم الأخرى</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>نوع الرسوم</th>
                                <th>المبلغ</th>
                                <th>رقم المرجع</th>
                                <th>رقم المعاملة</th>
                                <th>البنك</th>
                                <th>تاريخ الدفع</th>
                                <?php if ($_SESSION['committee_role_id'] != 2): ?>
                                    <th>الإجراءات</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($other_payments as $payment): ?>
                                <tr>
                                    <td>
                                        <strong><?= e($payment['fee_type_name'] ?? 'غير محدد') ?></strong>
                                        <?php if ($payment['name']): ?>
                                            <br><small class="text-muted"><?= e($payment['name']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="fw-bold text-success"><?= number_format($payment['amount']) ?> SDG</span>
                                        <?php if ($payment['stamp'] > 0): ?>
                                            <br><small class="text-muted">دمغة: <?= number_format($payment['stamp']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($payment['fee_reference'] ?? $payment['reference']) ?></td>
                                    <td><?= e($payment['transaction_ref'] ?? '—') ?></td>
                                    <td><?= e($payment['bank_name'] ?? '—') ?></td>
                                    <td><?= e($payment['created_at']) ?></td>
                                    <?php if ($_SESSION['committee_role_id'] != 2): ?>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <button class="btn btn-outline-success" onclick="printReceipt(<?= $payment['id'] ?>, 'other_payment')">
                                                    <i class="fas fa-print"></i>
                                                </button>
                                                <button class="btn btn-outline-danger" onclick="deleteOtherPayment(<?= $payment['id'] ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </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 editRegistration(registrationId) {
    console.log("Fetching registration ID: " + registrationId);
    
    // Show loading indicator
    $('#editRegistrationModal .modal-body').append('<div id="loadingIndicator" class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x"></i><p>جاري تحميل البيانات...</p></div>');
    
    // Fetch registration data via AJAX
    $.ajax({
        url: 'committee_get_registration.php',
        type: 'GET',
        data: { id: registrationId },
        dataType: 'json',
        timeout: 10000, // 10 second timeout
        success: function(data) {
            console.log("AJAX Response:", data);
            $('#loadingIndicator').remove();
            
            if (data.success) {
                // Populate modal fields
                $('#registration_id').val(data.registration.id);
                $('#start').val(data.registration.start);
                $('#end').val(data.registration.end);
                $('#payment_amount').val(data.registration.payment_amount);
                $('#payment_reference').val(data.registration.payment_reference);
                $('#is_paid').val(data.registration.is_paid);
                $('#semester_id').val(data.registration.semester_id);
                $('#notes').val(data.registration.notes);
                
                // Show the modal
                $('#editRegistrationModal').modal('show');
            } else {
                alert('خطأ في تحميل بيانات التسجيل: ' + (data.message || 'خطأ غير معروف'));
                console.error('Server error:', data.message);
            }
        },
        error: function(xhr, status, error) {
            $('#loadingIndicator').remove();
            console.error('AJAX Error Details:');
            console.error('Status:', status);
            console.error('Error:', error);
            console.error('Response Text:', xhr.responseText);
            console.error('Status Code:', xhr.status);
            
            let errorMessage = 'حدث خطأ في تحميل البيانات. الرجاء المحاولة مرة أخرى.\n';
            errorMessage += 'التفاصيل: ' + status + ' - ' + error;
            
            if (xhr.status === 404) {
                errorMessage += '\nالملف committee_get_registration.php غير موجود';
            } else if (xhr.status === 500) {
                errorMessage += '\nخطأ في السيرفر. الرجاء مراجعة مسؤول النظام';
            }
            
            alert(errorMessage);
        }
    });
}

// Handle form submission
 // Handle form submission
 // Handle form submission
function submitEditForm(event) {
    event.preventDefault();
    console.log("Submitting form...");
    
    // Get form data
    var formData = $('#editRegistrationForm').serialize();
    console.log("Form data:", formData);
    
    // Show loading indicator
    var submitBtn = $(event.target).find('button[type="submit"]');
    var originalText = submitBtn.html();
    submitBtn.html('<i class="fas fa-spinner fa-spin"></i> جاري الحفظ...').prop('disabled', true);
    
    // Submit via AJAX
    $.ajax({
        url: 'committee_update_registration.php',
        type: 'POST',
        data: formData,
        dataType: 'json',
        timeout: 10000,
        success: function(response) {
            submitBtn.html(originalText).prop('disabled', false);
            console.log("Update response:", response);
            
            if (response.success) {
                $('#editRegistrationModal').modal('hide');
                alert('تم تحديث التسجيل بنجاح');
                location.reload();
            } else {
                alert('خطأ: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            submitBtn.html(originalText).prop('disabled', false);
            console.error('Submit Error - Status:', status);
            console.error('Submit Error - Error:', error);
            console.error('Response Text:', xhr.responseText);
            
            // Try to parse the response if it's JSON
            try {
                var response = JSON.parse(xhr.responseText);
                alert('خطأ: ' + response.message);
            } catch(e) {
                alert('حدث خطأ في حفظ البيانات. الرجاء المحاولة مرة أخرى.\n' + error);
            }
        }
    });
    
    return false;
}

function deleteRegistration(registrationId) {
    if (confirm('هل أنت متأكد من حذف هذا التسجيل؟')) {
        window.location.href = 'committee_delete_registration.php?id=' + registrationId + '&student_id=<?= urlencode($correct_student_id) ?>';
    }
}

function deleteStudent() {
    if (confirm('هل أنت متأكد من حذف هذا الطالب بشكل دائم؟\n\nسيتم حذف الطالب من جدول students فقط.\n\nتحذير: هذه العملية لا يمكن التراجع عنها.')) {
        window.location.href = 'committee_delete_student.php?student_id=<?= urlencode($correct_student_id) ?>';
    }
}

function deleteOtherFee(feeId) {
    if (confirm('هل أنت متأكد من حذف هذه الرسوم؟')) {
        window.location.href = 'committee_delete_other_fee.php?id=' + feeId + '&student_id=<?= urlencode($correct_student_id) ?>';
    }
}

function deleteOtherPayment(paymentId) {
    if (confirm('هل أنت متأكد من حذف هذه الدفعة؟')) {
        window.location.href = 'committee_delete_other_payment.php?id=' + paymentId + '&student_id=<?= urlencode($correct_student_id) ?>';
    }
}

function printReceipt(id, type) {
    window.open('committee_print_receipt.php?id=' + id + '&type=' + type, '_blank');
}
</script>

</body>
</html>
