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


// ---------------- Session Validation Function ----------------
function validateSession() {
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        header("Location: login.php?error=session_expired");
        exit;
    }
    
    // Check if facility is set
    if (!isset($_SESSION['facility_id'])) {
        // Logout immediately instead of showing error
        session_unset();
        session_destroy();
        header("Location: login.php?error=facility_not_set");
        exit;
    }
    
    // Validate facility ID
    $facility_id = (int) $_SESSION['facility_id'];
    if ($facility_id <= 0) {
        session_unset();
        session_destroy();
        header("Location: login.php?error=invalid_facility");
        exit;
    }
    
    return $facility_id;
}

// Validate session and get facility_id
$facility_id = validateSession();

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

// ---------------- Pharmacological Groups ----------------
$pharmaGroups = ["Antibiotics","Antivirals","Antifungals","Analgesics","Antiparasitics","Antineoplastics","Vaccines"];

// ---------------- Drug Units ----------------
$drugUnits = ["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']) {
            session_unset();
            session_destroy();
            header("Location: login.php?error=csrf_invalid");
            exit;
        }

        $drug_name = trim($_POST['drug_name']);
        $pharmacological_group = trim($_POST['pharmacological_group']);
        $drug_unit = trim($_POST['drug_unit']);

        $stmt = $pdo->prepare("
            INSERT INTO drugs (facility_id, drug_name, pharmacological_group, drug_unit, status) 
            VALUES (?, ?, ?, ?, 'enabled')
        ");
        $stmt->execute([$facility_id, $drug_name, $pharmacological_group, $drug_unit]);

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

    // ---------- UPDATE ----------
    if (isset($_POST['update'])) {
        if ($_POST['csrf'] !== $_SESSION['csrf_token']) {
            session_unset();
            session_destroy();
            header("Location: login.php?error=csrf_invalid");
            exit;
        }

        $id = (int) $_POST['id'];
        $drug_name = trim($_POST['drug_name']);
        $pharmacological_group = trim($_POST['pharmacological_group']);
        $drug_unit = trim($_POST['drug_unit']);

        if ($id <= 0 || $drug_name === '') {
            $_SESSION['flash'] = [
                'message' => 'Invalid input provided',
                'color'   => '#dc3545'
            ];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }

        // ✅ DUPLICATE CHECK (EXCLUDE CURRENT ID)
        $check = $pdo->prepare("
            SELECT id 
            FROM drugs 
            WHERE facility_id = ?
              AND drug_name = ?
              AND id <> ?
            LIMIT 1
        ");
        $check->execute([$facility_id, $drug_name, $id]);

        if ($check->fetch()) {
            $_SESSION['flash'] = [
                'message' => 'Another drug with this name already exists in this facility.',
                'color'   => '#dc3545'
            ];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }

        // ✅ SAFE UPDATE
        $stmt = $pdo->prepare("
            UPDATE drugs 
            SET drug_name = ?, 
                pharmacological_group = ?, 
                drug_unit = ? 
            WHERE id = ? 
              AND facility_id = ?
        ");
        $stmt->execute([
            $drug_name,
            $pharmacological_group,
            $drug_unit,
            $id,
            $facility_id
        ]);

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

    // ---------- TOGGLE ENABLE/DISABLE ----------
    if (isset($_POST['toggle'])) {
        if ($_POST['csrf'] !== $_SESSION['csrf_token']) {
            session_unset();
            session_destroy();
            header("Location: login.php?error=csrf_invalid");
            exit;
        }

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

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

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

        $_SESSION['flash'] = ['message'=>$statusText,'color'=>$statusColor];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
}

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

// ---------------- Fetch Distinct Drug Names for Dropdown ----------------
$stmt = $pdo->prepare("
    SELECT DISTINCT drug_name 
    FROM drugs 
    WHERE facility_id = ? 
    ORDER BY drug_name ASC
");
$stmt->execute([$facility_id]);
$drugNames = $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">Drugs 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-md" data-toggle="modal" data-target="#addDrugModal">Add Drug</button>
              </div>
            </div>

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

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

                  <!-- Edit Modal -->
                  <div class="modal fade" id="editModal<?= $drug['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="<?= $drug['id'] ?>">

                          <div class="modal-header">
                            <h4>Edit Drug</h4>
                          </div>
                          <div class="modal-body">
                            <label>Drug Name *</label>
                            <!-- Searchable input -->
                            <div class="form-control dropdown-search" style="position: relative; padding: 0; cursor: pointer;">
                              <div class="selected" style="padding: .375rem .75rem;"><?= htmlspecialchars($drug['drug_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($drugNames as $dname): ?>
                                    <li class="option-item" style="padding: .375rem .75rem; cursor: pointer;"><?= htmlspecialchars($dname) ?></li>
                                  <?php endforeach; ?>
                                </ul>
                              </div>
                              <input type="hidden" name="drug_name" value="<?= htmlspecialchars($drug['drug_name']) ?>">
                            </div>

                            <label>Pharmacological Group *</label>
                            <select name="pharmacological_group" class="form-control" required>
                              <option value="">-- Select Group --</option>
                              <?php foreach($pharmaGroups as $group): ?>
                                <option value="<?= htmlspecialchars($group) ?>" <?= $drug['pharmacological_group']==$group?'selected':'' ?>><?= htmlspecialchars($group) ?></option>
                              <?php endforeach; ?>
                            </select>

                            <label>Drug Unit *</label>
                            <select name="drug_unit" class="form-control" required>
                              <option value="">-- Select Unit --</option>
                              <?php foreach($drugUnits as $unit): ?>
                                <option value="<?= htmlspecialchars($unit) ?>" <?= $drug['drug_unit']==$unit?'selected':'' ?>><?= htmlspecialchars($unit) ?></option>
                              <?php endforeach; ?>
                            </select>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
                            <button type="submit" name="update" class="btn btn-outline-primary btn-md">Update</button>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>

                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Drug Modal -->
<div class="modal fade" id="addDrugModal" 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 Drug</label>
        </div>
        <div class="modal-body">
          <label>Drug 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($drugNames as $dname): ?>
                  <li class="option-item" style="padding: .375rem .75rem; cursor: pointer;"><?= htmlspecialchars($dname) ?></li>
                <?php endforeach; ?>
              </ul>
            </div>
            <input type="hidden" name="drug_name">
          </div>

          <label>Pharmacological Group *</label>
          <select name="pharmacological_group" class="form-control" required>
            <option value="">-- Select Group --</option>
            <?php foreach($pharmaGroups as $group): ?>
              <option value="<?= htmlspecialchars($group) ?>"><?= htmlspecialchars($group) ?></option>
            <?php endforeach; ?>
          </select>

          <label>Drug Unit *</label>
          <select name="drug_unit" class="form-control" required>
            <option value="">-- Select Unit --</option>
            <?php foreach($drugUnits as $unit): ?>
              <option value="<?= htmlspecialchars($unit) ?>"><?= htmlspecialchars($unit) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="create" class="btn btn-outline-primary btn-md">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; ?>
