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

// ---------------- Facility Check ----------------
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'];

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

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

        $name = trim($_POST['name']);

        // ---- DUPLICATE CHECK PER FACILITY ----
        $stmt = $pdo->prepare("
            SELECT id 
            FROM medical_acts 
            WHERE facility_id = ? AND name = ?
            LIMIT 1
        ");
        $stmt->execute([$facility_id, $name]);
        if ($stmt->fetch()) {
            $_SESSION['flash'] = [
                'message' => 'Medical Act already exists in your facility. Duplication is not allowed.',
                'color'   => '#dc3545'
            ];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }

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

        $_SESSION['flash'] = [
            'message' => 'Medical Act 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']);
        $name = trim($_POST['name']);

        // ---- DUPLICATE CHECK PER FACILITY (EXCLUDE SELF) ----
        $stmt = $pdo->prepare("
            SELECT id 
            FROM medical_acts 
            WHERE facility_id = ? AND name = ? AND id != ?
            LIMIT 1
        ");
        $stmt->execute([$facility_id, $name, $id]);
        if ($stmt->fetch()) {
            $_SESSION['flash'] = [
                'message' => 'Medical Act already exists in your facility. Duplication is not allowed.',
                'color'   => '#dc3545'
            ];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }

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

        $_SESSION['flash'] = [
            'message' => 'Medical Act 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 medical_acts 
            SET status=? 
            WHERE id=? AND facility_id=?
        ");
        $stmt->execute([$currentStatus, $id, $facility_id]);

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

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

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

// ---------------- Fetch Distinct Names for Dropdown ----------------
$stmt = $pdo->prepare("
    SELECT DISTINCT name 
    FROM medical_acts 
    WHERE facility_id=? 
    ORDER BY name ASC
");
$stmt->execute([$facility_id]);
$actNames = $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">Medical Acts 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="#addActModal">Add Medical Act</button>
              </div>
            </div>

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

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

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

                          <div class="modal-header">
                            <h4>Edit Medical Act</h4>
                          </div>
                          <div class="modal-body">
                            <label>Act Name *</label>
                            <div class="form-control dropdown-search" style="position: relative; padding: 0; cursor: pointer;">
                              <div class="selected" style="padding: .375rem .75rem;"><?= htmlspecialchars($act['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($actNames as $name): ?>
                                    <li class="option-item" style="padding: .375rem .75rem; cursor: pointer;"><?= htmlspecialchars($name) ?></li>
                                  <?php endforeach; ?>
                                </ul>
                              </div>
                              <input type="hidden" name="name" value="<?= htmlspecialchars($act['name']) ?>">
                            </div>
                          </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 Medical Act Modal -->
<div class="modal fade" id="addActModal" 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 Medical Act</label>
        </div>
        <div class="modal-body">
          <label>Act 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($actNames as $name): ?>
                  <li class="option-item" style="padding: .375rem .75rem; cursor: pointer;"><?= htmlspecialchars($name) ?></li>
                <?php endforeach; ?>
              </ul>
            </div>
            <input type="hidden" name="name">
          </div>
        </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"]');

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

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

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

    searchInput.addEventListener('input', () => {
        filterOptions(searchInput.value);
        hiddenInput.value = searchInput.value;
        selected.textContent = searchInput.value;
    });

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