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

session_start();
include('includes/db.php');    // must set $pdo (PDO)
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'];

// ---------------- Lab Units ----------------
$labUnits = [
    "g/dL","mg/dL","mmol/L","μmol/L","U/L","UI/L","ng/mL","pg/mL",
    "fL","%","cells/μL","copies/mL","mEq/L","X 10^9/L","X 10^12/L",
    "X 10^6/μL","Ratio","Index","10^3/uL","pg","Min"
];

// ---------------- Lab Categories ----------------
$labCategories = [
    "Biochemistry","Hematology","Serology","Virology","Immunology",
    "Hormonology","Microbiology","Parasitology","Toxicology","Bactériologie"
];

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

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

    // ---------- CREATE LAB TEST ----------
    if (isset($_POST['create_lab_test'])) {

        $lab_test_name = trim($_POST['lab_test_name']);
        $category = $_POST['lab_test_category'] ?? '';
        $sub_names = $_POST['sub_name'] ?? [];
        $sub_mins  = $_POST['sub_min'] ?? [];
        $sub_maxs  = $_POST['sub_max'] ?? [];
        $sub_units = $_POST['sub_unit'] ?? [];

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

        if ($category !== '' && !in_array($category, $labCategories)) $category = null;

        try {
            $pdo->beginTransaction();

            // Insert lab test scoped to facility
            $stmt = $pdo->prepare("INSERT INTO lab_test (lab_test_name, category, status, facility_id) VALUES (?, ?, 'enabled', ?)");
            $stmt->execute([$lab_test_name, $category, $facility_id]);
            $lab_test_id = $pdo->lastInsertId();

            $subTestsArray = [];
            if(count($sub_names) > 0){
                $insertSub = $pdo->prepare("INSERT INTO sub_lab_test (lab_test_id, sub_test_name, min_value, max_value, lab_test_unit, status) VALUES (?, ?, ?, ?, ?, 'enabled')");
                for($i=0; $i<count($sub_names); $i++){
                    $name = trim($sub_names[$i]); if($name==='') continue;
                    $min = $sub_mins[$i]!==''?(float)$sub_mins[$i]:null;
                    $max = $sub_maxs[$i]!==''?(float)$sub_maxs[$i]:null;
                    $unit = in_array($sub_units[$i], $labUnits)?$sub_units[$i]:null;
                    $insertSub->execute([$lab_test_id, $name, $min, $max, $unit]);
                    $subTestsArray[] = ['name'=>$name,'min'=>$min,'max'=>$max,'unit'=>$unit];
                }
            }

            if(!empty($subTestsArray)){
                $pdo->prepare("UPDATE lab_test SET sub_tests=? WHERE id=?")->execute([json_encode($subTestsArray), $lab_test_id]);
            }

            $pdo->commit();
            $_SESSION['flash'] = ['message'=>'Lab Test added successfully!','color'=>'#28a745'];
        } catch(Exception $e){
            $pdo->rollBack();
            $_SESSION['flash'] = ['message'=>'Error: '.$e->getMessage(),'color'=>'#dc3545'];
        }

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

    // ---------- UPDATE LAB TEST ----------
    if (isset($_POST['update_lab_test'])) {

        $lab_test_id = intval($_POST['lab_test_id_edit']);
        $lab_test_name = trim($_POST['lab_test_name_edit']);
        $category = $_POST['lab_test_category_edit'] ?? '';
        $sub_names = $_POST['sub_name'] ?? [];
        $sub_mins  = $_POST['sub_min'] ?? [];
        $sub_maxs  = $_POST['sub_max'] ?? [];
        $sub_units = $_POST['sub_unit'] ?? [];

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

        if ($category !== '' && !in_array($category, $labCategories)) $category = null;

        try {
            $pdo->beginTransaction();

            // Update lab test scoped to facility
            $pdo->prepare("UPDATE lab_test SET lab_test_name=?, category=? WHERE id=? AND facility_id=?")
                ->execute([$lab_test_name, $category, $lab_test_id, $facility_id]);

            // Delete existing sub-tests
            $pdo->prepare("DELETE FROM sub_lab_test WHERE lab_test_id=?")->execute([$lab_test_id]);

            $subTestsArray = [];
            if(count($sub_names) > 0){
                $insertSub = $pdo->prepare("INSERT INTO sub_lab_test (lab_test_id, sub_test_name, min_value, max_value, lab_test_unit, status) VALUES (?, ?, ?, ?, ?, 'enabled')");
                for($i=0; $i<count($sub_names); $i++){
                    $name = trim($sub_names[$i]); if($name==='') continue;
                    $min = $sub_mins[$i]!==''?(float)$sub_mins[$i]:null;
                    $max = $sub_maxs[$i]!==''?(float)$sub_maxs[$i]:null;
                    $unit = in_array($sub_units[$i], $labUnits)?$sub_units[$i]:null;
                    $insertSub->execute([$lab_test_id, $name, $min, $max, $unit]);
                    $subTestsArray[] = ['name'=>$name,'min'=>$min,'max'=>$max,'unit'=>$unit];
                }
            }

            $pdo->prepare("UPDATE lab_test SET sub_tests=? WHERE id=?")->execute([json_encode($subTestsArray), $lab_test_id]);

            $pdo->commit();
            $_SESSION['flash'] = ['message'=>'Lab Test updated successfully!','color'=>'#007bff'];
        } catch(Exception $e){
            $pdo->rollBack();
            $_SESSION['flash'] = ['message'=>'Error: '.$e->getMessage(),'color'=>'#dc3545'];
        }

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

    // ---------- TOGGLE STATUS ----------
    if (isset($_POST['toggle_lab_test'])) {
        $id = intval($_POST['lab_test_toggle_id']);
        $currentStatus = $_POST['lab_test_current_status'] === 'enabled' ? 'disabled' : 'enabled';
        $pdo->prepare("UPDATE lab_test SET status=? WHERE id=? AND facility_id=?")->execute([$currentStatus,$id,$facility_id]);
        $_SESSION['flash'] = [
            'message'=>$currentStatus==='enabled'?'Lab Test enabled!':'Lab Test disabled!',
            'color'=>$currentStatus==='enabled'?'#28a745':'#dc3545'
        ];
        header("Location: ".$_SERVER['PHP_SELF']); exit;
    }
}

// ---------------- Fetch Data ----------------
$labTests = $pdo->prepare("SELECT * FROM lab_test WHERE facility_id=? ORDER BY lab_test_name ASC");
$labTests->execute([$facility_id]);
$labTests = $labTests->fetchAll(PDO::FETCH_ASSOC);

$subStmt = $pdo->query("SELECT * FROM sub_lab_test ORDER BY lab_test_id, id ASC")->fetchAll(PDO::FETCH_ASSOC);
$subByLab = [];
foreach($subStmt as $r) $subByLab[$r['lab_test_id']][] = $r;
?>


<!-- Toast container -->
<div aria-live="polite" aria-atomic="true" style="position: fixed; top: 1rem; right: 1rem; z-index: 9999;">
  <div id="toast-container"></div>
</div>

<!-- 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">Lab Tests</h4></div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">

            <div class="row mb-2">
              <div class="col-lg-6 col-md-8 col-sm-12">
                <button class="btn btn-outline-primary btn-md" data-toggle="modal" data-target="#addLabModal">Add Lab Test</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Lab Test Name</th>
                    <th>Category</th>
                    <th>Sub Tests Count</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $i=1; foreach($labTests as $lab):
                        $subs = $subByLab[$lab['id']] ?? [];
                  ?>
                  <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($lab['lab_test_name']) ?></td>
                    <td><?= htmlspecialchars($lab['category'] ?? '') ?></td>
                    <td>
                      <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#subTestModal<?= $lab['id'] ?>">Sub Test</button>
                    </td>
                    <td style="color:<?= $lab['status']=='enabled'?'#28a745':'#dc3545' ?>; font-weight:bold;"><?= ucfirst($lab['status']) ?></td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editLabModal<?= $lab['id'] ?>">Edit</button>
                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="lab_test_toggle_id" value="<?= $lab['id'] ?>">
                        <input type="hidden" name="lab_test_current_status" value="<?= $lab['status'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="toggle_lab_test" class="btn btn-sm <?= $lab['status']=='enabled'?'btn-secondary':'btn-success' ?>"><?= $lab['status']=='enabled'?'Disable':'Enable' ?></button>
                      </form>
                    </td>
                  </tr>

                  <!-- Sub Test Modal -->
                  <div class="modal fade" id="subTestModal<?= $lab['id'] ?>" tabindex="-1">
                    <div class="modal-dialog modal-dialog-centered">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h5 class="modal-title">Sub Tests for "<?= htmlspecialchars($lab['lab_test_name']) ?>"</h5>
                          <button type="button" class="close" data-dismiss="modal">&times;</button>
                        </div>
                        <div class="modal-body">
                          <?php if(count($subs)>0): ?>
                            <ul class="list-group">
                              <?php foreach($subs as $s): ?>
                                <li class="list-group-item">
                                  <strong><?= htmlspecialchars($s['sub_test_name']) ?></strong>
                                  <?= ($s['min_value']!==null || $s['max_value']!==null) ? ": {$s['min_value']} &nbsp|&nbsp {$s['max_value']}" : '' ?>
                                  &nbsp|&nbsp<?= $s['lab_test_unit'] ? htmlspecialchars($s['lab_test_unit']) : '' ?>
                                </li>
                              <?php endforeach; ?>
                            </ul>
                          <?php else: ?>
                            <p>No sub tests available.</p>
                          <?php endif; ?>
                        </div>
                        <div class="modal-footer"><button class="btn btn-secondary" data-dismiss="modal">Close</button></div>
                      </div>
                    </div>
                  </div>

                  <!-- Edit Lab Modal -->
                  <div class="modal fade" id="editLabModal<?= $lab['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="lab_test_id_edit" value="<?= $lab['id'] ?>">
                          <div class="modal-header"><h4>Edit Lab Test</h4></div>
                          <div class="modal-body">
                            <label>Lab Test Name *</label>
                            <input type="text" name="lab_test_name_edit" class="form-control" required value="<?= htmlspecialchars($lab['lab_test_name']) ?>">
                            <label class="mt-2">Category *</label>
                            <select name="lab_test_category_edit" class="form-control" required>
                              <option value="">-- Select Category --</option>
                              <?php foreach($labCategories as $cat): ?>
                                <option value="<?= $cat ?>" <?= ($lab['category'] ?? '') === $cat ? 'selected':'' ?>><?= $cat ?></option>
                              <?php endforeach; ?>
                            </select>
                            <hr>
                            <h5>Sub Tests</h5>
                            <div id="sub-rows-edit-<?= $lab['id'] ?>">
                              <?php 
                                if(count($subs)==0) $subs[] = ['sub_test_name'=>'','min_value'=>null,'max_value'=>null,'lab_test_unit'=>''];
                                foreach($subs as $s):
                              ?>
                              <div class="sub-row form-row mb-2">
                                <div class="col" style="display:inline-block;width:15%;"><input type="text" name="sub_name[]" class="form-control" placeholder="Name" value="<?= htmlspecialchars($s['sub_test_name']) ?>"></div>
                                <div class="col" style="display:inline-block;width:24%; margin-left:8px;"><input type="text" name="sub_min[]" class="form-control" placeholder="Min" value="<?= $s['min_value']!==null?$s['min_value']:'' ?>"></div>
                                <div class="col" style="display:inline-block;width:24%; margin-left:8px;"><input type="text" name="sub_max[]" class="form-control" placeholder="Max" value="<?= $s['max_value']!==null?$s['max_value']:'' ?>"></div>
                                <div class="col" style="display:inline-block;width:20%; margin-left:8px;">
                                  <select name="sub_unit[]" class="form-control">
                                    <option value="">-- Unit --</option>
                                    <?php foreach($labUnits as $u): ?>
                                      <option value="<?= $u ?>" <?= ($s['lab_test_unit'] ?? '') === $u ? 'selected':'' ?>><?= $u ?></option>
                                    <?php endforeach; ?>
                                  </select>
                                </div>
                                <div class="col" style="display:inline-block;width:5%; margin-left:8px;">
                                  <button type="button" class="btn btn-outline-danger btn-sm remove-sub-btn">×</button>
                                </div>
                              </div>
                              <?php endforeach; ?>
                            </div>
                            <div class="text-left mb-2">
                              <button type="button" class="btn btn-outline-primary btn-sm add-sub-btn-edit" data-target="#sub-rows-edit-<?= $lab['id'] ?>">Add Sub Test</button>
                            </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_lab_test" class="btn btn-outline-primary btn-md">Update</button>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>

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

          </div>
        </div>
      </div>
    </div>

    <!-- Add Lab Modal -->
    <div class="modal fade" id="addLabModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <form method="post">
            <input type="hidden" name="csrf" value="<?= $csrf ?>">
            <div class="modal-header"><h4>Add Lab Test</h4></div>
            <div class="modal-body">
              <label>Lab Test Name *</label>
              <input type="text" name="lab_test_name" class="form-control" required>
              <label class="mt-2">Category *</label>
              <select name="lab_test_category" class="form-control" required>
                <option value="">-- Select Category --</option>
                <?php foreach($labCategories as $cat): ?>
                  <option value="<?= $cat ?>"><?= $cat ?></option>
                <?php endforeach; ?>
              </select>
              <hr>
              <h5>Sub Tests</h5>
              <div id="sub-rows-add">
                <div class="sub-row form-row mb-2">
                  <div class="col" style="display:inline-block;width:15%; margin-left:8px;"><input type="text" name="sub_name[]" class="form-control" placeholder="Name"></div>
                  <div class="col" style="display:inline-block;width:24%; margin-left:8px;"><input type="text" name="sub_min[]" class="form-control" placeholder="Min"></div>
                  <div class="col" style="display:inline-block;width:24%; margin-left:8px;"><input type="text" name="sub_max[]" class="form-control" placeholder="Max"></div>
                  <div class="col" style="display:inline-block;width:20%; margin-left:8px;">
                    <select name="sub_unit[]" class="form-control">
                      <option value="">-- Unit --</option>
                      <?php foreach($labUnits as $u): ?>
                        <option value="<?= $u ?>"><?= $u ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                  <div class="col" style="display:inline-block;width:5%; margin-left:8px;">
                    <button type="button" class="btn btn-outline-danger btn-sm remove-sub-btn">×</button>
                  </div>
                </div>
              </div>
              <div class="text-left mb-2">
                <button type="button" id="sub-rows-add-btn" class="btn btn-outline-primary btn-sm">Add Sub Test</button>

              </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_lab_test" class="btn btn-outline-primary btn-md">Add Lab Test</button>
            </div>
          </form>
        </div>
      </div>
    </div>

  </div>
</div>
<script>
// Lab Units array
const labUnits = ["g/dL","mg/dL","mmol/L","μmol/L","U/L","UI/L","ng/mL","pg/mL",
                  "fL","%","cells/μL","copies/mL","mEq/L","X 10^9/L","X 10^12/L",
                  "X 10^6/μL","Ratio","Index","10^3/uL","pg","Min"];

// Generate options for unit select
function getUnitOptions(selected='') {
    let options = '<option value="">-- Unit --</option>';
    labUnits.forEach(u => {
        options += `<option value="${u}" ${selected === u ? 'selected':''}>${u}</option>`;
    });
    return options;
} 

// Add Sub Test row dynamically
function addSubRow(containerSelector, subData={}) {
    const container = document.querySelector(containerSelector);
    if(!container) return;

    const div = document.createElement('div');
    div.className = 'sub-row form-row mb-2';
    div.innerHTML = `
        <div class="col" style="display:inline-block;width:15%;"><input type="text" name="sub_name[]" class="form-control" placeholder="Name" value="${subData.name ?? ''}"></div>
        <div class="col" style="display:inline-block;width:24%; margin-left:8px;"><input type="text" name="sub_min[]" class="form-control" placeholder="Min" value="${subData.min ?? ''}"></div>
        <div class="col" style="display:inline-block;width:24%; margin-left:8px;"><input type="text" name="sub_max[]" class="form-control" placeholder="Max" value="${subData.max ?? ''}"></div>
        <div class="col" style="display:inline-block;width:20%; margin-left:8px;">
            <select name="sub_unit[]" class="form-control">${getUnitOptions(subData.unit ?? '')}</select>
        </div>
        <div class="col" style="display:inline-block;width:5%; margin-left:8px;">
            <button type="button" class="btn btn-outline-danger btn-sm remove-sub-btn">×</button>
        </div>
    `;
    container.appendChild(div);
}

// Remove Sub Test row dynamically
document.addEventListener('click', function(e){
    if(e.target.classList.contains('remove-sub-btn')){
        const row = e.target.closest('.sub-row');
        if(row) row.remove();
    }
});

// Initialize Add/Edit modals buttons
document.addEventListener('DOMContentLoaded', function(){
    // Add button for Add modal
    const addBtnAddModal = document.querySelector('#sub-rows-add-btn');
    if(addBtnAddModal){
        addBtnAddModal.addEventListener('click', function(){
            addSubRow('#sub-rows-add');
        });
    }

    // Add buttons for Edit modals
    document.querySelectorAll('.add-sub-btn-edit').forEach(btn=>{
        btn.addEventListener('click', function(){
            const target = btn.getAttribute('data-target'); // container ID
            addSubRow(target);
        });
    });

    // Toast messages
    <?php if(!empty($_SESSION['flash'])):
        $msg = $_SESSION['flash']['message'];
        $color = $_SESSION['flash']['color'];
        unset($_SESSION['flash']);
    ?>
    const toast = document.createElement('div');
    toast.innerText = <?= json_encode($msg) ?>;
    toast.style.position = 'fixed';
    toast.style.top = '20px';
    toast.style.right = '20px';
    toast.style.padding = '15px 25px';
    toast.style.background = <?= json_encode($color) ?>;
    toast.style.color = '#fff';
    toast.style.borderRadius = '5px';
    toast.style.zIndex = 9999;
    toast.style.boxShadow = '0 0 10px rgba(0,0,0,0.2)';
    document.body.appendChild(toast);
    setTimeout(()=>{ toast.remove(); }, 4000);
    <?php endif; ?>
});
</script>


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