<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../helpers.php';

// Check committee access (session is already started in header/db)
if (!isset($_SESSION['committee_id'])) {
    header('Location: ../login.php');
    exit;
}

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;

// Get filter parameters
$current_semester = $_GET['semester'] ?? '';
$college_id = $_GET['college_id'] ?? null;
$section_id = $_GET['section_id'] ?? null;
$batch_id = $_GET['batch_id'] ?? null;

// Build query conditions for partially registered students
// Students who have is_paid = 0 but payment_amount > 0
$where = "WHERE r.id IS NOT NULL AND r.is_paid = 0 AND r.payment_amount > 0";
$params = [];
$types = "";

if (!empty($current_semester)) {
    $where .= " AND r.semester_id = ?";
    $params[] = $current_semester;
    $types .= "i";
} else {
    // If no semester selected, get the latest semester
    $current_semester_query = $mysqli1->query("SELECT id FROM semesters WHERE deleted_at IS NULL ORDER BY created_at DESC LIMIT 1");
    if ($current_semester_query->num_rows > 0) {
        $current_semester = $current_semester_query->fetch_assoc()['id'];
        $where .= " AND r.semester_id = ?";
        $params[] = $current_semester;
        $types .= "i";
    }
}

if ($college_id) {
    $where .= " AND s.college_id = ?";
    $params[] = $college_id;
    $types .= "i";
}

if ($section_id) {
    $where .= " AND s.section_id = ?";
    $params[] = $section_id;
    $types .= "i";
}

if ($batch_id) {
    $where .= " AND s.batch_id = ?";
    $params[] = $batch_id;
    $types .= "i";
}

// Query for partially registered students
$sql = "SELECT 
    s.student_id,
    s.student_name,
    s.student_name_eng,
    sec.name as section_name,
    b.value as batch_name,
    prog.name as program_name,
    c.name as college_name,
    sem.name as semester_name,
    r.payment_amount as total_paid,
    r.study_fees,
    r.registration_fees,
    r.insurance_fees,
    r.discount,
    r.penalty,
    r.stamp,
    r.payment_reference,
    r.is_paid,
    (COALESCE(r.study_fees, 0) + COALESCE(r.registration_fees, 0) + COALESCE(r.insurance_fees, 0) + COALESCE(r.penalty, 0) + COALESCE(r.stamp, 0) - COALESCE(r.discount, 0)) as total_fees,
    ((COALESCE(r.study_fees, 0) + COALESCE(r.registration_fees, 0) + COALESCE(r.insurance_fees, 0) + COALESCE(r.penalty, 0) + COALESCE(r.stamp, 0) - COALESCE(r.discount, 0)) - COALESCE(r.payment_amount, 0)) as remaining_amount
FROM students s
LEFT JOIN sections sec ON sec.id = s.section_id
LEFT JOIN batches b ON b.id = s.batch_id
LEFT JOIN programs prog ON prog.id = s.program_id
LEFT JOIN colleges c ON c.id = s.college_id
LEFT JOIN registrations r ON r.student_id = s.student_id
LEFT JOIN semesters sem ON sem.id = r.semester_id
$where
ORDER BY remaining_amount DESC, s.student_id DESC";

$st = $mysqli1->prepare($sql);
if ($types && !empty($params)) {
    $st->bind_param($types, ...$params);
}
$st->execute();
$students = $st->get_result()->fetch_all(MYSQLI_ASSOC);
$st->close();

// Include header with correct path
include __DIR__ . '/../header.php';
?>

<div class="container py-4">
    <div class="d-flex align-items-center mb-4">
        <a href="../committee_dashboard.php" class="btn btn-outline-secondary btn-sm me-3">
            <i class="fas fa-arrow-right me-1"></i>
            العودة للوحة التحكم
        </a>
        <h4 class="mb-0 fw-bold">تقرير الطلاب المسجلين جزئياً</h4>
        <div class="ms-auto">
            <span class="chip orange">العدد: <?= number_format(count($students)) ?></span>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4 d-print-none filters">
        <div class="card-body">
            <form method="get" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label fw-semibold">الكلية:</label>
                    <select name="college_id" class="form-select">
                        <option value="">جميع الكليات</option>
                        <?php
                        $colleges = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
                        while ($college = $colleges->fetch_assoc()) {
                            $selected = $college_id == $college['id'] ? 'selected' : '';
                            echo "<option value=\"{$college['id']}\" $selected>" . e($college['name']) . "</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-semibold">القسم:</label>
                    <select name="section_id" class="form-select">
                        <option value="">جميع الأقسام</option>
                        <?php
                        $sections = $mysqli1->query("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
                        while ($section = $sections->fetch_assoc()) {
                            $selected = $section_id == $section['id'] ? 'selected' : '';
                            echo "<option value=\"{$section['id']}\" $selected>" . e($section['name']) . "</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-semibold">الدفعة:</label>
                    <select name="batch_id" class="form-select">
                        <option value="">جميع الدفعات</option>
                        <?php
                        $batches = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id DESC");
                        while ($batch = $batches->fetch_assoc()) {
                            $selected = $batch_id == $batch['id'] ? 'selected' : '';
                            echo "<option value=\"{$batch['id']}\" $selected>" . e($batch['value']) . "</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-semibold">الفصل الدراسي:</label>
                    <select name="semester" class="form-select">
                        <option value="">جميع الفصول</option>
                        <?php
                        $semesters = $mysqli1->query("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY created_at DESC");
                        while ($semester = $semesters->fetch_assoc()) {
                            $selected = $current_semester == $semester['id'] ? 'selected' : '';
                            echo "<option value=\"{$semester['id']}\" $selected>" . e($semester['name'] . ' (' . $semester['code'] . ')') . "</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="fas fa-filter me-1"></i>
                        تطبيق الفلتر
                    </button>
                    <a href="partially_registered.php" class="btn btn-outline-secondary">
                        <i class="fas fa-sync-alt me-1"></i>
                        إعادة تعيين
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- Report Data -->
    <div class="card main-report">
        <div class="card-header bg-warning text-dark">
            <h5 class="mb-0">
                <i class="fas fa-exclamation-circle me-2"></i>
                الطلاب المسجلين جزئياً
                <?php if (!empty($current_semester)): ?>
                    - <?= e($students[0]['semester_name'] ?? 'الفصل المحدد') ?>
                <?php endif; ?>
            </h5>
        </div>
        <div class="card-body">
            <!-- Normal View Table -->
            <div class="table-responsive d-print-none">
                <table class="table table-striped table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>الرقم الجامعي</th>
                            <th>اسم الطالب</th>
                            <th class="text-end">المدفوع</th>
                            <th class="text-end">المتبقي</th>
                            <th class="text-end">الإجمالي</th>
                            <th>نسبة السداد</th>
                            <th>حالة السداد</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($students)): ?>
                            <tr>
                                <td colspan="9" class="text-center text-muted py-4">
                                    <i class="fas fa-info-circle me-2"></i>
                                    لا توجد بيانات للعرض
                                    <br>
                                    <small class="text-muted">(لا يوجد طلاب مسجلين جزئياً بالمعايير المحددة)</small>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($students as $index => $student): ?>
                                <?php
                                $total_fees = $student['total_fees'];
                                $total_paid = $student['total_paid'];
                                $remaining = $student['remaining_amount'];
                                $completion_rate = $total_fees > 0 ? ($total_paid / $total_fees) * 100 : 0;
                                
                                // Determine status color
                                if ($completion_rate >= 80) {
                                    $status_color = 'bg-success';
                                    $status_text = 'شبه مكتمل';
                                } elseif ($completion_rate >= 50) {
                                    $status_color = 'bg-info';
                                    $status_text = 'متوسط السداد';
                                } elseif ($completion_rate >= 25) {
                                    $status_color = 'bg-warning';
                                    $status_text = 'قليل السداد';
                                } else {
                                    $status_color = 'bg-danger';
                                    $status_text = 'متدني السداد';
                                }
                                ?>
                                <tr>
                                    <td class="fw-bold"><?= $index + 1 ?></td>
                                    <td><code><?= e($student['student_id']) ?></code></td>
                                    <td><?= e($student['student_name'] ?: $student['student_name_eng']) ?></td>
                                    <td class="text-end fw-bold text-success">
                                        <?= number_format($total_paid, 2) ?> ر.س
                                    </td>
                                    <td class="text-end fw-bold text-danger">
                                        <?= number_format($remaining, 2) ?> ر.س
                                    </td>
                                    <td class="text-end fw-bold text-primary">
                                        <?= number_format($total_fees, 2) ?> ر.س
                                    </td>
                                    <td>
                                        <div class="progress" style="height: 20px; min-width: 100px;">
                                            <div class="progress-bar <?= $status_color ?>" 
                                                 style="width: <?= $completion_rate ?>%"
                                                 title="<?= number_format($completion_rate, 1) ?>%">
                                                <?= number_format($completion_rate, 1) ?>%
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge <?= $status_color ?>"><?= $status_text ?></span>
                                    </td>
                                    <td>
                                        <a href="../committee_student_profile.php?student_id=<?= urlencode($student['student_id']) ?>" 
                                           class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-eye me-1"></i>
                                            عرض الملف
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Print View Table -->
            <div class="table-responsive d-none d-print-block">
                <!-- Print Header -->
                <div class="print-header">
                    <div class="print-banner">
                        <img src="../img/banar3.jpg" alt="Banner" onerror="this.style.display='none'">
                    </div>
                    <div class="print-title">
                        قائمة الطلاب المسجلين جزئياً
                    </div>
                </div>
                
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="50">#</th>
                            <th width="120">الرقم الجامعي</th>
                            <th>اسم الطالب</th>
                            <th width="100" class="text-end">المدفوع</th>
                            <th width="100" class="text-end">المتبقي</th>
                            <th width="100" class="text-end">الإجمالي</th>
                            <th width="80" class="text-center">نسبة السداد</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($students)): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-4">
                                    لا توجد بيانات للعرض
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($students as $index => $student): ?>
                                <?php
                                $total_fees = $student['total_fees'];
                                $total_paid = $student['total_paid'];
                                $completion_rate = $total_fees > 0 ? ($total_paid / $total_fees) * 100 : 0;
                                ?>
                                <tr>
                                    <td class="fw-bold text-center"><?= $index + 1 ?></td>
                                    <td class="text-center"><?= e($student['student_id']) ?></td>
                                    <td><?= e($student['student_name'] ?: $student['student_name_eng']) ?></td>
                                    <td class="text-end"><?= number_format($total_paid, 2) ?> ر.س</td>
                                    <td class="text-end text-danger"><?= number_format($student['remaining_amount'], 2) ?> ر.س</td>
                                    <td class="text-end"><?= number_format($total_fees, 2) ?> ر.س</td>
                                    <td class="text-center fw-bold"><?= number_format($completion_rate, 1) ?>%</td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Summary -->
            <?php if (!empty($students)): ?>
            <div class="mt-4 border-top pt-3 d-print-none">
                <div class="row">
                    <div class="col-md-3">
                        <div class="dash-card text-center">
                            <div class="n text-warning"><?= number_format(count($students)) ?></div>
                            <div>إجمالي الطلاب المسجلين جزئياً</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="dash-card text-center">
                            <div class="n text-success">
                                <?php
                                $totalPaid = array_sum(array_column($students, 'total_paid'));
                                echo number_format($totalPaid, 2);
                                ?> ر.س
                            </div>
                            <div>إجمالي المبالغ المدفوعة</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="dash-card text-center">
                            <div class="n text-danger">
                                <?php
                                $totalRemaining = array_sum(array_column($students, 'remaining_amount'));
                                echo number_format($totalRemaining, 2);
                                ?> ر.س
                            </div>
                            <div>إجمالي المبالغ المتبقية</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="dash-card text-center">
                            <div class="n text-info">
                                <?php
                                $totalFees = array_sum(array_column($students, 'total_fees'));
                                $avgCompletion = $totalFees > 0 ? ($totalPaid / $totalFees) * 100 : 0;
                                echo number_format($avgCompletion, 1);
                                ?>%
                            </div>
                            <div>متوسط نسبة السداد</div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Export Options -->
            <div class="mt-4 border-top pt-3 d-print-none">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        <i class="fas fa-info-circle me-1"></i>
                        آخر تحديث: <?= date('Y-m-d H:i:s') ?>
                    </div>
                    <div>
                        <button class="btn btn-success btn-sm" onclick="exportToExcel()">
                            <i class="fas fa-file-excel me-1"></i>
                            تصدير لإكسل
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="printReport()">
                            <i class="fas fa-print me-1"></i>
                            طباعة
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
@media print {
    .d-print-none,
    .btn,
    .card-header,
    .filters,
    .dash-card,
    .border-top,
    .text-muted,
    .chip,
    .d-flex.mb-4,
    .card:not(.main-report) {
        display: none !important;
    }
    
    .d-print-block {
        display: block !important;
    }
    
    .table-responsive {
        overflow: visible !important;
    }
    
    .card, 
    .card-body {
        border: none !important;
        box-shadow: none !important;
        padding: 0 !important;
        margin: 0 !important;
    }
    
    .container {
        max-width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
    }
    
    .table {
        font-size: 12px;
        width: 100% !important;
        border: 1px solid #dee2e6;
    }
    
    .table th {
        background-color: #f8f9fa !important;
        border: 1px solid #dee2e6 !important;
        font-weight: bold;
    }
    
    .table td {
        border: 1px solid #dee2e6 !important;
    }
    
    body {
        padding: 10mm !important;
        margin: 0 !important;
        font-family: 'Cairo', sans-serif;
        direction: rtl;
    }
    
    table { 
        page-break-inside: auto;
    }
    tr { 
        page-break-inside: avoid; 
        page-break-after: auto;
    }

    /* Print Header Styles */
    .print-header {
        text-align: center;
        margin-bottom: 20px;
        page-break-after: avoid;
    }
    .print-banner {
        width: 70%;
        margin: 0 auto 10px auto;
    }
    .print-banner img {
        width: 100%;
        height: auto;
        display: block;
        max-height: 80px;
        object-fit: contain;
    }
    .print-title {
        font-size: 22px;
        font-weight: 700;
        margin: 10px 0;
        color: #333;
        font-family: 'Cairo', sans-serif;
    }
}

.orange {
    background-color: #ffa726;
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: bold;
}

.progress {
    background-color: #e9ecef;
    border-radius: 4px;
    overflow: hidden;
}

.progress-bar {
    transition: width 0.6s ease;
    font-size: 12px;
    line-height: 20px;
}

.dash-card {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    border: 1px solid #dee2e6;
}

.dash-card .n {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
}

.chip {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: bold;
}
</style>

<script>
function exportToExcel() {
    // Simple table export implementation
    const table = document.querySelector('.table-responsive.d-print-none table');
    const html = table.outerHTML;
    const url = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'الطلاب_المسجلين_جزئياً.xls';
    link.click();
}

 function printReport() {
    // Create a new window for printing
    const printWindow = window.open('', '_blank');
    
    // Get the print table HTML
    const printTable = document.querySelector('.d-print-block').innerHTML;
    
    // Create the print content
    const printContent = `
        <!DOCTYPE html>
        <html dir="rtl">
        <head>
            <meta charset="UTF-8">
            <title>قائمة الطلاب المسجلين جزئياً</title>
            <style>
                @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap');
                
                body {
                    font-family: 'Cairo', sans-serif;
                    margin: 10mm;
                    direction: rtl;
                }
                .print-header {
                    text-align: center;
                    margin-bottom: 20px;
                }
                .print-banner {
                    width: 70%;
                    margin: 0 auto 10px auto;
                }
                .print-banner img {
                    width: 100%;
                    height: auto;
                    display: block;
                    max-height: 80px;
                    object-fit: contain;
                }
                .print-title {
                    font-size: 22px;
                    font-weight: 700;
                    margin: 10px 0;
                    color: #333;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                    font-size: 12px;
                }
                th, td {
                    border: 1px solid #000;
                    padding: 6px 8px;
                    text-align: center;
                }
                th {
                    background-color: #f5f5f5;
                    font-weight: bold;
                }
                .text-end {
                    text-align: left;
                }
                .text-center {
                    text-align: center;
                }
                .no-data {
                    text-align: center;
                    padding: 20px;
                    color: #666;
                }
                @media print {
                    body { margin: 10mm; }
                }
            </style>
        </head>
        <body>
            ${printTable}
        </body>
        </html>
    `;
    
    printWindow.document.write(printContent);
    printWindow.document.close();
    
    // Wait for content to load then print
    printWindow.onload = function() {
        printWindow.print();
        // Optional: close window after printing
        setTimeout(() => printWindow.close(), 500);
    };
}
</script>

<?php include __DIR__ . '/../footer.php'; ?>