<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include('includes/db.php'); // PDO connection
include('includes/header.php');

// ---------------- Access Control ----------------
if (!isset($_SESSION['user_role'])) {
    $_SESSION['flash'] = [
        "message" => "Please log in first!",
        "color"   => "#dc3545"
    ];
    header("Location: login.php");
    exit;
}

// ---------------- Facility Context ----------------
$facility_id = intval($_SESSION['facility_id'] ?? 0);
if ($facility_id <= 0) {
    die("Facility not assigned.");
}

// ---------------- Date Filters ----------------
$fromDate = $_GET['from_date'] ?? date('Y-m-01');
$toDate   = $_GET['to_date'] ?? date('Y-m-t');

// ---------------- Fetch HMIS Categories (Facility Scoped) ----------------
$stmt = $pdo->prepare("
    SELECT *
    FROM hmis_category
    WHERE facility_id = ?
    ORDER BY id ASC
");
$stmt->execute([$facility_id]);
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Fetch HMIS Indicators (Facility Scoped) ----------------
$ind_sql = "
    SELECT 
        i.*, 
        c.name AS category_name, 
        c.gender AS category_gender, 
        c.min_years, 
        c.max_years
    FROM hmis_indicators i
    LEFT JOIN hmis_category c 
        ON c.id = i.category_id 
       AND c.facility_id = ?
    WHERE 
        i.status = 'active'
        AND i.facility_id = ?
    ORDER BY c.id ASC, i.id ASC
";
$stmt = $pdo->prepare($ind_sql);
$stmt->execute([$facility_id, $facility_id]);
$indicators = $stmt->fetchAll(PDO::FETCH_ASSOC);

ob_end_flush();
?>


<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
    <div class="content-wrapper">

        <!-- Date Filter -->
        <div class="content-header row">
            <div class="col-md-12">
                <h3 class="content-header-title">HMIS Report Summary</h3>
            </div>
        </div>

        <div class="content-body">
            <div class="card mb-3">
                <div class="card-body">
                    <form method="get" class="form-inline">
                        <div class="form-group mr-2">
                            <label for="from_date" class="mr-1">From:</label>
                            <input type="date" name="from_date" class="form-control" value="<?= htmlspecialchars($fromDate) ?>">
                        </div>
                        <div class="form-group mr-2">
                            <label for="to_date" class="mr-1">To:</label>
                            <input type="date" name="to_date" class="form-control" value="<?= htmlspecialchars($toDate) ?>">
                        </div>
                        <button type="submit" class="btn btn-primary">Filter</button>
                    </form>
                </div>
            </div>

            <!-- HMIS Table -->
            <div class="card mt-3">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="hmisTable" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Category</th>
                                    <th>Indicator</th>
                                    <th>Description</th>
                                    <th>Gender</th>
                                    <th>Age Range</th>
                                    <th>Reported Count</th>
                                </tr>
                            </thead>
                            <tbody>
<?php
$n = 1;
foreach ($indicators as $i):
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM visit_tickets vt
        JOIN patients p ON vt.patient_id = p.id
        WHERE JSON_CONTAINS(vt.hmis_report, ?)
          AND (? = 'Any' OR p.gender = ?)
          AND (p.d_o_b IS NOT NULL AND TIMESTAMPDIFF(YEAR, p.d_o_b, ?) BETWEEN ? AND ?)
          AND DATE(vt.visit_date) BETWEEN ? AND ?
    ");

    $hmis_id_json = json_encode((int)$i['id']);
    $categoryGender = $i['category_gender'] ?: 'Any';

    $stmt->execute([
        $hmis_id_json,
        $categoryGender,
        $categoryGender,
        date('Y-m-d'), // current date as reference
        $i['min_years'],
        $i['max_years'],
        $fromDate,
        $toDate
    ]);

    $count = $stmt->fetchColumn();
    $colorClass = $count == 0 ? 'text-danger' : 'text-success';
?>
<tr>
    <td><?= $n++ ?></td>
    <td><?= htmlspecialchars($i['category_name'] ?: 'N/A') ?></td>
    <td><strong><?= htmlspecialchars($i['indicator_name']) ?></strong></td>
    <td><?= nl2br(htmlspecialchars($i['description'])) ?></td>
    <td><?= htmlspecialchars($i['category_gender'] ?: 'Any') ?></td>
    <td><?= $i['min_years'] ?> – <?= $i['max_years'] ?></td>
    <td class="<?= $colorClass ?>"><strong><?= $count ?></strong></td>
</tr>
<?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

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

<!-- DataTables & Buttons -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
$(document).ready(function() {
    $('#hmisTable').DataTable({
        pageLength: 10,
        dom: 'Bfrtip',
        buttons: ['excel','pdf','print'],
        order: [[0, 'asc']]
    });
});
</script>
