<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$start_date = isset($_GET['start']) ? $_GET['start'] : date('Y-m-01');
$end_date = isset($_GET['end']) ? $_GET['end'] : date('Y-m-t');

// Payment Methods Analysis
$sql_methods = "SELECT 
                    payment_method, 
                    COUNT(*) as count, 
                    SUM(amount) as total 
                FROM payments 
                WHERE payment_date BETWEEN ? AND ? 
                GROUP BY payment_method";
$stmt = $conn->prepare($sql_methods);
$stmt->bind_param("ss", $start_date, $end_date);
$stmt->execute();
$methods_res = $stmt->get_result();

$labels = [];
$series = [];
while ($row = $methods_res->fetch_assoc()) {
    $labels[] = ucfirst(str_replace('_', ' ', $row['payment_method']));
    $series[] = (float) $row['total'];
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Payment Analysis')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Payment Analysis</h4>
                                <div class="page-title-right">
                                    <form method="GET" class="d-flex gap-2 align-items-center">
                                        <input type="date" name="start" class="form-control form-control-sm"
                                            value="<?php echo $start_date; ?>">
                                        <span>to</span>
                                        <input type="date" name="end" class="form-control form-control-sm"
                                            value="<?php echo $end_date; ?>">
                                        <button type="submit" class="btn btn-sm btn-primary">Filter</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Payment Methods Distribution</h4>
                                </div>
                                <div class="card-body">
                                    <div id="payment-pie" class="apex-charts" dir="ltr"></div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Summary</h4>
                                </div>
                                <div class="card-body">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Method</th>
                                                <th class="text-end">Total Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $total = 0;
                                            foreach ($labels as $i => $label):
                                                $total += $series[$i];
                                                ?>
                                                <tr>
                                                    <td><?php echo $label; ?></td>
                                                    <td class="text-end"><?php echo number_format($series[$i], 2); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr class="fw-bold">
                                                <td>TOTAL</td>
                                                <td class="text-end"><?php echo number_format($total, 2); ?></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>
    <script>
        var options = {
            series: <?php echo json_encode($series); ?>,
            labels: <?php echo json_encode($labels); ?>,
            chart: {
                type: 'donut',
                height: 350,
            },
            colors: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'],
            legend: {
                position: 'bottom'
            }
        };

        var chart = new ApexCharts(document.querySelector("#payment-pie"), options);
        chart.render();
    </script>
</body>

</html>