<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';

$auth = new Auth();
if (!$auth->isLoggedIn() || (!$auth->hasPermission('manage_students') && !$auth->hasRole('admin'))) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();

function getSemesterName($number) {
    switch ((int)$number) {
        case 1: return 'الفصل الأول';
        case 2: return 'الفصل الثاني';
        case 3: return 'الفصل الثالث';
        case 4: return 'الفصل الرابع';
        case 5: return 'الفصل الخامس';
        case 6: return 'الفصل السادس';
        case 7: return 'الفصل السابع';
        case 8: return 'الفصل الثامن';
        default: return 'فصل ' . (int)$number;
    }
}

$student_id = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;
$message = '';

if ($student_id && !$auth->canAccessStudent($student_id)) {
    header('Location: students.php');
    exit;
}

// معالجة الإضافة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $student_id_post = (int)($_POST['student_id'] ?? 0);
    $semester_id = (int)($_POST['semester_id'] ?? 0);
    $fee_type = $_POST['fee_type'] ?? 'tuition';
    $amount = (float)($_POST['amount'] ?? 0);
    $due_date = $_POST['due_date'] ?? null;
    
    if ($student_id_post && $semester_id && $amount > 0) {
        if ($auth->canAccessStudent($student_id_post)) {
            try {
                $db->query(
                    "INSERT INTO fees (student_id, semester_id, fee_type, amount, due_date) 
                     VALUES (?, ?, ?, ?, ?)",
                    [$student_id_post, $semester_id, $fee_type, $amount, $due_date]
                );
                $message = '<div class="alert alert-success">تم إضافة الرسوم بنجاح</div>';
            } catch (PDOException $e) {
                $message = '<div class="alert alert-error">خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>';
            }
        }
    }
}

// معالجة السداد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'pay') {
    $fee_id = (int)($_POST['fee_id'] ?? 0);
    $paid_amount = (float)($_POST['paid_amount'] ?? 0);
    
    $fee = $db->fetchOne(
        "SELECT f.*, s.college_id FROM fees f JOIN students s ON f.student_id = s.id WHERE f.id = ?",
        [$fee_id]
    );
    
    if ($fee && $auth->canAccessStudent($fee['student_id'])) {
        $new_paid = (float)$fee['paid_amount'] + $paid_amount;
        $status = 'partial';
        
        if ($new_paid >= $fee['amount']) {
            $status = 'paid';
            $new_paid = $fee['amount'];
        } elseif ($new_paid > 0) {
            $status = 'partial';
        }
        
        $db->query(
            "UPDATE fees SET paid_amount = ?, payment_status = ?, payment_date = CURDATE() WHERE id = ?",
            [$new_paid, $status, $fee_id]
        );
        
        $message = '<div class="alert alert-success">تم تحديث السداد بنجاح</div>';
    }
}

// جلب الرسوم
if ($student_id) {
    if ($auth->hasRole('admin')) {
        $fees = $db->fetchAll(
            "SELECT f.*, s.student_number, s.full_name_ar, sem.academic_year, sem.semester_number
             FROM fees f
             JOIN students s ON f.student_id = s.id
             JOIN semesters sem ON f.semester_id = sem.id
             WHERE f.student_id = ?
             ORDER BY f.created_at DESC",
            [$student_id]
        );
    } else {
        $fees = $db->fetchAll(
            "SELECT f.*, s.student_number, s.full_name_ar, sem.academic_year, sem.semester_number
             FROM fees f
             JOIN students s ON f.student_id = s.id
             JOIN semesters sem ON f.semester_id = sem.id
             WHERE f.student_id = ? AND s.college_id = ?
             ORDER BY f.created_at DESC",
            [$student_id, $_SESSION['college_id']]
        );
    }
} else {
    if ($auth->hasRole('admin')) {
        $fees = $db->fetchAll(
            "SELECT f.*, s.student_number, s.full_name_ar, sem.academic_year, sem.semester_number
             FROM fees f
             JOIN students s ON f.student_id = s.id
             JOIN semesters sem ON f.semester_id = sem.id
             ORDER BY f.created_at DESC"
        );
    } else {
        $fees = $db->fetchAll(
            "SELECT f.*, s.student_number, s.full_name_ar, sem.academic_year, sem.semester_number
             FROM fees f
             JOIN students s ON f.student_id = s.id
             JOIN semesters sem ON f.semester_id = sem.id
             WHERE s.college_id = ?
             ORDER BY f.created_at DESC",
            [$_SESSION['college_id']]
        );
    }
}

// جلب الطلاب للقائمة المنسدلة
if ($auth->hasRole('admin')) {
    $students = $db->fetchAll("SELECT s.* FROM students s ORDER BY s.student_number");
} else {
    $students = $db->fetchAll(
        "SELECT s.* FROM students s WHERE s.college_id = ? ORDER BY s.student_number",
        [$_SESSION['college_id']]
    );
}

// جلب الفصول
if ($auth->hasRole('admin')) {
    $semesters = $db->fetchAll(
        "SELECT s.*, m.college_id FROM semesters s 
         JOIN majors m ON s.major_id = m.id 
         ORDER BY s.academic_year, s.semester_number"
    );
} else {
    $semesters = $db->fetchAll(
        "SELECT s.*, m.college_id FROM semesters s 
         JOIN majors m ON s.major_id = m.id 
         WHERE m.college_id = ?
         ORDER BY s.academic_year, s.semester_number",
        [$_SESSION['college_id']]
    );
}
?>
<!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>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h2>إدارة الرسوم الدراسية</h2>
            <?php if ($student_id): ?>
                <a href="student_details.php?id=<?php echo $student_id; ?>" class="btn btn-secondary">العودة</a>
            <?php endif; ?>
            <button onclick="document.getElementById('addForm').style.display='block'" class="btn btn-primary">إضافة رسوم</button>
        </div>
        
        <?php echo $message; ?>
        
        <!-- قسم البحث -->
        <div class="card" style="margin-bottom: 20px;">
            <div class="card-header">
                <h3>🔍 البحث عن طالب</h3>
            </div>
            <div style="padding: 20px;">
                <div class="form-group" style="position: relative; display: inline-block; width: 100%; max-width: 600px;">
                    <label for="searchInput" style="display: block; margin-bottom: 8px; font-weight: bold;">
                        ابحث عن طالب:
                    </label>
                    <div style="position: relative; display: flex; align-items: center;">
                        <input type="text" 
                               id="searchInput" 
                               placeholder="ابحث بالرقم الجامعي أو الاسم..."
                               style="padding: 10px 40px 10px 10px; width: 100%; border: 1px solid #ddd; border-radius: 4px; font-size: 16px;"
                               onkeyup="filterFees()">
                        <button type="button" 
                                id="clearSearchBtn" 
                                onclick="clearSearch()" 
                                style="position: absolute; left: 10px; background: #f44336; color: white; border: none; border-radius: 50%; width: 28px; height: 28px; cursor: pointer; display: none; font-size: 16px; line-height: 1;"
                                title="مسح البحث">
                            ×
                        </button>
                    </div>
                    <small style="display: block; margin-top: 5px; color: #666;">
                        يمكنك البحث بالرقم الجامعي أو الاسم
                    </small>
                </div>
                <div id="searchResults" style="margin-top: 10px; color: #666; font-size: 14px;"></div>
            </div>
        </div>
        
        <div id="addForm" class="card" style="display:none; margin-bottom: 20px;">
            <div class="card-header">
                <h3>إضافة رسوم جديدة</h3>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="form-group">
                    <label>الطالب</label>
                    <select name="student_id" required>
                        <option value="">اختر الطالب</option>
                        <?php foreach ($students as $student): ?>
                            <option value="<?php echo $student['id']; ?>" <?php echo $student['id'] == $student_id ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($student['student_number'] . ' - ' . $student['full_name_ar']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>الفصل الدراسي</label>
                    <select name="semester_id" required>
                        <option value="">اختر الفصل</option>
                        <?php foreach ($semesters as $sem): ?>
                            <option value="<?php echo $sem['id']; ?>">
                                فصل <?php echo $sem['semester_number']; ?> - <?php echo htmlspecialchars($sem['academic_year']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>نوع الرسوم</label>
                    <select name="fee_type" required>
                        <option value="tuition">رسوم دراسية</option>
                        <option value="registration">رسوم تسجيل</option>
                        <option value="other">أخرى</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>المبلغ</label>
                    <input type="number" name="amount" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label>تاريخ الاستحقاق</label>
                    <input type="date" name="due_date">
                </div>
                <button type="submit" class="btn btn-success">إضافة</button>
                <button type="button" onclick="document.getElementById('addForm').style.display='none'" class="btn btn-secondary">إلغاء</button>
            </form>
        </div>
        
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>الطالب</th>
                        <th>الفصل</th>
                        <th>نوع الرسوم</th>
                        <th>المبلغ</th>
                        <th>المسدد</th>
                        <th>المتبقي</th>
                        <th>الحالة</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody id="feesTableBody">
                    <?php foreach ($fees as $fee): ?>
                        <tr data-student-number="<?php echo htmlspecialchars($fee['student_number']); ?>"
                            data-student-name="<?php echo htmlspecialchars($fee['full_name_ar']); ?>">
                            <td><?php echo htmlspecialchars($fee['student_number'] . ' - ' . $fee['full_name_ar']); ?></td>
                            <td><?php echo getSemesterName($fee['semester_number']); ?> - <?php echo htmlspecialchars($fee['academic_year']); ?></td>
                            <td><?php 
                                $types = ['tuition' => 'رسوم دراسية', 'registration' => 'رسوم تسجيل', 'other' => 'أخرى'];
                                echo $types[$fee['fee_type']] ?? $fee['fee_type'];
                            ?></td>
                            <td><?php echo number_format($fee['amount'], 2); ?></td>
                            <td><?php echo number_format($fee['paid_amount'], 2); ?></td>
                            <td><?php echo number_format($fee['amount'] - $fee['paid_amount'], 2); ?></td>
                            <td><?php 
                                $status = ['pending' => 'غير مسدد', 'partial' => 'جزئي', 'paid' => 'مسدد'];
                                echo $status[$fee['payment_status']] ?? $fee['payment_status'];
                            ?></td>
                            <td>
                                <?php if ($fee['payment_status'] != 'paid'): ?>
                                    <button onclick="document.getElementById('pay_<?php echo $fee['id']; ?>').style.display='block'" class="btn btn-success">سداد</button>
                                    
                                    <div id="pay_<?php echo $fee['id']; ?>" style="display:none; margin-top:10px;">
                                        <form method="POST">
                                            <input type="hidden" name="action" value="pay">
                                            <input type="hidden" name="fee_id" value="<?php echo $fee['id']; ?>">
                                            <div class="form-group">
                                                <label>المبلغ المدفوع</label>
                                                <input type="number" name="paid_amount" step="0.01" min="0" max="<?php echo $fee['amount'] - $fee['paid_amount']; ?>" required>
                                            </div>
                                            <button type="submit" class="btn btn-success">تسجيل السداد</button>
                                            <button type="button" onclick="document.getElementById('pay_<?php echo $fee['id']; ?>').style.display='none'" class="btn btn-secondary">إلغاء</button>
                                        </form>
                                    </div>
                                <?php else: ?>
                                    <span class="btn btn-secondary">مسدد بالكامل</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <?php include 'includes/footer.php'; ?>
    
    <script>
    // دالة البحث والتصفية
    function filterFees() {
        const searchInput = document.getElementById('searchInput');
        const clearBtn = document.getElementById('clearSearchBtn');
        const searchTerm = searchInput.value.toLowerCase().trim();
        const tableBody = document.getElementById('feesTableBody');
        const rows = tableBody.getElementsByTagName('tr');
        const resultsDiv = document.getElementById('searchResults');
        
        // إظهار/إخفاء زر المسح
        if (searchTerm) {
            clearBtn.style.display = 'block';
        } else {
            clearBtn.style.display = 'none';
        }
        
        let visibleCount = 0;
        
        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];
            const studentNumber = (row.getAttribute('data-student-number') || '').toLowerCase();
            const studentName = (row.getAttribute('data-student-name') || '').toLowerCase();
            
            // البحث في جميع الحقول
            const matches = !searchTerm || 
                studentNumber.includes(searchTerm) ||
                studentName.includes(searchTerm);
            
            if (matches) {
                row.style.display = '';
                visibleCount++;
            } else {
                row.style.display = 'none';
            }
        }
        
        // عرض عدد النتائج
        if (searchTerm) {
            resultsDiv.innerHTML = `تم العثور على <strong>${visibleCount}</strong> سجل رسوم`;
            if (visibleCount === 0) {
                resultsDiv.innerHTML = '<span style="color: #d32f2f;">لم يتم العثور على أي نتائج</span>';
            }
        } else {
            resultsDiv.innerHTML = '';
        }
    }
    
    // دالة مسح البحث
    function clearSearch() {
        const searchInput = document.getElementById('searchInput');
        searchInput.value = '';
        filterFees();
        searchInput.focus();
    }
    </script>
</body>
</html>

