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

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

// ---------------- Access Control ----------------
if (!isset($_SESSION['user_role'])) {
    header("Location: login.php");
    exit;
}

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

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

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

// ---------------- CRUD ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf'] ?? '')) {
        die("Invalid CSRF token");
    }

    // ---------------- TOGGLE STATUS ----------------
    if (isset($_POST['toggle_status'])) {
        $id = intval($_POST['id']);
        $new = $_POST['new_status'] === 'active' ? 'active' : 'disabled';

        $stmt = $pdo->prepare("
            UPDATE hmis_indicators 
            SET status = ? 
            WHERE id = ? AND facility_id = ?
        ");
        $stmt->execute([$new, $id, $facility_id]);

        $_SESSION['flash'] = [
            'message' => "Status updated!",
            'color'   => $new === 'active' ? '#28a745' : '#dc3545'
        ];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------------- DELETE ----------------
    if (isset($_POST['delete'])) {
        $id = intval($_POST['id']);

        $stmt = $pdo->prepare("
            DELETE FROM hmis_indicators 
            WHERE id = ? AND facility_id = ?
        ");
        $stmt->execute([$id, $facility_id]);

        $_SESSION['flash'] = [
            'message' => "Indicator deleted!",
            'color'   => '#dc3545'
        ];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------------- CREATE / UPDATE ----------------
    $category_id    = intval($_POST['category_id']);
    $indicator_name = trim($_POST['indicator_name']);
    $description    = trim($_POST['description'] ?? '');
    $ecd_11         = trim($_POST['ecd_11'] ?? '');
    $status         = $_POST['status'] ?? 'active';

    // ---------------- CREATE ----------------
if (isset($_POST['create'])) {

    $chk = $pdo->prepare("
        SELECT COUNT(*) 
        FROM hmis_indicators 
        WHERE facility_id = ?
          AND category_id = ?
          AND indicator_name = ?
    ");
    $chk->execute([
        $facility_id,
        $category_id,
        $indicator_name
    ]);

    if ($chk->fetchColumn() > 0) {
        $_SESSION['flash'] = [
            'message' => "Indicator with same name already exists in this facility!",
            'color'   => '#dc3545'
        ];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    $ins = $pdo->prepare("
        INSERT INTO hmis_indicators 
            (facility_id, category_id, indicator_name, description, ecd_11, status)
        VALUES (?,?,?,?,?,?)
    ");
    $ins->execute([
        $facility_id,
        $category_id,
        $indicator_name,
        $description,
        $ecd_11,
        $status
    ]);

    $_SESSION['flash'] = [
        'message' => "Indicator created!",
        'color'   => '#28a745'
    ];
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// ---------------- UPDATE ----------------
if (isset($_POST['update'])) {
    $id = intval($_POST['id']);

    $chk = $pdo->prepare("
        SELECT COUNT(*) 
        FROM hmis_indicators 
        WHERE facility_id = ?
          AND category_id = ?
          AND indicator_name = ?
          AND id <> ?
    ");
    $chk->execute([
        $facility_id,
        $category_id,
        $indicator_name,
        $id
    ]);

    if ($chk->fetchColumn() > 0) {
        $_SESSION['flash'] = [
            'message' => "Another indicator with same name exists in this facility!",
            'color'   => '#dc3545'
        ];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    $up = $pdo->prepare("
        UPDATE hmis_indicators 
        SET category_id = ?, indicator_name = ?, description = ?, ecd_11 = ?, status = ?
        WHERE id = ? AND facility_id = ?
    ");
    $up->execute([
        $category_id,
        $indicator_name,
        $description,
        $ecd_11,
        $status,
        $id,
        $facility_id
    ]);

    $_SESSION['flash'] = [
        'message' => "Indicator updated!",
        'color'   => '#007bff'
    ];
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

}

ob_end_flush();
?>


<!-- NAV BAR + SIDEBAR -->
<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>

<!-- MAIN CONTENT -->
<div class="app-content content container-fluid">
    <div class="content-wrapper">
        <h2 class="text-center">HMIS INDICATOR MANAGEMENT</h2>
        <hr>

        <button class="btn btn-outline-primary btn-lg mb-2" data-toggle="modal" data-target="#addModal">
            Add Indicator
        </button>

        <!-- INDICATORS TABLE -->
        <div class="table-responsive">
            <table class="table table-hover mb-0" id="Table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Indicator Name</th>
                        <th>HMIS Category</th>
                        <th>Gender</th>
                        <th>Description</th>
                        <th>ECD 11</th>
                        <th>Min Years(s)</th>
                        <th>Max Years(s)</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $n=1; foreach($indicators as $i): ?>
                    <tr>
                        <td><?= $n++ ?></td>
                        <td><?= htmlspecialchars($i['indicator_name']) ?></td>
                        <td><?= htmlspecialchars($i['category_name']) ?></td>
                        <td><?= htmlspecialchars($i['category_gender']) ?></td>
                        <td><?= nl2br(htmlspecialchars($i['description'])) ?></td>
                        <td><?= htmlspecialchars($i['ecd_11']) ?></td>
                        <td><?= htmlspecialchars($i['category_min']) ?></td>
                        <td><?= htmlspecialchars($i['category_max']) ?></td>
                        <td><?= $i['status'] ?></td>
                        <td>
                            <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editModal<?= $i['id'] ?>">Edit</button>

                            <form method="post" style="display:inline;">
                                <input type="hidden" name="csrf" value="<?= $csrf ?>">
                                <input type="hidden" name="id" value="<?= $i['id'] ?>">
                                <input type="hidden" name="new_status" value="<?= $i['status']=='active'?'disabled':'active' ?>">
                                <button name="toggle_status" class="btn btn-sm <?= $i['status']=='active'?'btn-danger':'btn-success' ?>">
                                    <?= $i['status']=='active'?'Disable':'Enable' ?>
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ADD MODAL -->
<div class="modal fade" id="addModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="csrf" value="<?= $csrf ?>">
                <div class="modal-header">
                    <h4>Add Indicator</h4>
                    <button class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">

                    <label class="mt-2">Indicator Name</label>
                    <input type="text" name="indicator_name" class="form-control" required>

                    <label>HMISCategory</label>
                    <select name="category_id" class="form-control" required>
                        <option value="">Select</option>
                        <?php foreach($categories as $c): ?>
                        <option value="<?= $c['id'] ?>">
                            <?= htmlspecialchars($c['name']) ?> (Gender: <?= $c['gender'] ?: 'N/A' ?>, Min: <?= $c['min_years'] ?>, Max: <?= $c['max_years'] ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>

                    <label class="mt-2">Description</label>
                    <input name="description" class="form-control"  placeholder="Enter Description">

                    <label class="mt-2">ECD-11</label>
                    <input type="text" name="ecd_11" class="form-control" placeholder="Enter ECD-11">

                    <label class="mt-2">Status</label>
                    <select name="status" class="form-control">
                        <option value="active">Active</option>
                        <option value="disabled">Disabled</option>
                    </select>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
                    <button name="create" class="btn btn-outline-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- EDIT MODALS -->
<?php foreach($indicators as $i): ?>
<div class="modal fade" id="editModal<?= $i['id'] ?>">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="csrf" value="<?= $csrf ?>">
                <input type="hidden" name="id" value="<?= $i['id'] ?>">
                <div class="modal-header">
                    <h4>Edit Indicator</h4>
                    <button class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">

                    <label>Category</label>
                    <select name="category_id" class="form-control">
                        <?php foreach($categories as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= $i['category_id']==$c['id']?'selected':'' ?>>
                            <?= htmlspecialchars($c['name']) ?> (Gender: <?= $c['gender'] ?: 'N/A' ?>, Min: <?= $c['min_years'] ?>, Max: <?= $c['max_years'] ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>

                    <label class="mt-2">Indicator Name</label>
                    <input type="text" name="indicator_name" class="form-control" 
                           value="<?= htmlspecialchars($i['indicator_name']) ?>" required>

                    <label class="mt-2">Description</label>
                    <input name="description" class="form-control"><?= htmlspecialchars($i['description']) ?>

                    <label class="mt-2">ECD 11</label>
                    <input type="text" name="ecd_11" class="form-control" 
                           value="<?= htmlspecialchars($i['ecd_11']) ?>">

                    <label class="mt-2">Status</label>
                    <select name="status" class="form-control">
                        <option value="active" <?= $i['status']=='active'?'selected':'' ?>>Active</option>
                        <option value="disabled" <?= $i['status']=='disabled'?'selected':'' ?>>Disabled</option>
                    </select>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
                    <button name="update" class="btn btn-outline-primary">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endforeach; ?>

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

<!-- TOAST -->
<?php if(isset($_SESSION['flash'])): ?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    const div = document.createElement("div");
    div.className = "toast-msg";
    div.innerText = "<?= addslashes($_SESSION['flash']['message']) ?>";
    div.style.background = "<?= $_SESSION['flash']['color'] ?>";
    document.body.appendChild(div);
    setTimeout(()=> div.remove(), 4000);
});
</script>
<?php unset($_SESSION['flash']); endif; ?>

<style>
.toast-msg {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    border-radius: 6px;
    color: #fff;
    font-size: 14px;
    z-index: 99999;
}
</style>
