<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

// Admin or Teacher access
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

$student_details = null;
$fee_summary = null;
$all_fees = [];
$error_message = '';
$system_name = get_system_name($pdo);
$settings = get_all_settings($pdo);
$institution_name = $settings['site_name'] ?? $system_name;
$institution_address = $settings['site_address'] ?? '';
$logo_image = $settings['logo_image'] ?? '';
$logo_path = $logo_image ? '../' . $logo_image : '';

// Get filter parameters
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? '';
$group = $_GET['group'] ?? '';
$roll_number = $_GET['roll_number'] ?? '';

// Fetch data for dropdowns
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll(PDO::FETCH_ASSOC);
$sessions = $pdo->query("SELECT DISTINCT session FROM students ORDER BY session DESC")->fetchAll(PDO::FETCH_COLUMN);
$groups = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name")->fetchAll(PDO::FETCH_COLUMN);

if ($class_id && $session && $roll_number) {
    try {
        // Find student
        $sql = "
            SELECT s.id, s.first_name, s.last_name, s.roll_number, c.name as class_name, c.section, s.session, s.group_name
            FROM students s
            JOIN classes c ON s.class_id = c.id
            WHERE s.class_id = :class_id AND s.session = :session AND s.roll_number = :roll_number
        ";
        $params = ['class_id' => $class_id, 'session' => $session, 'roll_number' => $roll_number];

        if ($group) {
            $sql .= " AND s.group_name = :group_name";
            $params['group_name'] = $group;
        }

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $student_details = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($student_details) {
            $student_id = $student_details['id'];

            // Fetch all fees for the student (regardless of academic year)
            $fee_stmt = $pdo->prepare("
                SELECT *,
                       (amount - paid_amount) as due_amount
                FROM fees
                WHERE student_id = :student_id
                ORDER BY due_date ASC
            ");
            $fee_stmt->execute(['student_id' => $student_id]);
            $all_fees = $fee_stmt->fetchAll(PDO::FETCH_ASSOC);

            // Fetch payment history for the student
            $payment_history_stmt = $pdo->prepare("
                SELECT
                    fp.id as payment_id,
                    fp.payment_date,
                    fp.payment_method,
                    fp.amount,
                    f.fee_type,
                    f.month
                FROM
                    fee_payments fp
                JOIN
                    fees f ON fp.fee_id = f.id
                WHERE
                    f.student_id = :student_id
                ORDER BY
                    fp.payment_date ASC
            ");
            $payment_history_stmt->execute(['student_id' => $student_id]);
            $payment_history = $payment_history_stmt->fetchAll(PDO::FETCH_ASSOC);

            // Calculate summary
            $total_payable = 0;
            $total_paid = 0;
            foreach ($all_fees as $fee) {
                $total_payable += $fee['amount'];
                $total_paid += $fee['paid_amount'];
            }
            $fee_summary = [
                'total_payable' => $total_payable,
                'total_paid' => $total_paid,
                'total_due' => $total_payable - $total_paid
            ];

        } else {
            $error_message = "এই রোল, ক্লাস, গ্রুপ ও সেশনে কোনো ছাত্র পাওয়া যায়নি।";
        }
    } catch (Exception $e) {
        $error_message = "রিপোর্ট তৈরি করার সময় একটি ত্রুটি হয়েছে: " . $e->getMessage();
    }
}

?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ছাত্রের ফি সারসংক্ষেপ</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root{--indigo:#4fc3f7;--pink:#e83e8c;--teal:#4dd0e1;--orange:#ffb74d}
        body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0}
        .top-bar{background:linear-gradient(135deg,#0d2137,#1a3a5c);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 20px rgba(0,0,0,.4)}
        .top-bar .brand{color:#4fc3f7;font-weight:700;font-size:.9rem;text-decoration:none;display:flex;align-items:center;gap:8px}
        .top-bar .brand i{font-size:1.2rem}
        .top-bar .nav-links{display:flex;gap:12px}
        .top-bar .nav-links a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.75rem;font-weight:500;padding:4px 10px;border-radius:6px;transition:.2s}
        .top-bar .nav-links a:hover{color:#fff;background:rgba(255,255,255,.08)}
        .filter-card{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:10px 14px;margin-bottom:12px}
        .filter-card .form-label{font-size:.75rem;font-weight:700;color:#90caf9;margin-bottom:2px}
        .filter-card .form-select,.filter-card .form-control{font-size:.8rem;padding:4px 8px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0}
        .filter-card .form-select:focus,.filter-card .form-control:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.15)}
        .filter-card option{background:#11294a;color:#e0e0e0}
        .card{border:none;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);margin-bottom:1rem}
        .card .card-header{background:linear-gradient(135deg,#0d2137,#1a3a5c);color:#4fc3f7;border-bottom:1px solid rgba(255,255,255,.06);padding:8px 12px;font-weight:600;font-size:.9rem}
        .card .card-body{padding:10px 14px}
        .card-header h5{margin:0;font-size:.9rem;font-weight:600}
        .form-control,.form-select{font-size:.82rem;padding:5px 10px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0}
        .form-control:focus,.form-select:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.15)}
        .form-select option{background:#11294a;color:#e0e0e0}
        .form-control::placeholder{color:rgba(255,255,255,.3)}
        .btn{font-size:.78rem;border-radius:6px;padding:5px 14px;font-weight:600}
        .btn-primary{background:#1565c0;border:none}
        .btn-primary:hover{background:#1976d2}
        .btn-secondary{background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.15);color:#e0e0e0}
        .btn-secondary:hover{background:rgba(255,255,255,.25);color:#fff}
        .btn-success{background:#2e7d32;border:none}
        .btn-success:hover{background:#388e3c}
        label.form-label{font-size:.78rem;font-weight:600;color:#90caf9;margin-bottom:2px}
        .alert{font-size:.8rem;border-radius:8px;padding:8px 12px}
        .alert-danger{background:rgba(198,40,40,.2);border:1px solid rgba(198,40,40,.3);color:#ef9a9a}
        .text-muted{color:rgba(255,255,255,.5)!important}

        .report-container{max-width:900px;margin:1rem auto;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);border-radius:12px;overflow:hidden}
        .report-header{text-align:center;padding:1.2rem 1.5rem;border-bottom:1px solid rgba(255,255,255,.08)}
        .report-header h3{font-size:1.1rem;font-weight:800;color:#4fc3f7;margin:0 0 4px}
        .report-header h4{font-size:1rem;font-weight:700;color:#e0e0e0;margin:0 0 4px}
        .report-header p{font-size:.78rem;color:rgba(255,255,255,.5)}
        .report-body{padding:1.2rem 1.5rem}
        .summary-card{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:1rem}
        .summary-item{text-align:center}
        .summary-item p{margin-bottom:2px;font-size:.78rem;font-weight:600;color:#90caf9}
        .summary-item.paid p{color:#a5d6a7}
        .summary-item.due p{color:#ef9a9a}
        .summary-item h4{font-weight:800;font-size:1.2rem;margin:0;color:#e0e0e0}
        .summary-item.paid h4{color:#66bb6a}
        .summary-item.due h4{color:#ef5350}
        h5{font-size:.88rem;font-weight:700;color:#4fc3f7;margin:1rem 0 .6rem}
        .table{--bs-table-border-color:rgba(255,255,255,.08);color:#e0e0e0;font-size:.78rem;margin:0}
        .table-bordered{border:1px solid rgba(255,255,255,.08)}
        .table-striped>tbody>tr:nth-of-type(odd){--bs-table-accent-bg:rgba(255,255,255,.03);color:#e0e0e0}
        .table-striped>tbody>tr:nth-of-type(even){--bs-table-accent-bg:rgba(255,255,255,.01);color:#e0e0e0}
        .table thead th{border-bottom:1px solid rgba(255,255,255,.1);color:#90caf9;font-size:.75rem;font-weight:700;padding:6px 8px}
        .table td{padding:5px 8px;vertical-align:middle;border-color:rgba(255,255,255,.06)}
        .table-hover tbody tr:hover{--bs-table-hover-bg:rgba(79,195,247,.08);--bs-table-hover-color:#e0e0e0}
        #payment-history-table tbody td{color:#fff!important}
        #fee-detail-table tbody td{color:#fff!important}
        #fee-detail-table tbody td.text-danger{color:#ffd700!important}
        .badge{font-size:.68rem;font-weight:600;padding:3px 8px;border-radius:6px}
        .bg-success{background:#2e7d32!important}
        .bg-danger{background:#c62828!important}
        .bg-warning{background:#e65100!important}
        .bg-secondary{background:rgba(255,255,255,.15)!important;color:#e0e0e0}
        .text-danger{color:#ef5350!important}
        a{color:#90caf9}
        a:hover{color:#4fc3f7}

        @media print {
            body{background-color:#fff;font-family:'Hind Siliguri',sans-serif;font-size:12pt;color:#000}
            .no-print,.top-bar{display:none!important}
            .report-container{box-shadow:none;border:none;margin:0;padding:0;width:100%;max-width:100%;border-radius:0;background:#fff}
            .report-header .school-name{font-size:22pt;font-weight:700;color:#000!important;margin-bottom:2px}
            .report-header .school-address{font-size:11pt;color:#555!important}
            .report-header img{max-height:80px!important;max-width:80px!important}
            .report-header h3{font-size:16pt;font-weight:700;color:#000}
            .report-header h4{font-size:14pt;color:#000}
            .report-header p{font-size:11pt;color:#000!important}
            .summary-card{background:#fff!important;border:1px solid #ccc;padding:1rem}
            .summary-item p{font-size:11pt!important;font-weight:600!important;color:#000!important}
            .summary-item.paid p{color:#198754!important}
            .summary-item.due p{color:#dc3545!important}
            .summary-item h4{color:#000!important;font-size:14pt}
            .summary-item.paid h4{color:#198754!important}
            .summary-item.due h4{color:#dc3545!important}
            .table,.table th,.table td{border:1px solid #666!important;color:#000!important;background:#fff!important}
            .table thead th{background:#eee!important;-webkit-print-color-adjust:exact;color-adjust:exact;color:#000!important}
            #fee-detail-table tbody td,#payment-history-table tbody td{color:#000!important}
            #fee-detail-table tbody td.text-danger{color:#000!important}
            .badge{border:1px solid #000;color:#000!important;background:#fff!important}
            h5{color:#000!important;margin-top:1.5rem;border-bottom:1px solid #000;padding-bottom:5px;font-size:13pt}
            @page{size:A4;margin:.75in}
            .report-body::after{content:"প্রিন্টের তারিখ: " "<?php echo date('d/m/Y H:i'); ?>";display:block;text-align:center;font-size:9pt;position:fixed;bottom:20px;left:50%;transform:translateX(-50%);color:#000}
            .text-muted{color:#000!important}
            .fw-bold{font-weight:700!important}
            .text-danger{color:#dc3545!important}
        }
    </style>
</head>
<body>

<div class="top-bar no-print">
    <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
    <div class="nav-links">
        <a href="manage.php"><i class="fas fa-wrench"></i> ফি ম্যানেজ</a>
        <a href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি সংগ্রহ</a>
        <a href="management_dashboard.php"><i class="fas fa-cog"></i> ফি ড্যাশবোর্ড</a>
        <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
        <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
    </div>
</div>

<div class="container-fluid px-4 py-3">
    <div class="filter-card no-print">
        <form method="GET" action="">
            <div class="row g-1 align-items-end">
                <div class="col-md-3"><label class="form-label"><i class="fas fa-chalkboard me-1" style="color:var(--teal)"></i>ক্লাস</label><select name="class_id" class="form-select" required><option value="">-- নির্বাচন করুন --</option><?php foreach ($classes as $class): ?><option value="<?php echo $class['id']; ?>" <?php echo ($class_id == $class['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?></option><?php endforeach; ?></select></div>
                <div class="col-md-3"><label class="form-label"><i class="fas fa-calendar-alt me-1" style="color:var(--indigo)"></i>সেশন</label><select name="session" class="form-select" required><option value="">-- নির্বাচন করুন --</option><?php foreach ($sessions as $sess): ?><option value="<?php echo htmlspecialchars($sess); ?>" <?php echo ($session === $sess) ? 'selected' : ''; ?>><?php echo htmlspecialchars($sess); ?></option><?php endforeach; ?></select></div>
                <div class="col-md-2"><label class="form-label"><i class="fas fa-users me-1" style="color:var(--orange)"></i>গ্রুপ</label><select name="group" class="form-select"><option value="">সব গ্রুপ</option><?php foreach ($groups as $grp): ?><option value="<?php echo htmlspecialchars($grp); ?>" <?php echo ($group === $grp) ? 'selected' : ''; ?>><?php echo htmlspecialchars($grp); ?></option><?php endforeach; ?></select></div>
                <div class="col-md-2"><label class="form-label"><i class="fas fa-hashtag me-1" style="color:var(--pink)"></i>রোল</label><input type="number" name="roll_number" class="form-control" value="<?php echo htmlspecialchars($roll_number); ?>" required></div>
                <div class="col-md-2 d-flex align-items-end"><button type="submit" class="btn btn-primary w-100" style="font-size:.78rem;padding:5px;border-radius:6px"><i class="fas fa-search me-1"></i>রিপোর্ট দেখুন</button></div>
            </div>
            <div class="text-center mt-2">
                <a href="manage.php" class="btn btn-secondary" style="font-size:.72rem"><i class="fas fa-arrow-left me-1"></i>ফি ব্যবস্থাপনায় ফিরুন</a>
            </div>
        </form>
        <?php if ($error_message): ?><div class="alert alert-danger mt-2"><?php echo $error_message; ?></div><?php endif; ?>
    </div>

    <?php if ($student_details && $fee_summary): ?>
    <div class="report-container">
        <div class="report-header">
            <div style="display:flex;align-items:center;justify-content:center;gap:12px;margin-bottom:6px;position:relative">
                <?php if ($logo_path && file_exists($logo_path)): ?>
                    <img src="<?php echo $logo_path; ?>" alt="লোগো" style="max-height:60px;max-width:60px;flex-shrink:0;position:absolute;left:0">
                <?php endif; ?>
                <div style="text-align:center">
                    <div class="school-name" style="font-size:1rem;font-weight:800;color:rgba(255,255,255,.85)"><?php echo htmlspecialchars($institution_name); ?></div>
                    <?php if ($institution_address): ?>
                        <div class="school-address" style="font-size:.72rem;color:rgba(255,255,255,.5)"><?php echo htmlspecialchars($institution_address); ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <h3>ফি সারসংক্ষেপ</h3>
            <h4><?php echo htmlspecialchars($student_details['first_name'] . ' ' . $student_details['last_name']); ?></h4>
            <p class="mb-0" style="color:rgba(255,255,255,.5);font-size:.78rem">
                রোল: <?php echo htmlspecialchars($student_details['roll_number']); ?> | 
                ক্লাস: <?php echo htmlspecialchars($student_details['class_name'] . ' - ' . $student_details['section']); ?> 
                <?php if($student_details['group_name']): ?>| গ্রুপ: <?php echo htmlspecialchars($student_details['group_name']); ?><?php endif; ?>
                | সেশন: <?php echo htmlspecialchars($student_details['session']); ?>
            </p>
        </div>
        <div class="report-body">
            <div class="summary-card mb-3">
                <div class="row g-2">
                    <div class="col-4 summary-item"><p>মোট প্রদেয়</p><h4>৳<?php echo number_format($fee_summary['total_payable'], 2); ?></h4></div>
                    <div class="col-4 summary-item paid"><p>মোট পরিশোধিত</p><h4>৳<?php echo number_format($fee_summary['total_paid'], 2); ?></h4></div>
                    <div class="col-4 summary-item due"><p>মোট বকেয়া</p><h4>৳<?php echo number_format($fee_summary['total_due'], 2); ?></h4></div>
                </div>
            </div>

            <h5><i class="fas fa-list me-1"></i>ফি-এর বিস্তারিত তালিকা</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped" id="fee-detail-table">
                    <thead><tr><th>ফি-এর ধরন</th><th>মাস</th><th>প্রদেয়</th><th>পরিশোধিত</th><th>বকেয়া</th><th>স্ট্যাটাস</th><th>শেষ তারিখ</th></tr></thead>
                    <tbody>
                        <?php foreach ($all_fees as $fee): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                            <td><?php echo htmlspecialchars($fee['month'] ?? 'N/A'); ?></td>
                            <td>৳<?php echo number_format($fee['amount'], 2); ?></td>
                            <td>৳<?php echo number_format($fee['paid_amount'], 2); ?></td>
                            <td class="fw-bold <?php echo ($fee['due_amount'] > 0) ? 'text-danger' : ''; ?>">৳<?php echo number_format($fee['due_amount'], 2); ?></td>
                            <td><?php $sc='bg-secondary';if($fee['status']=='paid')$sc='bg-success';if($fee['status']=='partial')$sc='bg-warning';if($fee['status']=='pending'||$fee['status']=='overdue')$sc='bg-danger'; ?><span class="badge <?php echo $sc; ?>"><?php echo ucfirst($fee['status']); ?></span></td>
                            <td><?php echo date("d/m/Y", strtotime($fee['due_date'])); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <h5 class="mt-4"><i class="fas fa-history me-1"></i>পেমেন্ট হিস্ট্রি</h5>
            <div class="table-responsive">
                <table class="table table-bordered table-striped" id="payment-history-table">
                    <thead><tr><th>তারিখ</th><th>রসিদ নং</th><th>বিবরণ</th><th>পদ্ধতি</th><th class="text-end">টাকা</th></tr></thead>
                    <tbody>
                        <?php if (empty($payment_history)): ?>
                            <tr><td colspan="5" class="text-center" style="color:rgba(255,255,255,.7)">কোনো পেমেন্ট পাওয়া যায়নি।</td></tr>
                        <?php else: ?>
                            <?php foreach ($payment_history as $payment): ?>
                            <tr>
                                <td><?php echo date("d/m/Y", strtotime($payment['payment_date'])); ?></td>
                                <td><?php echo htmlspecialchars($payment['payment_id']); ?></td>
                                <td><?php echo htmlspecialchars($payment['fee_type']); if($payment['month']) echo " - " . htmlspecialchars($payment['month']); ?></td>
                                <td><?php echo htmlspecialchars(ucfirst($payment['payment_method'])); ?></td>
                                <td class="text-end fw-bold">৳<?php echo number_format($payment['amount'], 2); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="text-center mt-3 no-print">
                <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print me-1"></i>প্রিন্ট</button>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

</body>
</html>