<?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 - cast to integer and ensure it's positive
    $facility_id = (int) $_SESSION['facility_id'];
    if ($facility_id <= 0) {
        session_unset();
        session_destroy();
        header("Location: login.php?error=invalid_facility");
        exit;
    }
    
    // Ensure it's treated as unsigned (positive only)
    return abs($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'];

// ---------------- Handle CRUD for imaging ----------------
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;
        }

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

        if ($name === '') {
            $_SESSION['flash'] = [
                'message' => 'Imaging name is required',
                'color'   => '#dc3545'
            ];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }

        try {
            // Check if imaging already exists for this facility
            $checkStmt = $pdo->prepare("
                SELECT id FROM imaging 
                WHERE name = ? AND (facility_id = ? OR facility_id IS NULL)
                LIMIT 1
            ");
            $checkStmt->execute([$name, $facility_id]);
            
            if ($checkStmt->fetch()) {
                $_SESSION['flash'] = [
                    'message' => 'Imaging with this name already exists',
                    'color'   => '#dc3545'
                ];
                header("Location: ".$_SERVER['PHP_SELF']);
                exit;
            }
            
            // Insert new imaging
            $stmt = $pdo->prepare("
                INSERT INTO imaging (facility_id, name, description, status, created_at, updated_at) 
                VALUES (?, ?, ?, 'enabled', NOW(), NOW())
            ");
            $stmt->execute([$facility_id, $name, $description]);

            $_SESSION['flash'] = ['message'=>'Imaging added successfully!','color'=>'#28a745'];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        } catch (Exception $e) {
            $_SESSION['flash'] = [
                'message' => 'Error: ' . $e->getMessage(),
                'color'   => '#dc3545'
            ];
            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'];
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);

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

        try {
            // Check if another imaging with same name exists
            $checkStmt = $pdo->prepare("
                SELECT id FROM imaging 
                WHERE name = ? AND id != ? AND (facility_id = ? OR facility_id IS NULL)
                LIMIT 1
            ");
            $checkStmt->execute([$name, $id, $facility_id]);
            
            if ($checkStmt->fetch()) {
                $_SESSION['flash'] = [
                    'message' => 'Another imaging with this name already exists',
                    'color'   => '#dc3545'
                ];
                header("Location: ".$_SERVER['PHP_SELF']);
                exit;
            }
            
            // Update imaging
            $stmt = $pdo->prepare("
                UPDATE imaging 
                SET name = ?, 
                    description = ?, 
                    updated_at = NOW()
                WHERE id = ? 
                  AND (facility_id = ? OR facility_id IS NULL)
            ");
            $stmt->execute([$name, $description, $id, $facility_id]);

            $_SESSION['flash'] = ['message'=>'Imaging updated successfully!','color'=>'#007bff'];
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        } catch (Exception $e) {
            $_SESSION['flash'] = [
                'message' => 'Error: ' . $e->getMessage(),
                'color'   => '#dc3545'
            ];
            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'];
        $newStatus = $currentStatus === 'enabled' ? 'disabled' : 'enabled';

        $stmt = $pdo->prepare("
            UPDATE imaging 
            SET status = ?, updated_at = NOW()
            WHERE id = ? 
              AND (facility_id = ? OR facility_id IS NULL)
        ");
        $stmt->execute([$newStatus, $id, $facility_id]);

        $statusText  = $newStatus === 'enabled' ? 'Imaging enabled!' : 'Imaging disabled!';
        $statusColor = $newStatus === 'enabled' ? '#28a745' : '#dc3545';

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

// ---------------- Fetch Imaging ----------------
$stmt = $pdo->prepare("
    SELECT 
        i.id, 
        i.name, 
        i.description, 
        i.status, 
        i.created_at,
        i.updated_at,
        f.name as facility_name
    FROM imaging i
    LEFT JOIN facility f ON f.id = i.facility_id
    WHERE i.facility_id = ? OR i.facility_id IS NULL
    ORDER BY 
        CASE WHEN i.facility_id IS NULL THEN 0 ELSE 1 END, -- Global types first
        i.name
");
$stmt->execute([$facility_id]);
$imagingTypes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Fetch Distinct Names for Dropdown ----------------
$stmt = $pdo->prepare("
    SELECT DISTINCT name 
    FROM imaging 
    WHERE (facility_id = ? OR facility_id IS NULL) 
      AND status = 'enabled'
    ORDER BY name ASC
");
$stmt->execute([$facility_id]);
$typeNames = $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">Imaging 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="#addImagingModal">Add Imaging</button>
              </div>
            </div>

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

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

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

                          <div class="modal-header">
                            <h4>Edit Imaging</h4>
                          </div>
                          <div class="modal-body">
                            <label>Name *</label>
                            <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($type['name']) ?>" required>

                            <label>Description</label>
                            <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($type['description'] ?? '') ?></textarea>
                            
                            <div class="mt-2">
                              <small class="text-muted">
                                <?php if($type['facility_name']): ?>
                                  This is a facility-specific imaging for: <?= htmlspecialchars($type['facility_name']) ?>
                                <?php else: ?>
                                  This is a global imaging available to all facilities
                                <?php endif; ?>
                              </small>
                            </div>
                          </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>

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

          <label>Description</label>
          <textarea name="description" class="form-control" rows="3"></textarea>
          
          <div class="mt-2">
            <small class="text-muted">
              This imaging will be created for your facility: <?= htmlspecialchars($_SESSION['facility_name'] ?? 'Current Facility') ?>
            </small>
          </div>
        </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>
// Only apply dropdown search to add modal, not edit modals
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);
}

/* Table styling */
.table-responsive {
  margin-top: 20px;
}

.badge {
  font-size: 0.85em;
  padding: 0.35em 0.65em;
}
</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; ?>