<?php
require_once('../config.php');
include('../header/header.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: dashboard.php");
    exit();
}

// Handle payment recording
if (isset($_POST['add_payment'])) {
    $student_id = $_POST['student_id'];
    $amount_paid = $_POST['amount_paid'];
    $total_fee = $_POST['total_fee'];
    $payment_date = date('Y-m-d H:i:s');
    
    // Calculate status
    $status = 'pending';
    if ($amount_paid >= $total_fee) {
        $status = 'paid';
    } elseif ($amount_paid > 0) {
        $status = 'partial';
    }

    $stmt = $pdo->prepare("INSERT INTO payments (student_id, amount_paid, total_fee, payment_date, status) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$student_id, $amount_paid, $total_fee, $payment_date, $status]);
    $success = "Payment recorded successfully.";
}

// Fetch all payments with student names
$stmt = $pdo->query("SELECT p.*, u.username as student_name FROM payments p JOIN users u ON p.student_id = u.id ORDER BY p.payment_date DESC");
$payments = $stmt->fetchAll();

// Fetch all students for the dropdown
$stmt = $pdo->query("SELECT id, username FROM users WHERE role = 'student'");
$students = $stmt->fetchAll();
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">Payments & Arrears Management</h2>
        <span class="badge bg-secondary px-3 py-2 rounded-pill"><?php echo count($payments); ?> Records</span>
    </div>

    <!-- Stats Summary -->
    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <?php 
                $total_collected = array_sum(array_column($payments, 'amount_paid'));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-success">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-success bg-opacity-10 text-success me-3">
                        <i class="fas fa-hand-holding-usd"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Total Collected</p>
                        <h4 class="fw-bold mb-0">KES <?php echo number_format($total_collected, 0); ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <?php 
                $total_arrears = array_sum(array_map(function($p) { return $p['total_fee'] - $p['amount_paid']; }, $payments));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-danger">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-danger bg-opacity-10 text-danger me-3">
                        <i class="fas fa-exclamation-circle"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Total Arrears</p>
                        <h4 class="fw-bold mb-0">KES <?php echo number_format($total_arrears, 0); ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <?php 
                $paid_count = count(array_filter($payments, function($p) { return $p['status'] == 'paid'; }));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-primary">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-primary bg-opacity-10 text-primary me-3">
                        <i class="fas fa-check-double"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Fully Paid</p>
                        <h4 class="fw-bold mb-0"><?php echo $paid_count; ?> Students</h4>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Add Payment Column -->
        <div class="col-lg-4 mb-4">
            <div class="card glass-card border-0 shadow-sm h-100">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center mb-4">
                        <div class="bg-primary bg-opacity-10 text-primary p-2 rounded-3 me-3">
                            <i class="fas fa-plus"></i>
                        </div>
                        <h5 class="fw-bold mb-0">Record New Payment</h5>
                    </div>
                    
                    <?php if(isset($success)): ?>
                        <div class="alert alert-success border-0 shadow-sm small py-2">
                            <i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Student Name</label>
                            <select name="student_id" class="form-select" required>
                                <option value="">-- Select Student --</option>
                                <?php foreach($students as $student): ?>
                                    <option value="<?php echo $student['id']; ?>"><?php echo htmlspecialchars($student['username']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Total Course Fee (KES)</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0">KES</span>
                                <input type="number" step="0.01" name="total_fee" class="form-control border-start-0" placeholder="0.00" required>
                            </div>
                        </div>
                        <div class="mb-4">
                            <label class="form-label small fw-bold">Amount Received (KES)</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0">KES</span>
                                <input type="number" step="0.01" name="amount_paid" class="form-control border-start-0" placeholder="0.00" required>
                            </div>
                        </div>
                        <button type="submit" name="add_payment" class="btn btn-primary w-100 py-3 shadow-sm">
                            <i class="fas fa-save me-2"></i>Record Payment
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Payments Table Column -->
        <div class="col-lg-8">
            <div class="card glass-card border-0 shadow-sm">
                <div class="card-header bg-white py-3 border-0">
                    <h5 class="fw-bold mb-0">Transaction History & Balances</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-4">Student</th>
                                    <th>Total Fee</th>
                                    <th>Paid</th>
                                    <th>Balance</th>
                                    <th>Status</th>
                                    <th class="pe-4 text-end">Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($payments as $payment): 
                                    $arrears = $payment['total_fee'] - $payment['amount_paid'];
                                ?>
                                    <tr>
                                        <td class="ps-4">
                                            <div class="fw-bold text-dark"><?php echo htmlspecialchars($payment['student_name']); ?></div>
                                            <small class="text-muted">ID: #PAY-<?php echo $payment['id']; ?></small>
                                        </td>
                                        <td>KES <?php echo number_format($payment['total_fee'], 0); ?></td>
                                        <td class="text-success fw-bold">KES <?php echo number_format($payment['amount_paid'], 0); ?></td>
                                        <td class="text-danger fw-bold">KES <?php echo number_format($arrears, 0); ?></td>
                                        <td>
                                            <span class="badge <?php 
                                                echo $payment['status'] == 'paid' ? 'bg-success' : ($payment['status'] == 'partial' ? 'bg-warning' : 'bg-danger'); 
                                            ?> px-3 py-2 rounded-pill text-capitalize">
                                                <?php echo $payment['status']; ?>
                                            </span>
                                        </td>
                                        <td class="pe-4 text-end small text-muted">
                                            <i class="far fa-clock me-1"></i><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include('../footer/footer.php'); ?>
