<?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'];

$stmt = $pdo->prepare("
    SELECT * 
    FROM hmis_category 
    WHERE facility_id = ?
    ORDER BY created_at DESC, id DESC
");
$stmt->execute([$facility_id]);
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);


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

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

    // ---------- DISABLE / ENABLE ----------
    if (isset($_POST['toggle_status'])) {
        $id = intval($_POST['id']);
        $newStatus = $_POST['new_status'] === 'active' ? 'active' : 'disabled';

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

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

    $name    = trim($_POST['name']);
    $gender  = $_POST['gender'] ?? null;
    $status  = $_POST['status'] ?? 'active';
    $minYear = intval($_POST['min_years'] ?? 0);
    $maxYear = intval($_POST['max_years'] ?? 0);

    // ---------- CHECK DUPLICATION (PER FACILITY) ----------
    $sql = "
        SELECT COUNT(*) 
        FROM hmis_category 
        WHERE facility_id = ?
          AND name = ?
          AND gender = ?
          AND min_years = ?
          AND max_years = ?
    ";
    $params = [$facility_id, $name, $gender, $minYear, $maxYear];

    if (isset($_POST['id'])) {
        $sql .= " AND id <> ?";
        $params[] = intval($_POST['id']);
    }

    $checkStmt = $pdo->prepare($sql);
    $checkStmt->execute($params);

    if ($checkStmt->fetchColumn() > 0) {
        $_SESSION['flash'] = [
            'message' => "This exact category already exists for this facility!",
            'color'   => '#dc3545'
        ];
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- CREATE ----------
    if (isset($_POST['create'])) {
        $stmt = $pdo->prepare("
            INSERT INTO hmis_category 
                (facility_id, name, gender, min_years, max_years, status)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $facility_id,
            $name,
            $gender,
            $minYear,
            $maxYear,
            $status
        ]);

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

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

        $stmt = $pdo->prepare("
            UPDATE hmis_category 
            SET name = ?, gender = ?, min_years = ?, max_years = ?, status = ?
            WHERE id = ? AND facility_id = ?
        ");
        $stmt->execute([
            $name,
            $gender,
            $minYear,
            $maxYear,
            $status,
            $id,
            $facility_id
        ]);

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

ob_end_flush();
?>


<!-- NAVBAR & 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="card-title text-center">HMIS CATEGORY MANAGEMENT</h2>
    <hr>

    <div class="row mb-2">
      <div class="col-lg-4 col-md-6 col-sm-12">
        <button type="button" class="btn btn-outline-primary btn-lg" data-toggle="modal" data-target="#addCategoryModal">Add Category</button>
      </div>
    </div>

    <!-- CATEGORY TABLE -->
    <div class="table-responsive">
      <table class="table table-hover mb-0" id="Table">
    <thead>
      <tr>
        <th>#</th>
        <th>Name</th>
        <th>Gender</th>
        <th>Min Years</th>
        <th>Max Years</th>
        <th>Status</th>
        <th>Created At</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <?php 
      $counter = count($categories); // Start from total to reverse numbering
      foreach($categories as $cat): 
      ?>
      <tr>
        <td><?= $counter-- ?></td>
        <td><?= htmlspecialchars($cat['name']) ?></td>
        <td><?= htmlspecialchars($cat['gender']) ?></td>
        <td><?= $cat['min_years'] ?></td>
        <td><?= $cat['max_years'] ?></td>
        <td><?= htmlspecialchars($cat['status']) ?></td>
        <td><?= isset($cat['created_at']) ? date('Y-m-d H:i', strtotime($cat['created_at'])) : '-' ?></td>
        <td>
          <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editCategoryModal<?= $cat['id'] ?>">Edit</button>
          <form method="post" style="display:inline;">
            <input type="hidden" name="csrf" value="<?= $csrf ?>">
            <input type="hidden" name="id" value="<?= $cat['id'] ?>">
            <input type="hidden" name="new_status" value="<?= $cat['status']==='active'?'disabled':'active' ?>">
            <button type="submit" name="toggle_status" class="btn btn-sm <?= $cat['status']==='active'?'btn-danger':'btn-success' ?>" 
              onclick="return confirm('Are you sure to <?= $cat['status']==='active'?'disable':'enable' ?> this category?');">
              <?= $cat['status']==='active'?'Disable':'Enable' ?>
            </button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
</table>

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

<!-- ADD CATEGORY MODAL -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form method="post" id="addCategoryForm">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <div class="modal-header">
          <h4 class="modal-title">Add Category</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <label>Name *</label>
          <input type="text" name="name" class="form-control" required>

          <label>Gender</label>
          <select name="gender" class="form-control">
            <option value="">Select Gender</option>
            <option value="Male">Male</option>
            <option value="Female">Female</option>
          </select>

          <label>Min Years *</label>
          <input type="number" name="min_years" class="form-control" min="0" required>

          <label>Max Years *</label>
          <input type="number" name="max_years" class="form-control" min="0" required>

          <label>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 type="button" class="btn btn-outline-secondary btn-lg" data-dismiss="modal">Close</button>
          <button type="submit" name="create" class="btn btn-outline-primary btn-lg">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- EDIT CATEGORY MODALS -->
<?php foreach($categories as $cat): ?>
<div class="modal fade" id="editCategoryModal<?= $cat['id'] ?>" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <input type="hidden" name="id" value="<?= $cat['id'] ?>">
        <div class="modal-header">
          <h4 class="modal-title">Edit Category</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <label>Name *</label>
          <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($cat['name']) ?>" required>

          <label>Gender</label>
          <select name="gender" class="form-control">
            <option value="">Select Gender</option>
            <option value="Male" <?= $cat['gender']=='Male'?'selected':'' ?>>Male</option>
            <option value="Female" <?= $cat['gender']=='Female'?'selected':'' ?>>Female</option>
          </select>

          <label>Min Years *</label>
          <input type="number" name="min_years" class="form-control" value="<?= $cat['min_years'] ?>" min="0" required>

          <label>Max Years *</label>
          <input type="number" name="max_years" class="form-control" value="<?= $cat['max_years'] ?>" min="0" required>

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

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

<style>
.toast-message{
    position:fixed;
    top:20px;
    right:20px;
    padding:12px 20px;
    color:#fff;
    border-radius:5px;
    z-index:9999;
    box-shadow:0 2px 8px rgba(0,0,0,0.2);
    font-size:14px;
}
</style>

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