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

// Generate CSRF token if not exists using the correct function name from helpers.php
csrf_token(); // This will set $_SESSION['csrf'] if not exists

// Check user role
$committeeRoleId = (int)($_SESSION['committee_role_id'] ?? 0);
if (!in_array($committeeRoleId, [1, 2])) {
    die("Error: Unauthorized access. Only administrators (role_id=1) and registrars (role_id=2) can access this page.");
}

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

// Validate and sanitize student_id
$student_id = $_GET['student_id'] ?? '';
$student_id = trim($student_id);

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

// Validate student_id format using helper function (if exists) or custom validation
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $student_id)) {
    error_log("Invalid student_id format attempted: " . $student_id);
    die("Error: Invalid student ID format");
}

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

// Function to safely generate alternative formats
function generateSafeAlternativeFormats($student_id) {
    $formats = [];
    $safe_id = preg_replace('/[^a-zA-Z0-9_-]/', '', $student_id);
    
    // Only generate formats from the safe ID
    $formats[] = $safe_id;
    $formats[] = str_replace('-', '', $safe_id);
    $formats[] = str_replace('23-', '', $safe_id);
    $formats[] = '23-' . preg_replace('/[^a-zA-Z0-9]/', '', $safe_id);
    
    // Add dash if missing (for numeric IDs)
    if (preg_match('/^\d+$/', $safe_id) && strlen($safe_id) > 2) {
        $formats[] = substr($safe_id, 0, 2) . '-' . substr($safe_id, 2);
    }
    
    // Remove leading zeros
    $formats[] = ltrim($safe_id, '0');
    
    // Add leading zero
    $formats[] = '0' . $safe_id;
    
    // Filter and return unique values
    $formats = array_unique($formats);
    return array_filter($formats, function($format) {
        return preg_match('/^[a-zA-Z0-9_-]*$/', $format);
    });
}

// First try exact match with prepared statement
$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 safely
    $alternative_formats = generateSafeAlternativeFormats($student_id);
    
    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;
        }
    }
}
$accessCheck->close();

if (!$studentData) {
    // Show comprehensive error with debugging info
    echo "<!DOCTYPE html><html lang='ar' dir='rtl'><head><meta charset='UTF-8'><title>خطأ</title></head><body>";
    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> " . e($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()) {
            $encoded_id = urlencode($sample['student_id']);
            echo "<li><a href='student_profile_admin.php?student_id={$encoded_id}&csrf=" . 
                 urlencode($_SESSION['csrf'] ?? '') . "'>" . 
                 e($sample['student_id']) . " - " . e($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='registration_management.php' class='btn btn-secondary'>Return to Dashboard</a>";
    echo "</div>";
    echo "</div>";
    include 'footer.php';
    die();
}

// Check access permissions using committee_scope() helper
$scope = committee_scope();
if (!$scope['can_all'] && $scope['college_id'] !== null && (int)$studentData['college_id'] !== $scope['college_id']) {
    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 with admission type and specialization
$stmt = $mysqli1->prepare("
    SELECT 
        s.*,
        c.name AS college_name,
        p.name AS program_name,
        sec.name AS section_name,
        sp.specialization_name_ar AS specialization_name,
        co.name AS country_name,
        st.name AS state_name,
        l.name AS locality_name,
        adm.name AS admission_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 specializations sp ON s.specialization_id = sp.specialization_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
    LEFT JOIN admissions adm ON s.admission_id = adm.id
    WHERE s.student_id = ?
");

if (!$stmt) {
    error_log("Prepare failed: " . $mysqli1->error);
    die("Database error occurred");
}

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

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

// Get batch name
$batch_name = 'غير محدد';
if (!empty($data['batch_id'])) {
    $batch_stmt = $mysqli1->prepare("SELECT value FROM batches WHERE id = ?");
    if ($batch_stmt) {
        $batch_stmt->bind_param("i", $data['batch_id']);
        $batch_stmt->execute();
        $batch_result = $batch_stmt->get_result();
        if ($batch_result->num_rows > 0) {
            $batch = $batch_result->fetch_assoc();
            $batch_name = e($batch['value']);
        }
        $batch_stmt->close();
    }
}

// Get gender text
$gender_text = 'غير محدد';
if ($data['gender'] == 1) {
    $gender_text = 'ذكر';
} elseif ($data['gender'] == 2) {
    $gender_text = 'أنثى';
}

// Get admission type (نوع القبول)
$admission_name = 'غير محدد';
if (!empty($data['admission_name'])) {
    $admission_name = e($data['admission_name']);
}

// Format student ID for display using formatStudentId() helper
$formatted_student_id = formatStudentId($correct_student_id);

// Get registration data with discount information
$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
");

if (!$registrations_stmt) {
    error_log("Prepare failed for registrations: " . $mysqli1->error);
    $registrations = [];
} else {
    $registrations_stmt->bind_param("s", $correct_student_id);
    $registrations_stmt->execute();
    $registrations = $registrations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $registrations_stmt->close();
}

// Get payment data with discount information
$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
");

if (!$payment_stmt) {
    error_log("Prepare failed for payments: " . $mysqli1->error);
    $payments = [];
} else {
    $payment_stmt->bind_param("s", $correct_student_id);
    $payment_stmt->execute();
    $payments = $payment_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $payment_stmt->close();
}

// Get discount summary from registrations (where discount > 0)
$discount_summary_stmt = $mysqli1->prepare("
    SELECT 
        r.id,
        r.payment_reference,
        r.semester_id,
        r.study_fees,
        r.registration_fees,
        r.insurance_fees,
        r.payment_amount,
        r.due_amount,
        r.discount,
        r.is_paid,
        r.created_at,
        r.updated_at,
        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
    AND r.discount > 0
    ORDER BY r.created_at DESC
");

if (!$discount_summary_stmt) {
    error_log("Prepare failed for discount summary: " . $mysqli1->error);
    $discount_summary = [];
} else {
    $discount_summary_stmt->bind_param("s", $correct_student_id);
    $discount_summary_stmt->execute();
    $discount_summary = $discount_summary_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $discount_summary_stmt->close();
}

// Get other_fees data
$phone_number = $studentData['phone_number'];
$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
");

if (!$other_fees_stmt) {
    error_log("Prepare failed for other fees: " . $mysqli1->error);
    $other_fees = [];
} else {
    $other_fees_stmt->bind_param("s", $phone_number);
    $other_fees_stmt->execute();
    $other_fees = $other_fees_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $other_fees_stmt->close();
}

// 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
");

if (!$other_payments_stmt) {
    error_log("Prepare failed for other payments: " . $mysqli1->error);
    $other_payments = [];
} else {
    $other_payments_stmt->bind_param("s", $phone_number);
    $other_payments_stmt->execute();
    $other_payments = $other_payments_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $other_payments_stmt->close();
}
?>

<!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">
    <!-- Cairo Font -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <?php base_head_css(); ?>
    <style>
        * {
            font-family: 'Cairo', sans-serif;
        }
        
        body {
            background-color: #f8f9fa;
            direction: rtl;
        }
        
        .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;
            display: flex;
            justify-content: space-between;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-row strong {
            color: #374151;
            font-weight: 600;
        }
        
        .status-badge {
            font-size: 0.8rem;
            padding: 0.4rem 0.8rem;
        }
        
        .table th {
            font-weight: 600;
            background-color: #f8f9fa;
            text-align: right;
        }
        
        .table td {
            text-align: right;
        }
        
        .btn-group-sm > .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        
        .batch-badge {
            background-color: #3b82f6;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            display: inline-block;
        }
        
        .gender-badge {
            background-color: #8b5cf6;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            display: inline-block;
        }
        
        .admission-badge {
            background-color: #10b981;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            display: inline-block;
        }
        
        .specialization-badge {
            background-color: #f59e0b;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            display: inline-block;
        }
        
        /* RTL specific adjustments */
        .me-auto {
            margin-right: auto !important;
            margin-left: 0 !important;
        }
        
        .ms-auto {
            margin-left: auto !important;
            margin-right: 0 !important;
        }
        
        .me-2 {
            margin-right: 0.5rem !important;
            margin-left: 0 !important;
        }
        
        .ms-2 {
            margin-left: 0.5rem !important;
            margin-right: 0 !important;
        }
        
        /* Adjust table for RTL */
        .table {
            text-align: right;
        }
        
        .btn i {
            margin-left: 0.25rem;
            margin-right: 0;
        }
        
        /* Alert positioning */
        .alert {
            text-align: right;
        }
        
        .alert .btn-close {
            margin-left: 0;
            margin-right: -0.5rem;
        }
        
        /* Form control for RTL */
        .form-control {
            text-align: right;
        }
        
        /* Role badge styling */
        .role-badge {
            position: absolute;
            top: 15px;
            left: 15px;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .role-admin {
            background-color: #dc2626;
            color: white;
        }
        
        .role-registrar {
            background-color: #2563eb;
            color: white;
        }
        
        /* Discount styling */
        .discount-badge {
            background-color: #f59e0b;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            display: inline-block;
        }
        
        .discount-value {
            font-size: 1rem;
            font-weight: bold;
            color: #dc2626;
        }
        
        .total-before-discount {
            text-decoration: line-through;
            color: #6b7280;
            font-size: 0.9rem;
        }
        
        .total-after-discount {
            font-size: 1.1rem;
            font-weight: bold;
            color: #10b981;
        }
        
        .discount-label {
            font-size: 0.8rem;
            color: #6b7280;
        }
        
        .no-discount {
            color: #6b7280;
            font-style: italic;
        }
        
        .original-amount {
            font-weight: bold;
            color: #374151;
        }
        
        /* CSRF token hidden */
        .csrf-token {
            display: none;
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>
    
    <div class="container py-4">
        <!-- CSRF Token for forms - using 'csrf' as in helpers.php -->
        <meta name="csrf-token" content="<?= e($_SESSION['csrf'] ?? '') ?>">
        
        <!-- Header with Role Badge -->
        <div class="d-flex align-items-center mb-4 position-relative">
            <h3 class="mb-0 fw-bold">ملف الطالب</h3>
            <div class="me-auto">
                <a class="btn btn-outline-secondary" href="registration_management.php?csrf=<?= urlencode($_SESSION['csrf'] ?? '') ?>">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التسجيل
                </a>
            </div>
            
            <!-- Role Badge -->
            <div class="role-badge <?= $committeeRoleId == 1 ? 'role-admin' : 'role-registrar' ?>">
                <?= $committeeRoleId == 1 ? 'مدير النظام' : 'مسجل الكلية' ?>
            </div>
        </div>

        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?= e($_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">
                <?= e($_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>
                <a href="edit_student_admin.php?student_id=<?= urlencode($correct_student_id) ?>&csrf=<?= urlencode($_SESSION['csrf'] ?? '') ?>" class="btn btn-outline-primary">
                    <i class="fas fa-cog me-2"></i>تعديل البيانات
                </a>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="info-row">
                        <strong>رقم الطالب:</strong> 
                        <code><?= e($formatted_student_id) ?></code>
                    </div>
                    <div class="info-row">
                        <strong>الاسم:</strong> <?= e($data['student_name']) ?>
                    </div>

                    <div class="info-row">
                        <strong>الدفعة:</strong> 
                        <span class="batch-badge"><?= $batch_name ?></span>
                    </div>
                    <div class="info-row">
                        <strong>الجنس:</strong>
                        <span class="gender-badge"><?= $gender_text ?></span>
                    </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>
                        <?php if (!empty($data['specialization_name'])): ?>
                            <span class="specialization-badge"><?= e($data['specialization_name']) ?></span>
                        <?php else: ?>
                            <span class="text-muted">غير محدد</span>
                        <?php endif; ?>
                    </div>
                    <div class="info-row">
                        <strong>نوع القبول:</strong>
                        <span class="admission-badge"><?= $admission_name ?></span>
                    </div>
              
                </div>
            </div>
            
            <!-- Status Information -->
            <div class="row mt-3 border-top pt-3">
                <div class="col-md-4">
                    <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>
                <div class="col-md-4">
                    <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>
                <div class="col-md-4">
                    <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>
                <span class="badge bg-primary"><?= count($registrations) ?> تسجيل</span>
            </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 (in_array($committeeRoleId, [1, 2])): ?>
                                    <th>الإجراءات</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($registrations as $registration): ?>
                                <?php
                                $payment_amount = (float)($registration['payment_amount'] ?? 0);
                                $discount = (float)($registration['discount'] ?? 0);
                                $total_before_discount = $payment_amount + $discount;
                                $has_discount = $discount > 0;
                                ?>
                                <tr>
                                    <td>
                                        <strong><?= e($registration['semester_name'] ?? '—') ?></strong>
                                        <?php if (!empty($registration['semester_code'])): ?>
                                            <br><small class="text-muted"><?= e($registration['semester_code']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($has_discount): ?>
                                            <div>
                                                <span class="total-before-discount">
                                                    <?= number_format($total_before_discount) ?> SDG
                                                </span>
                                            </div>
                                        <?php else: ?>
                                            <div>
                                                <span class="original-amount">
                                                    <?= number_format($payment_amount) ?> SDG
                                                </span>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($has_discount): ?>
                                            <div class="d-flex flex-column">
                                                <span class="discount-value">
                                                    <?= number_format($discount) ?> SDG
                                                </span>
                                                <?php if ($total_before_discount > 0): ?>
                                                    <small class="discount-label">
                                                        <?= number_format(($discount / $total_before_discount) * 100, 1) ?>%
                                                    </small>
                                                <?php endif; ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="no-discount">لا يوجد</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($has_discount): ?>
                                            <div>
                                                <span class="total-after-discount">
                                                    <?= number_format($payment_amount) ?> SDG
                                                </span>
                                            </div>
                                        <?php else: ?>
                                            <div>
                                                <span class="original-amount">
                                                    <?= number_format($payment_amount) ?> SDG
                                                </span>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($registration['payment_reference'] ?? '—') ?></td>
                                    <td>
                                        <span class="badge <?= ($registration['is_paid'] ?? 0) == 1 ? 'bg-success' : 'bg-warning' ?> status-badge">
                                            <?= ($registration['is_paid'] ?? 0) == 1 ? 'مدفوع' : 'معلق' ?>
                                        </span>
                                    </td>
                                    <td><?= e($registration['created_at'] ?? '—') ?></td>
                                    <td><?= e($registration['notes'] ?? '—') ?></td>
                                    <?php if (in_array($committeeRoleId, [1, 2])): ?>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <?php if (($registration['is_paid'] ?? 0) == 1): ?>
                                                    <button class="btn btn-outline-success" onclick="printReceipt(<?= (int)$registration['id'] ?>, 'registration')">
                                                        <i class="fas fa-print"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <a class="btn btn-outline-info" href="create_installments.php?registration_id=<?= (int)$registration['id'] ?>&student_id=<?= urlencode($correct_student_id) ?>&csrf=<?= urlencode($_SESSION['csrf'] ?? '') ?>" title="إدارة الأقساط">
                                                        <i class="fas fa-cog"></i>
                                                    </a>
                                                    <button class="btn btn-outline-danger" onclick="deleteRegistration(<?= (int)$registration['id'] ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </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>
                                <th>التاريخ</th>
                                <?php if (in_array($committeeRoleId, [1, 2])): ?>
                                    <th>الإجراءات</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($payments as $payment): ?>
                                <?php
                                $payment_amount = (float)($payment['payment_amount'] ?? 0);
                                $payment_discount = (float)($payment['discount'] ?? 0);
                                $has_payment_discount = $payment_discount > 0;
                                $total_before_discount = $payment_amount + $payment_discount;
                                ?>
                                <tr>
                                    <td>
                                        <strong><?= e($payment['fee_type_name'] ?? 'غير محدد') ?></strong>
                                        <?php if (!empty($payment['registration_fees']) && $payment['registration_fees'] > 0): ?>
                                            <br><small class="text-muted">تسجيل: <?= number_format($payment['registration_fees']) ?> SDG</small>
                                        <?php endif; ?>
                                        <?php if (!empty($payment['insurance_fees']) && $payment['insurance_fees'] > 0): ?>
                                            <br><small class="text-muted">تأمين: <?= number_format($payment['insurance_fees']) ?> SDG</small>
                                        <?php endif; ?>
                                        <?php if (!empty($payment['study_fees']) && $payment['study_fees'] > 0): ?>
                                            <br><small class="text-muted">دراسية: <?= number_format($payment['study_fees']) ?> SDG</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($has_payment_discount): ?>
                                            <div class="d-flex flex-column">
                                                <span class="total-before-discount">
                                                    <?= number_format($total_before_discount) ?> SDG
                                                </span>
                                                <span class="fw-bold text-success total-after-discount">
                                                    <?= number_format($payment_amount) ?> SDG
                                                </span>
                                            </div>
                                        <?php else: ?>
                                            <div>
                                                <span class="fw-bold text-success">
                                                    <?= number_format($payment_amount) ?> SDG
                                                </span>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($has_payment_discount): ?>
                                            <div class="d-flex flex-column">
                                                <span class="discount-value">
                                                    <?= number_format($payment_discount) ?> SDG
                                                </span>
                                                <?php if ($total_before_discount > 0): ?>
                                                    <small class="discount-label">
                                                        <?= number_format(($payment_discount / $total_before_discount) * 100, 1) ?>%
                                                    </small>
                                                <?php endif; ?>
                                            </div>
                                        <?php else: ?>
                                            <span class="no-discount">لا يوجد</span>
                                        <?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 (!empty($payment['semester_code'])): ?>
                                            <br><small class="text-muted"><?= e($payment['semester_code']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($payment['created_at'] ?? '—') ?></td>
                                    <?php if (in_array($committeeRoleId, [1, 2])): ?>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <button class="btn btn-outline-success" onclick="printReceipt(<?= (int)$payment['id'] ?>, 'payment')">
                                                    <i class="fas fa-print"></i>
                                                </button>
                                                <?php if ($committeeRoleId == 1): // Only admin can delete ?>
                                                    <button class="btn btn-outline-danger" onclick="deletePayment(<?= (int)$payment['id'] ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Card 4: Discount Summary -->
        <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($discount_summary) ?> تخفيض</span>
            </div>

            <?php if (empty($discount_summary)): ?>
                <div class="text-center text-muted py-4">
                    <i class="fas fa-percentage 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>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $total_before_discount_all = 0;
                            $total_discount_all = 0;
                            $total_after_discount_all = 0;
                            ?>
                            <?php foreach ($discount_summary as $discount): ?>
                                <?php
                                $payment_amount = (float)($discount['payment_amount'] ?? 0);
                                $discount_amount = (float)($discount['discount'] ?? 0);
                                $total_before_discount = $payment_amount + $discount_amount;
                                $discount_percentage = $total_before_discount > 0 ? ($discount_amount / $total_before_discount) * 100 : 0;
                                
                                $total_before_discount_all += $total_before_discount;
                                $total_discount_all += $discount_amount;
                                $total_after_discount_all += $payment_amount;
                                ?>
                                <tr>
                                    <td>
                                        <strong><?= e($discount['semester_name'] ?? '—') ?></strong>
                                        <?php if (!empty($discount['semester_code'])): ?>
                                            <br><small class="text-muted"><?= e($discount['semester_code']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($discount['payment_reference'] ?? '—') ?></td>
                                    <td>
                                        <span class="total-before-discount">
                                            <?= number_format($total_before_discount) ?> SDG
                                        </span>
                                    </td>
                                    <td>
                                        <span class="discount-value">
                                            <?= number_format($discount_amount) ?> SDG
                                        </span>
                                    </td>
                                    <td>
                                        <span class="total-after-discount">
                                            <?= number_format($payment_amount) ?> SDG
                                        </span>
                                    </td>
                                    <td>
                                        <span class="fw-bold text-danger">
                                            <?= number_format($discount_percentage, 1) ?>%
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge <?= ($discount['is_paid'] ?? 0) == 1 ? 'bg-success' : 'bg-warning' ?> status-badge">
                                            <?= ($discount['is_paid'] ?? 0) == 1 ? 'مدفوع' : 'معلق' ?>
                                        </span>
                                    </td>
                                    <td><?= e($discount['created_at'] ?? '—') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <?php 
                            $total_discount_percentage = $total_before_discount_all > 0 ? ($total_discount_all / $total_before_discount_all) * 100 : 0;
                            ?>
                            <tr class="table-light">
                                <td colspan="2" class="text-end fw-bold">المجموع:</td>
                                <td class="fw-bold">
                                    <span class="total-before-discount">
                                        <?= number_format($total_before_discount_all) ?> SDG
                                    </span>
                                </td>
                                <td class="fw-bold">
                                    <span class="discount-value">
                                        <?= number_format($total_discount_all) ?> SDG
                                    </span>
                                </td>
                                <td class="fw-bold">
                                    <span class="total-after-discount">
                                        <?= number_format($total_after_discount_all) ?> SDG
                                    </span>
                                </td>
                                <td class="fw-bold">
                                    <span class="text-danger">
                                        <?= number_format($total_discount_percentage, 1) ?>%
                                    </span>
                                </td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Card 5: 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 (in_array($committeeRoleId, [1, 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 (!empty($fee['name'])): ?>
                                            <br><small class="text-muted"><?= e($fee['name']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="fw-bold <?= ($fee['is_paid'] ?? 0) == 1 ? 'text-success' : 'text-danger' ?>">
                                            <?= number_format($fee['amount'] ?? 0) ?> SDG
                                        </span>
                                        <?php if (!empty($fee['stamp']) && $fee['stamp'] > 0): ?>
                                            <br><small class="text-muted">دمغة: <?= number_format($fee['stamp']) ?> SDG</small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($fee['reference'] ?? '—') ?></td>
                                    <td>
                                        <span class="badge <?= ($fee['is_paid'] ?? 0) == 1 ? 'bg-success' : 'bg-warning' ?> status-badge">
                                            <?= ($fee['is_paid'] ?? 0) == 1 ? 'مدفوع' : 'معلق' ?>
                                        </span>
                                    </td>
                                    <td><?= e($fee['created_at'] ?? '—') ?></td>
                                    <td>
                                        <span class="badge <?= ($fee['order_status'] ?? 'pending') === 'completed' ? 'bg-success' : 'bg-warning' ?> status-badge">
                                            <?= e($fee['order_status'] ?? 'معلق') ?>
                                        </span>
                                    </td>
                                    <td><?= e($fee['user_name'] ?? '—') ?></td>
                                    <?php if (in_array($committeeRoleId, [1, 2])): ?>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <?php if (($fee['is_paid'] ?? 0) == 1): ?>
                                                    <button class="btn btn-outline-success" onclick="printReceipt(<?= (int)$fee['id'] ?>, 'other_fee')">
                                                        <i class="fas fa-print"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <?php if ($committeeRoleId == 1): // Only admin can delete ?>
                                                    <button class="btn btn-outline-danger" onclick="deleteOtherFee(<?= (int)$fee['id'] ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Card 6: 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 (in_array($committeeRoleId, [1, 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 (!empty($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'] ?? 0) ?> SDG</span>
                                        <?php if (!empty($payment['stamp']) && $payment['stamp'] > 0): ?>
                                            <br><small class="text-muted">دمغة: <?= number_format($payment['stamp']) ?> SDG</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 (in_array($committeeRoleId, [1, 2])): ?>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <button class="btn btn-outline-success" onclick="printReceipt(<?= (int)$payment['id'] ?>, 'other_payment')">
                                                    <i class="fas fa-print"></i>
                                                </button>
                                                <?php if ($committeeRoleId == 1): // Only admin can delete ?>
                                                    <button class="btn btn-outline-danger" onclick="deleteOtherPayment(<?= (int)$payment['id'] ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </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>
    // Get CSRF token from meta tag - using 'csrf' as in helpers.php
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

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

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

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

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

    function printReceipt(id, type) {
        window.open('committee_print_receipt.php?id=' + id + '&type=' + type + 
                   '&csrf=' + encodeURIComponent(csrfToken), '_blank');
    }
    </script>
</body>
</html>
<?php include 'footer.php'; ?>