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


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

// ---------------- Medical Departments List ----------------
$deptOptions = [
    "General Medicine","Pediatrics","Cardiology","Dermatology","Emergency Medicine","Endocrinology",
    "Gastroenterology","Neurology","Oncology","Ophthalmology","Orthopedics","Otolaryngology (ENT)",
    "Psychiatry","Pulmonology","Radiology","Rheumatology","Urology","Nursing Care","Nephrology","Obstetrics & Gynecology (OB/GYN)","Adminstration",
    "Anesthesiology","Pathology","Physical Therapy / Rehabilitation","Surgery (General Surgery)",
    "Dental / Oral Health","Nutrition / Dietetics","Infectious Diseases","Emergency Trauma","Critical Care / ICU","Reception","Family Planning",
    "Laboratory Medicine","Pharmacy / Clinical Pharmacology","Community Health","Occupational Health",
    "Preventive Medicine","Health Education & Promotion","Medical Imaging / MRI / CT Scan","Sleep Medicine",
    "Genetics / Genomic Medicine","Pain Management","Neonatology","Geriatrics / Elderly Care"
];

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

    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) die("Invalid CSRF token");

    $facility_id = $_SESSION['facility_id']; // <-- Always use session, remove dropdown

    // ---------- CREATE ----------
    if (isset($_POST['create'])) {
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);

        $stmt = $pdo->prepare("INSERT INTO departments (facility_id, name, description, status) VALUES (?, ?, ?, 'enabled')");
        $stmt->execute([$facility_id, $name, $description]);

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

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

        $stmt = $pdo->prepare("UPDATE departments SET name=?, description=? WHERE id=? AND facility_id=?");
        $stmt->execute([$name, $description, $id, $facility_id]);

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

    // ---------- TOGGLE ENABLE/DISABLE ----------
    if (isset($_POST['toggle'])) {
        $id = intval($_POST['id']);
        $currentStatus = $_POST['current_status'] === 'enabled' ? 'disabled' : 'enabled';

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

        $statusText = $currentStatus=='enabled' ? 'Department enabled!' : 'Department disabled!';
        $statusColor = $currentStatus=='enabled' ? '#28a745' : '#dc3545';
        $_SESSION['flash'] = ['message'=>$statusText,'color'=>$statusColor];

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

// ---------------- Fetch Departments (facility-aware) ----------------
$departmentsStmt = $pdo->prepare("
    SELECT *
    FROM departments
    WHERE facility_id = :facility_id
    ORDER BY id DESC
");
$departmentsStmt->execute(['facility_id' => $_SESSION['facility_id']]);
$departments = $departmentsStmt->fetchAll(PDO::FETCH_ASSOC);
?>


<!-- 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">Departments 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="#addDeptModal">Add Department</button>
              </div>
            </div>

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

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

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

                          <div class="modal-header">
                            <h4>Edit Department</h4>
                          </div>
                          <div class="modal-body">
                            <label>Department Name *</label>
                            <input type="text" name="name" class="form-control" list="departmentListEdit<?= $dept['id'] ?>" 
                                   value="<?= htmlspecialchars($dept['name']) ?>" required placeholder="Type or select department">
                            <datalist id="departmentListEdit<?= $dept['id'] ?>">
                              <?php foreach($deptOptions as $opt): ?>
                                <option value="<?= htmlspecialchars($opt) ?>"><?= htmlspecialchars($opt) ?></option>
                              <?php endforeach; ?>
                            </datalist>

                            <label>Description</label>
                            <textarea name="description" class="form-control"><?= htmlspecialchars($dept['description']) ?></textarea>
                          </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 Department Modal -->
<div class="modal fade" id="addDeptModal" 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 Department</label>
        </div>
        <div class="modal-body">
          <label>Department Name *</label>
          <input type="text" name="name" class="form-control" list="departmentList" 
                 required placeholder="Type or select department" autocomplete="off">
          <datalist id="departmentList">
            <?php foreach($deptOptions as $opt): ?>
              <option value="<?= htmlspecialchars($opt) ?>"><?= htmlspecialchars($opt) ?></option>
            <?php endforeach; ?>
          </datalist>

          <label>Description</label>
          <textarea name="description" class="form-control" maxlength="255" placeholder="Optional description"></textarea>
        </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>

<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 for datalist suggestions */
input::-webkit-calendar-picker-indicator {
  display: none !important;
}

.form-control {
  height: 45px;
}

textarea.form-control {
  height: auto;
  min-height: 80px;
}
</style>

<script>
// Auto-complete enhancement
document.addEventListener('DOMContentLoaded', function() {
  // Focus on department input when modal opens
  $('#addDeptModal').on('shown.bs.modal', function () {
    $(this).find('input[name="name"]').focus();
  });
  
  // Focus on department input when edit modal opens
  $('[id^="editModal"]').on('shown.bs.modal', function () {
    $(this).find('input[name="name"]').focus().select();
  });
  
  // Prevent form submission on Enter key in input field (let user choose from dropdown)
  document.querySelectorAll('input[list]').forEach(input => {
    input.addEventListener('keydown', function(e) {
      if (e.key === 'Enter' && !this.getAttribute('data-selected')) {
        e.preventDefault();
      }
    });
    
    // Mark when user selects from dropdown
    input.addEventListener('input', function() {
      const options = document.getElementById(this.getAttribute('list')).options;
      for (let option of options) {
        if (option.value === this.value) {
          this.setAttribute('data-selected', 'true');
          return;
        }
      }
      this.removeAttribute('data-selected');
    });
  });
});
</script>

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

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