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

// Only logged-in students
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'student') {
    header('Location: ../login.php');
    exit();
}

// Get student from user
$stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s LEFT JOIN classes c ON s.class_id=c.id WHERE s.user_id=? LIMIT 1");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch();
if (!$student) { 
    die('Student profile not found'); 
}

// Check if student has scholarship
$has_scholarship = ($student['scholarship'] === 'yes');

// Load all fees
$stmt = $pdo->prepare("SELECT f.*, (f.amount - f.paid_amount) as due_amount FROM fees f WHERE f.student_id=? ORDER BY f.due_date ASC, f.created_at ASC");
$stmt->execute([$student['id']]);
$fees = $stmt->fetchAll();

// Process fee selection
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['selected_fees'])) {
    $selected_fees = $_POST['selected_fees'];
    $total_amount = 0;
    
    // Calculate total amount for selected fees
    foreach ($fees as $fee) {
        if (in_array($fee['id'], $selected_fees) && $fee['due_amount'] > 0) {
            $total_amount += $fee['due_amount'];
        }
    }
    
    // Redirect to payment page with selected amount
    if ($total_amount > 0) {
        header("Location: student_payment.php?amount=$total_amount");
        exit();
    } else {
        $_SESSION['info_message'] = 'আপনার কোন বকেয়া ফি নেই।';
        header('Location: my_fees.php');
        exit();
    }
}

?>
<!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="../assets/css/style.css" rel="stylesheet">
    <style>
        .fee-item { border:1px solid #dee2e6; border-radius:8px; padding:12px; margin-bottom:10px; background:#fff; }
        .fee-item.overdue { border-left:4px solid #dc3545; background:#fff5f5; }
        .fee-item.selected { border:2px solid #0d6efd; background:#f0f8ff; }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
        <div class="navbar-nav ms-auto">
            <a class="nav-link" href="my_fees.php"><i class="fas fa-arrow-left"></i> আমার ফি</a>
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>
</nav>

<div class="container-fluid mt-4">
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($_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">
            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($_SESSION['error_message']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['info_message'])): ?>
        <div class="alert alert-info alert-dismissible fade show">
            <i class="fas fa-info-circle"></i> <?= htmlspecialchars($_SESSION['info_message']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['info_message']); ?>
    <?php endif; ?>
    
    <div class="card">
        <div class="card-header">
            <h5><i class="fas fa-list-check"></i> ফি নির্বাচন</h5>
        </div>
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-4"><strong>নাম:</strong> <?=htmlspecialchars($student['first_name'].' '.$student['last_name'])?></div>
                <div class="col-md-4"><strong>আইডি:</strong> <?=htmlspecialchars($student['student_id'])?></div>
                <div class="col-md-4"><strong>ক্লাস:</strong> <?=htmlspecialchars(($student['class_name']??'').' - '.($student['section']??''))?></div>
            </div>
            
            <?php if ($has_scholarship): ?>
                <div class="alert alert-success">
                    <i class="fas fa-graduation-cap"></i> অভিনন্দন! আপনি উপবৃত্তি পেয়েছেন। ফি পরিশোধের দরকার নেই।
                </div>
            <?php elseif (empty($fees)): ?>
                <div class="alert alert-info">কোন ফি নির্ধারিত নেই।</div>
            <?php else: ?>
                <form method="POST">
                    <div class="mb-3">
                        <h6>আপনার ফি তালিকা:</h6>
                        <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>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $total_payable = 0; 
                                    $total_paid = 0; 
                                    $total_due = 0;
                                    foreach ($fees as $f): 
                                        $due = (float)($f['amount'] - $f['paid_amount']); 
                                        $overdue = ($due>0 && !empty($f['due_date']) && strtotime($f['due_date']) < time());
                                        $total_payable += (float)$f['amount'];
                                        $total_paid += (float)$f['paid_amount'];
                                        $total_due += $due;
                                    ?>
                                    <tr class="<?= $overdue ? 'table-danger' : '' ?>">
                                        <td>
                                            <?php if ($due > 0): ?>
                                                <input type="checkbox" name="selected_fees[]" value="<?= $f['id'] ?>" class="fee-checkbox" data-amount="<?= $due ?>">
                                            <?php else: ?>
                                                <i class="fas fa-check-circle text-success"></i>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= htmlspecialchars($f['fee_type']) ?></td>
                                        <td><?= $f['month'] ? htmlspecialchars($f['month']) : '-' ?></td>
                                        <td>৳<?= number_format((float)$f['amount'], 2) ?></td>
                                        <td>৳<?= number_format((float)$f['paid_amount'], 2) ?></td>
                                        <td class="<?= $due > 0 ? 'text-danger fw-bold' : 'text-success' ?>">
                                            ৳<?= number_format($due, 2) ?>
                                        </td>
                                        <td><?= $f['due_date'] ? htmlspecialchars($f['due_date']) : 'N/A' ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="table-primary">
                                        <th colspan="3">মোট</th>
                                        <th>৳<?= number_format($total_payable, 2) ?></th>
                                        <th>৳<?= number_format($total_paid, 2) ?></th>
                                        <th class="<?= $total_due > 0 ? 'text-danger fw-bold' : 'text-success' ?>">
                                            ৳<?= number_format($total_due, 2) ?>
                                        </th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    
                    <?php if ($total_due > 0): ?>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> নির্বাচিত ফি গুলো পরিশোধ করতে চাইলে "পেমেন্ট করুন" বাটনে ক্লিক করুন
                        </div>
                        
                        <div class="d-grid gap-2 d-md-block">
                            <button type="submit" class="btn btn-success btn-lg" id="pay-button" disabled>
                                <i class="fas fa-money-bill-wave"></i> পেমেন্ট করুন (৳<span id="total-amount">0.00</span>)
                            </button>
                            <a href="my_fees.php" class="btn btn-secondary btn-lg">
                                <i class="fas fa-arrow-left"></i> আমার ফি-তে ফিরে যান
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> আপনার কোন বকেয়া ফি নেই।
                        </div>
                        <div class="d-grid">
                            <a href="my_fees.php" class="btn btn-primary btn-lg">
                                <i class="fas fa-arrow-left"></i> আমার ফি-তে ফিরে যান
                            </a>
                        </div>
                    <?php endif; ?>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Handle fee selection and calculate total
    document.addEventListener('DOMContentLoaded', function() {
        const checkboxes = document.querySelectorAll('.fee-checkbox');
        const payButton = document.getElementById('pay-button');
        const totalAmount = document.getElementById('total-amount');
        
        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                let total = 0;
                checkboxes.forEach(cb => {
                    if (cb.checked) {
                        total += parseFloat(cb.dataset.amount) || 0;
                    }
                });
                
                totalAmount.textContent = total.toFixed(2);
                payButton.disabled = (total <= 0);
            });
        });
    });
</script>
</body>
</html>