<?php

ob_start();

require_once __DIR__ . '/../library/auth.php';

allow_roles(['admin', 'accountant']);

$school_id          = $_SESSION['school_id'];

$current_session_id = get_current_session_id($pdo);

$page_title = 'Fees Dashboard';

require_once __DIR__ . '/../include/header.php';

require_once __DIR__ . '/../include/sidebar.php';

// ======================================================
// FILTER
// ======================================================

$selected_class = isset($_GET['class_id'])
    ? (int) $_GET['class_id']
    : 0;

// ======================================================
// FETCH CLASSES
// ======================================================

$stmt = $pdo->prepare("
    SELECT

        id,
        class_name

    FROM classes

    WHERE school_id = ?

    ORDER BY class_name ASC
");

$stmt->execute([$school_id]);

$classes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ======================================================
// FETCH STUDENTS FEES SUMMARY
// ======================================================

$students = [];

if ($selected_class > 0) {

    $stmt = $pdo->prepare("
        SELECT

            s.id,

            s.name AS student_name,

            ss.roll_no,
            ss.section,

            c.class_name,

            COALESCE(cf.total_fees, 0) AS total_fees,

            COALESCE(fp.total_paid, 0) AS total_paid,

            (
                COALESCE(cf.total_fees, 0)
                -
                COALESCE(fp.total_paid, 0)
            ) AS balance_due

        FROM student_sessions ss

        INNER JOIN students s
            ON s.id = ss.student_id

        INNER JOIN classes c
            ON c.id = ss.class_id

        LEFT JOIN class_fees cf
            ON cf.class_id = ss.class_id
            AND cf.school_id = ss.school_id

        LEFT JOIN (

            SELECT

                student_id,

                SUM(paid_amount) AS total_paid

            FROM fee_payments

            WHERE school_id = ?
            AND session_id = ?

            GROUP BY student_id

        ) fp
            ON fp.student_id = s.id

        WHERE ss.class_id = ?
        AND ss.school_id = ?
        AND ss.session_id = ?
        AND ss.status = 'Active'

        ORDER BY

            ss.roll_no + 0 ASC,

            s.name ASC
    ");

    $stmt->execute([

        $school_id,

        $current_session_id,

        $selected_class,

        $school_id,

        $current_session_id

    ]);

    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// ======================================================
// GRAND TOTALS
// ======================================================

$grand_total = array_sum(
    array_column($students, 'total_fees')
);

$total_paid = array_sum(
    array_column($students, 'total_paid')
);

$total_due = array_sum(
    array_column($students, 'balance_due')
);

?>

<div class="content-wrapper">

    <!-- ================================================== -->
    <!-- HEADER -->
    <!-- ================================================== -->

    <section class="content-header">

        <div class="container-fluid">

            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center">

                <div class="mb-2 mb-md-0">

                    <h1 class="m-0">

                        <i class="fas fa-wallet text-primary"></i>

                        Fees Dashboard

                    </h1>

                    <small class="text-muted">

                        Manage class wise fees collection

                    </small>

                </div>

                <div>

                    <a
                        href="<?= WEB_ROOT ?>fees/fees_settings.php"
                        class="btn btn-primary btn-sm"
                    >

                        <i class="fas fa-cog"></i>

                        Fees Settings

                    </a>

                </div>

            </div>

        </div>

    </section>

    <!-- ================================================== -->
    <!-- CONTENT -->
    <!-- ================================================== -->

    <section class="content">

        <div class="container-fluid">

            <!-- ============================================== -->
            <!-- FILTER CARD -->
            <!-- ============================================== -->

            <div class="card card-outline card-primary shadow-sm">

                <div class="card-body">

                    <form method="GET">

                        <div class="row align-items-end">

                            <div class="col-12 col-md-8 col-lg-4 mb-3 mb-md-0">

                                <label class="font-weight-bold">

                                    Select Class

                                </label>

                                <select
                                    name="class_id"
                                    class="form-control"
                                    onchange="this.form.submit();"
                                >

                                    <option value="">

                                        -- Select Class --

                                    </option>

                                    <?php foreach ($classes as $class) : ?>

                                        <option
                                            value="<?= $class['id'] ?>"
                                            <?= ($selected_class == $class['id']) ? 'selected' : '' ?>
                                        >

                                            <?= htmlspecialchars($class['class_name']) ?>

                                        </option>

                                    <?php endforeach; ?>

                                </select>

                            </div>

                        </div>

                    </form>

                </div>

            </div>

            <?php if ($selected_class > 0) : ?>

                <!-- ========================================== -->
                <!-- SUMMARY CARDS -->
                <!-- ========================================== -->

                <div class="row mt-4">

                    <div class="col-12 col-md-4 mb-3">

                        <div class="small-box bg-info shadow-sm">

                            <div class="inner">

                                <h3>

                                    ₹<?= number_format($grand_total, 2) ?>

                                </h3>

                                <p>

                                    Total Fees

                                </p>

                            </div>

                            <div class="icon">

                                <i class="fas fa-file-invoice-dollar"></i>

                            </div>

                        </div>

                    </div>

                    <div class="col-12 col-md-4 mb-3">

                        <div class="small-box bg-success shadow-sm">

                            <div class="inner">

                                <h3>

                                    ₹<?= number_format($total_paid, 2) ?>

                                </h3>

                                <p>

                                    Total Collected

                                </p>

                            </div>

                            <div class="icon">

                                <i class="fas fa-check-circle"></i>

                            </div>

                        </div>

                    </div>

                    <div class="col-12 col-md-4 mb-3">

                        <div class="small-box bg-danger shadow-sm">

                            <div class="inner">

                                <h3>

                                    ₹<?= number_format($total_due, 2) ?>

                                </h3>

                                <p>

                                    Pending Amount

                                </p>

                            </div>

                            <div class="icon">

                                <i class="fas fa-exclamation-circle"></i>

                            </div>

                        </div>

                    </div>

                </div>

                <!-- ========================================== -->
                <!-- DESKTOP TABLE -->
                <!-- ========================================== -->

                <div class="card card-outline card-success shadow-sm d-none d-md-block">

                    <div class="card-header">

                        <h3 class="card-title">

                            <i class="fas fa-table"></i>

                            Class Fees Summary

                        </h3>

                    </div>

                    <div class="card-body p-0">

                        <div class="table-responsive">

                            <table class="table table-hover mb-0">

                                <thead class="thead-light">

                                    <tr>

                                        <th>Roll</th>

                                        <th>Student</th>

                                        <th>Class</th>

                                        <th>Total</th>

                                        <th>Paid</th>

                                        <th>Due</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php if (empty($students)) : ?>

                                        <tr>

                                            <td
                                                colspan="6"
                                                class="text-center p-4"
                                            >

                                                No students found

                                            </td>

                                        </tr>

                                    <?php endif; ?>

                                    <?php foreach ($students as $student) : ?>

                                        <tr>

                                            <td>

                                                <strong>

                                                    <?= htmlspecialchars($student['roll_no'] ?? '-') ?>

                                                </strong>

                                            </td>

                                            <td>

                                                <div class="font-weight-bold">

                                                    <?= htmlspecialchars($student['student_name']) ?>

                                                </div>

                                            </td>

                                            <td>

                                                <?= htmlspecialchars($student['class_name']) ?>

                                                -

                                                <?= htmlspecialchars($student['section'] ?? '-') ?>

                                            </td>

                                            <td>

                                                <strong>

                                                    ₹<?= number_format($student['total_fees'], 2) ?>

                                                </strong>

                                            </td>

                                            <td class="text-success">

                                                <strong>

                                                    ₹<?= number_format($student['total_paid'], 2) ?>

                                                </strong>

                                            </td>

                                            <td>

                                                <?php if ($student['balance_due'] > 0) : ?>

                                                    <span class="badge badge-danger">

                                                        ₹<?= number_format($student['balance_due'], 2) ?>

                                                    </span>

                                                <?php else : ?>

                                                    <span class="badge badge-success">

                                                        Paid

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                </tbody>

                            </table>

                        </div>

                    </div>

                </div>

                <!-- ========================================== -->
                <!-- MOBILE CARDS -->
                <!-- ========================================== -->

                <div class="d-block d-md-none">

                    <?php if (empty($students)) : ?>

                        <div class="alert alert-warning">

                            No students found

                        </div>

                    <?php endif; ?>

                    <?php foreach ($students as $student) : ?>

                        <div class="card shadow-sm mb-3 border-0">

                            <div class="card-body">

                                <div class="d-flex justify-content-between align-items-start">

                                    <div>

                                        <h6 class="mb-1 font-weight-bold">

                                            <?= htmlspecialchars($student['student_name']) ?>

                                        </h6>

                                        <small class="text-muted">

                                            Roll :
                                            <?= htmlspecialchars($student['roll_no'] ?? '-') ?>

                                        </small>

                                    </div>

                                    <?php if ($student['balance_due'] > 0) : ?>

                                        <span class="badge badge-danger">

                                            Due

                                        </span>

                                    <?php else : ?>

                                        <span class="badge badge-success">

                                            Paid

                                        </span>

                                    <?php endif; ?>

                                </div>

                                <hr>

                                <div class="row text-center">

                                    <div class="col-4">

                                        <small class="text-muted d-block">

                                            Total

                                        </small>

                                        <strong>

                                            ₹<?= number_format($student['total_fees'], 0) ?>

                                        </strong>

                                    </div>

                                    <div class="col-4">

                                        <small class="text-muted d-block">

                                            Paid

                                        </small>

                                        <strong class="text-success">

                                            ₹<?= number_format($student['total_paid'], 0) ?>

                                        </strong>

                                    </div>

                                    <div class="col-4">

                                        <small class="text-muted d-block">

                                            Due

                                        </small>

                                        <strong class="text-danger">

                                            ₹<?= number_format($student['balance_due'], 0) ?>

                                        </strong>

                                    </div>

                                </div>

                            </div>

                        </div>

                    <?php endforeach; ?>

                </div>

            <?php endif; ?>

        </div>

    </section>

</div>

<?php

ob_end_flush();

require_once __DIR__ . '/../include/footer.php';

?>