<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting(0);

include('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];
if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {

    header('location:logout.php');

    exit();

}



// Fetch all sessions and terms for dropdowns

$sessions = [];

$terms = [];



$sessionQuery = mysqli_query($con, "SELECT DISTINCT session FROM payment ORDER BY session DESC");

while ($row = mysqli_fetch_assoc($sessionQuery)) {

    $sessions[] = $row['session'];

}



$termQuery = mysqli_query($con, "SELECT DISTINCT Term FROM payment ORDER BY Term ASC");

while ($row = mysqli_fetch_assoc($termQuery)) {

    $terms[] = $row['Term'];

}

?>



<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>



<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

        <?php @include("includes/header.php"); ?>

        <?php @include("includes/sidebar.php"); ?>



        <div class="content-wrapper">

<section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

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

                <div class="col-md-8">

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

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

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Payment Management

                                <span class="premium-subtitle text-secondary">Payment Analytics</span>

                            </h1>
                    <div class="mt-1">
                      <?php if ($currentSessionName): ?>
                        <span class="badge badge-primary mr-1">
                          <i class="fas fa-calendar-alt"></i>
                          <?= htmlspecialchars($currentSessionName) ?>
                        </span>
                      <?php endif; ?>
                      <?php if ($currentTermName): ?>
                        <span class="badge badge-success">
                          <i class="fas fa-bookmark"></i>
                          <?= htmlspecialchars($currentTermName) ?>
                        </span>
                      <?php else: ?>
                        <span class="badge badge-warning">
                          <i class="fas fa-exclamation-triangle"></i> No active term
                        </span>
                      <?php endif; ?>
                    </div>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <nav aria-label="breadcrumb">

                        <ol class="breadcrumb premium-breadcrumb">

                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item"><rove href="approve.php" class="text-primary">Approve Payment</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Payment Analytics</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section> 

            <section class="content">

                <div class="card card-primary">

                    <div class="card-header">

                        <h5 class="card-title font-weight-bold"><i class="fas fa-chart-line"></i> Payment Analytics Report </h5>

                    </div>

                    <div class="card-body">

                        <!-- Filter Form -->

                        <form method="GET" id="filterForm">

                            <div class="form-group row">

                                <div class="form-group col-md-6">

                                    <label>Session:</label>

                                    <select name="session" id="session" class="form-control">

                                        <option value="">All Session</option>

                                        <?php foreach ($sessions as $sessionItem): ?>

                                            <option value="<?php echo htmlspecialchars($sessionItem); ?>"><?php echo htmlspecialchars($sessionItem); ?></option>

                                        <?php endforeach; ?>

                                    </select>

                                </div>

                                <div class="form-group col-md-6">

                                    <label>Term:</label>

                                    <select name="term" id="term" class="form-control">

                                        <option value="">All Term</option>

                                        <?php foreach ($terms as $termItem): ?>

                                            <option value="<?php echo htmlspecialchars($termItem); ?>"><?php echo htmlspecialchars($termItem); ?></option>

                                        <?php endforeach; ?>

                                    </select>

                                </div>

                            </div>

                            <div class="form-group text-center">

                                <button type="button" class="btn btn-primary" onclick="updateReport()"><i class="fas fa-filter"></i> Filter</button>

                            </div>

                        </form>



                        <!-- Chart Container -->

                        <canvas id="paymentChart" height="100"></canvas>



                        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

                        <script>

                            function updateReport() {

                                const session = document.getElementById('session').value;

                                const term = document.getElementById('term').value;



                                // AJAX request to fetch data

                                const xhr = new XMLHttpRequest();

                                xhr.open('GET', `get_payment_data.php?session=${session}&term=${term}`, true);

                                xhr.onload = function() {

                                    if (xhr.status === 200) {

                                        const data = JSON.parse(xhr.responseText);



                                        // Update Chart Data

                                        const labels = data.labels;

                                        const amounts = data.amounts;

                                        const colors = labels.map(() => 'rgba(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',0.6)');



                                        const ctx = document.getElementById('paymentChart').getContext('2d');



                                        new Chart(ctx, {

                                            type: 'bar',

                                            data: {

                                                labels: labels,

                                                datasets: [{

                                                        label: 'Actual Payment Received (₦)',

                                                        data: amounts.map((amount, index) => amount - data.discounts[index]),

                                                        backgroundColor: 'rgba(54, 162, 235, 0.6)',

                                                        borderColor: 'rgba(54, 162, 235, 1)',

                                                        borderWidth: 1

                                                    },

                                                    {

                                                        label: 'Discount Given (₦)',

                                                        data: data.discounts,

                                                        backgroundColor: 'rgba(255, 99, 132, 0.6)',

                                                        borderColor: 'rgba(255, 99, 132, 1)',

                                                        borderWidth: 1

                                                    }

                                                ]

                                            },

                                            options: {

                                                responsive: true,

                                                scales: {

                                                    y: {

                                                        beginAtZero: true,

                                                        title: {

                                                            display: true,

                                                            text: 'Amount (₦)'

                                                        }

                                                    },

                                                    x: {

                                                        title: {

                                                            display: true,

                                                            text: 'Session & Term'

                                                        }

                                                    }

                                                },

                                                plugins: {

                                                    title: {

                                                        display: true,

                                                        text: 'Payment vs Discount Analysis'

                                                    },

                                                    tooltip: {

                                                        callbacks: {

                                                            label: function(context) {

                                                                return `${context.dataset.label}: ₦${context.parsed.y.toLocaleString()}`;

                                                            }

                                                        }

                                                    }

                                                }

                                            }

                                        });





                                        // Update Table Data

                                        let tableHTML = '';

                                        data.rows.forEach(row => {

                                            // Check if the Term value is undefined or empty

                                            const termDisplay = row.term ? row.term : 'No Term Info'; // Display "No Term Info" if term is missing



                                            const discount = row.total_discount ?? 0;

                                            const totalWithDiscount = parseFloat(row.total_collected) - parseFloat(discount);



                                            tableHTML += `

                                            <tr>

                                                <td>${row.session}</td>

                                                <td>${row.Term}</td>

                                                <td>₦${parseFloat(row.total_collected).toLocaleString()}</td>

                                                <td>₦${parseFloat(discount).toLocaleString()}</td>

                                                <td>₦${totalWithDiscount.toLocaleString()}</td>

                                            </tr>`;



                                        });



                                        // Append Grand Total Row

                                        const grandTotalWithDiscount = data.totalSum - data.totalDiscount;



                                        tableHTML += `

                                            <tr style="font-weight: bold; background: #f2f2f2;">

                                                <td colspan="2" class="text-right">Grand Total:</td>

                                                <td>₦${data.totalSum.toLocaleString()}</td>

                                                <td>₦${data.totalDiscount.toLocaleString()}</td>

                                                <td>₦${grandTotalWithDiscount.toLocaleString()}</td>

                                            </tr>`;





                                        document.getElementById('paymentTableBody').innerHTML = tableHTML;

                                    }

                                };

                                xhr.send();

                            }

                            // Call updateReport automatically when page loads

                            window.addEventListener('DOMContentLoaded', function() {

                                updateReport();

                            });

                        </script>



                        <!-- Table -->

                        <table id="example11" class="table table-bordered table-hover">

                            <thead class="thead-light">

                                <tr>

                                    <th>Academic Session</th>

                                    <th>Term</th>

                                    <th>Expected Payment (₦)</th>

                                    <th>Discount Applied (₦)</th>

                                    <th>Actual Payment Received (₦)</th>

                                </tr>

                            </thead>



                            <tbody id="paymentTableBody">

                                <!-- Data will be populated here via AJAX -->

                            </tbody>

                        </table>



                    </div>

                </div>

            </section>



        </div>



        <?php @include("includes/footer.php"); ?>

    </div>

    <?php @include("includes/foot.php"); ?>

    <script src="dist/js/select2.min.js"></script>

    <script>

        // In your Javascript (external .js resource or <script> tag)

        $(document).ready(function() {

            $('#session').select2();

        });

        $(document).ready(function() {

            $('#term').select2();

        });

    </script>



</body>



</html>