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

session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY'])) {
    if (time() - $_SESSION['LAST_ACTIVITY'] > $SESSION_TIMEOUT) {
        session_unset();
        session_destroy();
        header("Location: login.php?timeout=1");
        exit;
    }
}
$_SESSION['LAST_ACTIVITY'] = time();

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


// ---------------- Access Control ----------------
if (!isset($_SESSION['facility_id'])) {
    die("Facility not set");
}
$facility_id = (int) $_SESSION['facility_id'];

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

// ---------------- Consumable Categories ----------------
$consumableCategories = [
    "Syringes","Gloves","Cotton","Tubes","IV cannulas / catheters","Masks",
    "Bandages","Needles","Blood collection tubes","Urine collection containers",
    "Surgical drapes and gowns","Dressing packs","Tourniquets",
    "Medical tape / adhesive strips","Specimen cups / containers"
];

// ---------------- Consumable Units ----------------
$consumableUnits = [
    "Sample Unit","Unit","X 10^9/L","%","10^12/L","g/dL","pg","fL",
    "Bottle","Pc","Kg","g"
];

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

    // ---------- CREATE ----------
    if (isset($_POST['create'])) {
        if ($_POST['csrf'] !== $_SESSION['csrf_token']) die("Invalid CSRF token");

        $consumable_name = trim($_POST['consumable_name']);
        $category = trim($_POST['category']);
        $unit = trim($_POST['unit']);

        // ---- DUPLICATE CHECK PER FACILITY ----
        $stmt = $pdo->prepare("
            SELECT id 
            FROM consumables 
            WHERE facility_id = ? AND consumable_name = ?
            LIMIT 1
        ");
        $stmt->execute([$facility_id, $consumable_name]);

        if ($stmt->fetch()) {
            $_SESSION['flash'] = [
                'message' => 'Consumable name already exists in your facility. Duplication is not allowed.',
                'color'   => '#dc3545'
            ];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }

        // ---- INSERT ----
        $stmt = $pdo->prepare("
            INSERT INTO consumables 
            (facility_id, consumable_name, category, unit, status) 
            VALUES (?, ?, ?, ?, 'enabled')
        ");
        $stmt->execute([$facility_id, $consumable_name, $category, $unit]);

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

    // ---------- UPDATE ----------
    if (isset($_POST['update'])) {
        if ($_POST['csrf'] !== $_SESSION['csrf_token']) die("Invalid CSRF token");

        $id = intval($_POST['id']);
        $consumable_name = trim($_POST['consumable_name']);
        $category = trim($_POST['category']);
        $unit = trim($_POST['unit']);

        // ---- DUPLICATE CHECK PER FACILITY (EXCLUDE SELF) ----
        $stmt = $pdo->prepare("
            SELECT id 
            FROM consumables 
            WHERE facility_id = ? AND consumable_name = ? AND id != ?
            LIMIT 1
        ");
        $stmt->execute([$facility_id, $consumable_name, $id]);

        if ($stmt->fetch()) {
            $_SESSION['flash'] = [
                'message' => 'Consumable name already exists in your facility. Duplication is not allowed.',
                'color'   => '#dc3545'
            ];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }

        $stmt = $pdo->prepare("
            UPDATE consumables 
            SET consumable_name=?, category=?, unit=? 
            WHERE id=? AND facility_id=?
        ");
        $stmt->execute([$consumable_name, $category, $unit, $id, $facility_id]);

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

    // ---------- TOGGLE ENABLE/DISABLE ----------
    if (isset($_POST['toggle'])) {
        if ($_POST['csrf'] !== $_SESSION['csrf_token']) die("Invalid CSRF token");

        $id = intval($_POST['id']);
        $currentStatus = $_POST['current_status'] === 'enabled' ? 'disabled' : 'enabled';

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

        $statusText  = $currentStatus === 'enabled' ? 'Consumable enabled!' : 'Consumable disabled!';
        $statusColor = $currentStatus === 'enabled' ? '#28a745' : '#dc3545';

        $_SESSION['flash'] = [
            'message' => $statusText,
            'color'   => $statusColor
        ];

        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
}

// ---------------- Fetch Consumables ----------------
$stmt = $pdo->prepare("
    SELECT * 
    FROM consumables 
    WHERE facility_id=? 
    ORDER BY id DESC
");
$stmt->execute([$facility_id]);
$consumables = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Fetch Distinct Names for Dropdown ----------------
$stmt = $pdo->prepare("
    SELECT DISTINCT consumable_name 
    FROM consumables 
    WHERE facility_id=? 
    ORDER BY consumable_name ASC
");
$stmt->execute([$facility_id]);
$consumableNames = $stmt->fetchAll(PDO::FETCH_COLUMN);
?>


<!-- Navbar and 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>
<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">Consumables Management</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">
            <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="#addConsumableModal">Add Consumable</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Consumable Name</th>
                    <th>Category</th>
                    <th>Unit</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $counter=1; foreach($consumables as $c): ?>
                  <tr>
                    <td><?= $counter++ ?></td>
                    <td><?= htmlspecialchars($c['consumable_name']) ?></td>
                    <td><?= htmlspecialchars($c['category']) ?></td>
                    <td><?= htmlspecialchars($c['unit']) ?></td>
                    <td style="color: <?= $c['status']=='enabled'?'#28a745':'#dc3545' ?>; font-weight:bold;">
                        <?= ucfirst($c['status']) ?>
                    </td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editModal<?= $c['id'] ?>">Edit</button>

                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="id" value="<?= $c['id'] ?>">
                        <input type="hidden" name="current_status" value="<?= $c['status'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="toggle" class="btn btn-sm <?= $c['status']=='enabled'?'btn-secondary':'btn-success' ?>">
                          <?= $c['status']=='enabled'?'Disable':'Enable' ?>
                        </button>
                      </form>
                    </td>
                  </tr>

                  <!-- Edit Modal -->
                  <div class="modal fade" id="editModal<?= $c['id'] ?>" tabindex="-1">
                    <div class="modal-dialog">
                      <div class="modal-content">
                        <form method="post">
                          <input type="hidden" name="csrf" value="<?= $csrf ?>">
                          <input type="hidden" name="id" value="<?= $c['id'] ?>">

                          <div class="modal-header">
                            <h4>Edit Consumable</h4>
                          </div>
                          <div class="modal-body">
                            <label>Consumable Name *</label>
                            <div class="form-control dropdown-search" style="position: relative; padding: 0; cursor: pointer;">
                              <div class="selected" style="padding: .375rem .75rem;"><?= htmlspecialchars($c['consumable_name']) ?></div>
                              <div class="options-container" style="position: absolute; top: 100%; left: 0; right: 0; border: 1px solid #ced4da; max-height: 200px; overflow-y: auto; background: #fff; display: none; z-index: 1000;">
                                <input type="text" placeholder="Search or type new..." class="form-control mb-1" style="box-sizing: border-box; width: 100%; padding: .375rem .75rem;">
                                <ul style="list-style: none; padding: 0; margin: 0;">
                                  <?php foreach($consumableNames as $name): ?>
                                    <li class="option-item" style="padding: .375rem .75rem; cursor: pointer;"><?= htmlspecialchars($name) ?></li>
                                  <?php endforeach; ?>
                                </ul>
                              </div>
                              <input type="hidden" name="consumable_name" value="<?= htmlspecialchars($c['consumable_name']) ?>">
                            </div>

                            <label>Category *</label>
                            <select name="category" class="form-control" required>
                              <option value="">-- Select Category --</option>
                              <?php foreach($consumableCategories as $cat): ?>
                                <option value="<?= htmlspecialchars($cat) ?>" <?= $c['category']==$cat?'selected':'' ?>><?= htmlspecialchars($cat) ?></option>
                              <?php endforeach; ?>
                            </select>

                            <label>Unit *</label>
                            <select name="unit" class="form-control" required>
                              <option value="">-- Select Unit --</option>
                              <?php foreach($consumableUnits as $u): ?>
                                <option value="<?= htmlspecialchars($u) ?>" <?= $c['unit']==$u?'selected':'' ?>><?= htmlspecialchars($u) ?></option>
                              <?php endforeach; ?>
                            </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; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Consumable Modal -->
<div class="modal fade" id="addConsumableModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <label class="modal-title">Add Consumable</label>
        </div>
        <div class="modal-body">
          <label>Consumable Name *</label>
          <div class="form-control dropdown-search" style="position: relative; padding: 0; cursor: pointer;">
            <div class="selected" style="padding: .375rem .75rem;">-- Select or type --</div>
            <div class="options-container" style="position: absolute; top: 100%; left: 0; right: 0; border: 1px solid #ced4da; max-height: 200px; overflow-y: auto; background: #fff; display: none; z-index: 1000;">
              <input type="text" placeholder="Search or type new..." class="form-control mb-1" style="box-sizing: border-box; width: 100%; padding: .375rem .75rem;">
              <ul style="list-style: none; padding: 0; margin: 0;">
                <?php foreach($consumableNames as $name): ?>
                  <li class="option-item" style="padding: .375rem .75rem; cursor: pointer;"><?= htmlspecialchars($name) ?></li>
                <?php endforeach; ?>
              </ul>
            </div>
            <input type="hidden" name="consumable_name">
          </div>

          <label>Category *</label>
          <select name="category" class="form-control" required>
            <option value="">-- Select Category --</option>
            <?php foreach($consumableCategories as $cat): ?>
              <option value="<?= htmlspecialchars($cat) ?>"><?= htmlspecialchars($cat) ?></option>
            <?php endforeach; ?>
          </select>

          <label>Unit *</label>
          <select name="unit" class="form-control" required>
            <option value="">-- Select Unit --</option>
            <?php foreach($consumableUnits as $u): ?>
              <option value="<?= htmlspecialchars($u) ?>"><?= htmlspecialchars($u) ?></option>
            <?php endforeach; ?>
          </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>

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

<script>
document.querySelectorAll('.dropdown-search').forEach(dropdown => {
    const selected = dropdown.querySelector('.selected');
    const optionsContainer = dropdown.querySelector('.options-container');
    const searchInput = optionsContainer.querySelector('input');
    const optionsList = optionsContainer.querySelectorAll('.option-item');
    const hiddenInput = dropdown.querySelector('input[type="hidden"]');

    // Toggle dropdown
    selected.addEventListener('click', () => {
        optionsContainer.style.display = optionsContainer.style.display === 'block' ? 'none' : 'block';
        searchInput.value = '';
        filterOptions('');
        searchInput.focus();
    });

    // Select option
    optionsList.forEach(option => {
        option.addEventListener('click', () => {
            selected.textContent = option.textContent;
            hiddenInput.value = option.textContent;
            optionsContainer.style.display = 'none';
        });
    });

    // Filter function
    function filterOptions(value) {
        const filter = value.toLowerCase();
        optionsList.forEach(option => {
            option.style.display = option.textContent.toLowerCase().includes(filter) ? '' : 'none';
        });
    }

    // Filter while typing
    searchInput.addEventListener('input', () => {
        filterOptions(searchInput.value);
        hiddenInput.value = searchInput.value; // allow typing new name
        selected.textContent = searchInput.value;
    });

    // Close dropdown if click outside
    document.addEventListener('click', (e) => {
        if (!dropdown.contains(e.target)) {
            optionsContainer.style.display = 'none';
        }
    });
});
</script>

<style>
.toast-message{
  position:fixed;
  top:20px;
  right:20px;
  z-index:9999;
  padding:.75rem 1rem;
  border-radius:.25rem;
  opacity:0.95;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}
</style>

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