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

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

$start = $_GET['start'] ?? date('Y-01-01');
$end = $_GET['end'] ?? date('Y-12-31');

// Report: New Registrations
$sql_regs = "SELECT COUNT(*) as cnt FROM patients WHERE created_at BETWEEN ? AND ?";
$stmt = $conn->prepare($sql_regs);
$e_start = $start . " 00:00:00";
$e_end = $end . " 23:59:59";
$stmt->bind_param("ss", $e_start, $e_end);
$stmt->execute();
$new_regs = $stmt->get_result()->fetch_assoc()['cnt'];

// Report: Total Visits
$sql_visits = "SELECT COUNT(*) as cnt FROM appointments WHERE appointment_date BETWEEN ? AND ?";
$stmt = $conn->prepare($sql_visits);
$stmt->bind_param("ss", $start, $end);
$stmt->execute();
$visits = $stmt->get_result()->fetch_assoc()['cnt'];

// Demographics: Gender
$sql_gender = "SELECT u.gender, COUNT(*) as cnt 
               FROM patients p JOIN users u ON p.user_id = u.user_id 
               GROUP BY u.gender"; // No date filter for demographics usually, or filter by created_at if "New Patients Demographics"
$gender_res = $conn->query($sql_gender);
$genders = [];
while ($row = $gender_res->fetch_assoc()) {
    $genders[$row['gender'] ? $row['gender'] : 'Unknown'] = $row['cnt'];
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Reports')); ?>
    <?php include 'layouts/head-css.php'; ?>
</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">Patient Reports</h4>
                                <div class="page-title-right">
                                    <form method="GET" class="d-flex gap-2">
                                        <input type="date" name="start" class="form-control form-control-sm"
                                            value="<?php echo $start; ?>">
                                        <input type="date" name="end" class="form-control form-control-sm"
                                            value="<?php echo $end; ?>">
                                        <button type="submit" class="btn btn-primary btn-sm">Update</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-3">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <h5 class="card-title text-muted">New Registrations</h5>
                                    <h2 class="mt-2 text-primary"><?php echo number_format($new_regs); ?></h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <h5 class="card-title text-muted">Total Appointments</h5>
                                    <h2 class="mt-2 text-success"><?php echo number_format($visits); ?></h2>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title">Patient Demographics (Gender)</h4>
                                </div>
                                <div class="card-body">
                                    <div id="gender-pie" class="apex-charts" dir="ltr"></div>
                                </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(array_values($genders)); ?>,
            labels: <?php echo json_encode(array_keys($genders)); ?>,
            chart: { type: 'donut', height: 350 },
            colors: ['#3b82f6', '#ec4899', '#f59e0b']
        };
        var chart = new ApexCharts(document.querySelector("#gender-pie"), options);
        chart.render();
    </script>
</body>

</html>