<?php
require_once('./include/config.php');

$userType = strtolower(trim($sess_user_type));

$isSuperAdmin = ($userType == 'superadmin');
$isAdmin      = ($userType == 'admin');

$page_title = 'Dashboard';

// Fetch filters
$departments = mysqli_query($conn, "SELECT id, department FROM tbl_doctor_form");
$wards = mysqli_query($conn, "SELECT DISTINCT ward FROM tbl_medication_errors WHERE ward IS NOT NULL AND ward != ''");
$severities = mysqli_query($conn, "SELECT * FROM tbl_severity");
$errorTypes = mysqli_query($conn, "SELECT * FROM tbl_error_type");
$positions = mysqli_query($conn, "SELECT DISTINCT position FROM tbl_medication_errors WHERE position IS NOT NULL AND position != ''");
$medErrors = mysqli_query($conn, "SELECT DISTINCT med_error_code FROM tbl_medication_errors WHERE med_error_code IS NOT NULL AND med_error_code != ''");
// Fetch user's mapped locations
$userqry = mysqli_query($conn, "
    SELECT u_loc
    FROM tbl_users
    WHERE u_emp_id = '$sess_user_id'
    LIMIT 1
");

$userres = mysqli_fetch_assoc($userqry);
$user_locations = trim($userres['u_loc'] ?? '');

// Get logged in user's mapped locations
$userqry = mysqli_query($conn, "
    SELECT u_loc
    FROM tbl_users
    WHERE u_emp_id = '$sess_user_id'
    LIMIT 1
");

$userres = mysqli_fetch_assoc($userqry);
$user_locations = trim($userres['u_loc'] ?? '');

if ($isSuperAdmin) {

    $locations = mysqli_query($conn, "
        SELECT h_id,h_loc,h_loc_id
        FROM tbl_hospital_master
        ORDER BY h_loc ASC
    ");

} else {

    $locations = mysqli_query($conn, "
        SELECT h_id,h_loc,h_loc_id
        FROM tbl_hospital_master
        WHERE FIND_IN_SET(h_loc_id,'$user_locations')
        ORDER BY h_loc ASC
    ");
}

// Fetch all records with joins
// Fetch dashboard records

if ($isSuperAdmin) {

    $query = "
    SELECT
        me.*,
        COALESCE(s.severity_name, me.severity) AS severity_name,
        COALESCE(et.error_type, me.error_type) AS error_type_name,
        COALESCE(st.subtype_name, me.sub_category) AS sub_type,
        COALESCE(pc.category_name, me.pharma_category) AS pharma_category_name,
        COALESCE(ar.adr_type_name, me.adr_reporting) AS adr_reporting_name,
        COALESCE(dr.recall_type_name, me.drug_recalls) AS drug_recalls_name,
        COALESCE(h.h_loc, me.h_loc_s) AS location_name,
        COALESCE(d.department, me.department) AS department_name
    FROM tbl_medication_errors me
    LEFT JOIN tbl_severity s ON me.severity=s.id
    LEFT JOIN tbl_error_type et ON me.error_type=et.id
    LEFT JOIN tbl_error_subtype st ON me.sub_category=st.id
    LEFT JOIN tbl_pharmacological_category pc ON me.pharma_category=pc.id
    LEFT JOIN tbl_adr ar ON me.adr_reporting=ar.id
    LEFT JOIN tbl_drug_recall_type dr ON me.drug_recalls=dr.id
    LEFT JOIN tbl_hospital_master h ON me.h_loc_s=h.h_loc_id
    LEFT JOIN tbl_doctor_form d ON me.department=d.id
    ORDER BY me.id DESC";
}
else {

    $query = "
    SELECT
        me.*,
        COALESCE(s.severity_name, me.severity) AS severity_name,
        COALESCE(et.error_type, me.error_type) AS error_type_name,
        COALESCE(st.subtype_name, me.sub_category) AS sub_type,
        COALESCE(pc.category_name, me.pharma_category) AS pharma_category_name,
        COALESCE(ar.adr_type_name, me.adr_reporting) AS adr_reporting_name,
        COALESCE(dr.recall_type_name, me.drug_recalls) AS drug_recalls_name,
        COALESCE(h.h_loc, me.h_loc_s) AS location_name,
        COALESCE(d.department, me.department) AS department_name
    FROM tbl_medication_errors me
    LEFT JOIN tbl_severity s ON me.severity=s.id
    LEFT JOIN tbl_error_type et ON me.error_type=et.id
    LEFT JOIN tbl_error_subtype st ON me.sub_category=st.id
    LEFT JOIN tbl_pharmacological_category pc ON me.pharma_category=pc.id
    LEFT JOIN tbl_adr ar ON me.adr_reporting=ar.id
    LEFT JOIN tbl_drug_recall_type dr ON me.drug_recalls=dr.id
    LEFT JOIN tbl_hospital_master h ON me.h_loc_s=h.h_loc_id
    LEFT JOIN tbl_doctor_form d ON me.department=d.id
    WHERE FIND_IN_SET(me.h_loc_s,'$user_locations')
    ORDER BY me.id DESC";
}

$sql = mysqli_query($conn, $query);

if (!$sql) {
    die("Query failed: " . mysqli_error($conn));
}

// CSV Download
if (isset($_POST['download'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=medication_errors.csv');

    $output = fopen('php://output', 'w');

    fputcsv($output, [
        'ID', 'Med Error Code', 'Group', 'Region', 'Location', 'Position',
        'Positioner Name', 'Error Datetime', 'Occurrence Time', 'Patient Details',
        'Doctor Name', 'Resident Name', 'Ward', 'Other Ward', 'Department',
        'Other Department', 'Severity', 'High Alert', 'Drug Involved', 'Error Type',
        'Sub Type', 'Pharma Category', 'ADR Reporting', 'ADR - Suspected Drug',
        'ADR - Drug Category', 'ADR - Dose Route', 'ADR - Date of Reaction',
        'ADR - Description of Reaction', 'ADR - Outcome Follow-up',
        'ADR - Rechallenge Details', 'ADR - Severity Level', 'ADR - Prevention',
        'ADR - Actions', 'ADR - Reported CP', 'ADR - Reporter Details',
        'Drug Recalls', 'Product Name', 'Batch Number', 'Manufacture', 'Reason', 'Availability',
        'Admin Error', 'Error Description', 'Error Made By', 'Intervention',
        'Root Cause', 'Action Taken'
    ]);

    $query = mysqli_query($conn, "SELECT * FROM tbl_medication_errors ORDER BY id DESC");
    while ($row = mysqli_fetch_assoc($query)) {
        $adrParts = array_pad(explode(',', $row['adr_types'] ?? ''), 12, '');
        fputcsv($output, [
            $row['id'], $row['med_error_code'], $row['h_grp'], $row['h_reg'],
            $row['h_loc_s'], $row['position'], $row['position_name'],
            $row['error_datetime'], $row['occurrence_time'], $row['patient_details'],
            $row['doctor_name'], $row['resident_name'], $row['ward'], $row['other_ward'],
            $row['department'], $row['other_department'], $row['severity'],
            $row['high_alert'], $row['drug_involved'], $row['error_type'],
            $row['sub_category'], $row['pharma_category'], $row['adr_reporting'],
            trim($adrParts[0]),  // Suspected Drug
            trim($adrParts[1]),  // Drug Category
            trim($adrParts[2]),  // Dose Route
            trim($adrParts[3]),  // Date of Reaction
            trim($adrParts[4]),  // Description of Reaction
            trim($adrParts[5]),  // Outcome Follow-up
            trim($adrParts[6]),  // Rechallenge Details
            trim($adrParts[7]),  // Severity Level
            trim($adrParts[8]),  // Prevention
            trim($adrParts[9]),  // Actions
            trim($adrParts[10]), // Reported CP
            trim($adrParts[11]), // Reporter Details
            $row['drug_recalls'], $row['product_name'],
            $row['batch_number'], $row['manufacture'], $row['reason'],
            $row['availability'], $row['admin_error'], $row['error_description'],
            $row['error_made_by'], $row['intervention'], $row['root_cause'],
            $row['action_taken']
        ]);
    }
    fclose($output);
    exit;
}

// Handle Edit
if (isset($_POST['edit'])) {
    $id = intval($_POST['id']);

    $fields = [
        'med_error_code', 'h_grp', 'h_reg', 'h_loc_s', 'position', 'position_name',
        'error_datetime', 'occurrence_time', 'patient_details', 'doctor_name',
        'resident_name', 'ward', 'other_ward', 'department', 'other_department',
        'severity', 'high_alert', 'drug_involved', 'error_type', 'sub_category',
        'pharma_category',
        'adr_reporting',
        'drug_recalls', 'product_name', 'batch_number', 'manufacture', 'reason', 'availability',
        'admin_error', 'error_description', 'error_made_by', 'intervention',
        'root_cause', 'action_taken'
    ];

    $updates = [];
    foreach ($fields as $field) {
        if (isset($_POST[$field])) {
            $updates[] = "$field='" . mysqli_real_escape_string($conn, $_POST[$field]) . "'";
        }
    }

    // Re-join ADR sub-fields into adr_types CSV
    $adrSubFields = [
        'adr_suspected_drug', 'adr_drug_category', 'adr_dose_route',
        'adr_date_reaction',  'adr_description',    'adr_outcome',
        'adr_rechallenge',    'adr_severity_level', 'adr_prevention',
        'adr_actions',        'adr_reported_cp',    'adr_reporter_details',
    ];
    $adrParts = [];
    foreach ($adrSubFields as $f) {
        $adrParts[] = mysqli_real_escape_string($conn, $_POST[$f] ?? '');
    }
    $updates[] = "adr_types='" . implode(',', $adrParts) . "'";

    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        $fileName = time() . '_' . basename($_FILES['attachment']['name']);
        $targetFile = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['attachment']['tmp_name'], $targetFile)) {
            $updates[] = "attachment='" . mysqli_real_escape_string($conn, $targetFile) . "'";
        }
    }

    if (!empty($updates)) {
        $sqlUpdate = "UPDATE tbl_medication_errors SET " . implode(", ", $updates) . " WHERE id=$id";
        if (mysqli_query($conn, $sqlUpdate)) {
            echo "<script>alert('Record updated successfully'); window.location.href=window.location.href;</script>";
            exit;
        } else {
            echo "<script>alert('Error updating record: " . mysqli_error($conn) . "');</script>";
        }
    }
}

// Handle Delete
if (isset($_POST['delete'])) {
    $id = intval($_POST['id']);
    $fileQuery = mysqli_query($conn, "SELECT attachment FROM tbl_medication_errors WHERE id=$id");
    if ($fileQuery && mysqli_num_rows($fileQuery) > 0) {
        $fileRow = mysqli_fetch_assoc($fileQuery);
        if (!empty($fileRow['attachment']) && file_exists($fileRow['attachment']))
            unlink($fileRow['attachment']);
    }
    $sqlDelete = "DELETE FROM tbl_medication_errors WHERE id=$id";
    $result = mysqli_query($conn, $sqlDelete);
    if ($result) {
        echo "<script>alert('Record deleted successfully'); window.location.href=window.location.href;</script>";
        exit;
    } else {
        echo "<script>alert('Error deleting record: " . mysqli_error($conn) . "');</script>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="icon" type="image/png" href="./assets/img/logo_white_icon.png">
  <title><?php echo $page_title; ?> | <?php echo $app_name; ?></title>

  <link rel="stylesheet" type="text/css"
    href="https://fonts.googleapis.com/css?family=Noto+Sans:300,400,500,700,900|Lato:300,400,500,700,900|Roboto+Slab:400,700" />
  <link href="./assets/css/nucleo-icons.css" rel="stylesheet" />
  <link href="./assets/css/nucleo-svg.css" rel="stylesheet" />
  <link rel="icon" type="image/png" href="./assets/img/favicon.png">
  <script src="https://kit.fontawesome.com/cf31b92a35.js" crossorigin="anonymous"></script>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons+Round" rel="stylesheet">
  <link href="./assets/css/material-dashboard.css" rel="stylesheet" />
  <link href="./assets/css/table.css" rel="stylesheet" />
  <link href="./assets/css/select2.min.css" rel="stylesheet" />
  <link href="./assets/css/pqselect.dev.css" rel="stylesheet" />
  <link href="./assets/css/jquery-ui.css" rel="Stylesheet" type="text/css" />
  <link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.2.96/css/materialdesignicons.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
</head>

<style>
  body { font-family: 'Poppins', sans-serif; background: #f4f6f9; }

  .form-control, .form-select, textarea.form-control {
    border: 1px solid #000 !important;
  }

  .filter-container {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    margin-bottom: 25px;
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #2582A1;
  }

  .filter-header h4 { color: #2582A1; font-weight: 600; margin: 0; }

  .filter-toggle-btn {
    background: #2582A1; color: white; border: none;
    padding: 8px 20px; border-radius: 5px; cursor: pointer; transition: all 0.3s;
  }
  .filter-toggle-btn:hover { background: #1a5d73; transform: translateY(-2px); }

  .filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
  }

  .filter-group { display: flex; flex-direction: column; }
  .filter-group label { font-weight: 600; color: #333; margin-bottom: 8px; font-size: 13px; }
  .filter-group select, .filter-group input {
    padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;
  }
  .filter-group select:focus, .filter-group input:focus {
    border-color: #2582A1; outline: none;
    box-shadow: 0 0 0 3px rgba(37,130,161,0.1);
  }

  .filter-icon-btn {
    width: 46px;
    height: 46px;
    padding: 0;
    border: none;
    border-radius: 8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    box-shadow: 0 3px 7px rgba(0,0,0,0.16);
    transition: background 0.3s, transform 0.2s, box-shadow 0.2s;
  }
  .filter-icon-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 10px rgba(0,0,0,0.2);
  }
  .filter-icon-btn i { pointer-events: none; }
  .filter-action-col {
    flex: 0 0 auto;
    width: auto;
    display: flex;
    align-items: flex-end;
  }
  .filter-action-col form { width: auto; }
  .filter-location-col { position: relative; }

  .filter-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 10px; }

  .table-responsive {
    overflow-x: auto; background: white;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  }

  table th, table td { white-space: nowrap; font-size: 13px; }
  thead { background: linear-gradient(135deg, #2582A1, #1a5d73); color: #fff; }
  thead th {
    padding: 15px; text-align: left; font-size: 13px;
    letter-spacing: 0.5px; text-transform: uppercase; font-weight: 600;
  }
  tbody tr { border-bottom: 1px solid #f0f0f0; }
  tbody tr:nth-child(even) { background: #f9f9f9; }
  tbody tr:hover { background: #f1f7ff; }
  tbody td { padding: 14px 15px; font-size: 13px; color: #333; }

  .dt-button {
    background: #2582A1 !important; color: white !important; border: none !important;
    padding: 8px 15px !important; border-radius: 5px !important; margin-right: 5px !important;
  }
  .dt-button:hover { background: #1a5d73 !important; }

  .dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: #2582A1 !important; border-color: #2582A1 !important; color: white !important;
  }

  /* Toggle sub-sections in edit modal */
  .toggle-section {
    border: 1px solid #2582A1;
    border-radius: 8px;
    padding: 15px;
    background: #f0f8fb;
    margin-top: 5px;
  }

  .toggle-section .section-title {
    font-weight: 700;
    color: #2582A1;
    margin-bottom: 12px;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  /* ADR sub-field label styling */
  .adr-field-label {
    font-size: 12px;
    font-weight: 600;
    color: #1a5d73;
    margin-bottom: 4px;
  }

  @media (max-width:768px) {
    .filter-grid { grid-template-columns: 1fr; }
    .filter-action-col { width: auto; }
  }

#filterLocation {
    position: absolute !important;
    width: 1px !important;
    height: 1px !important;
    padding: 0 !important;
    overflow: hidden !important;
    clip: rect(0, 0, 0, 0) !important;
    white-space: nowrap !important;
    border: 0 !important;
}

.location-picker { position: relative; }
.location-picker-control {
    height: 46px !important;
    min-height: 46px !important;
    border: 1px solid #ced4da !important;
    border-radius: 6px !important;
    padding: 0 12px !important;
    display: flex !important;
    align-items: center !important;
    overflow: hidden !important;
    background: #fff;
    color: #333;
    cursor: pointer;
    width: 100%;
    text-align: left;
}

.location-picker-panel {
    display: none;
    position: absolute;
    top: calc(100% + 3px);
    left: 0;
    z-index: 99999;
    width: min(520px, 92vw);
    background: #fff;
    border: 1px solid #b7cfe4;
    border-radius: 5px;
    box-shadow: 0 3px 10px rgba(0,0,0,0.18);
    overflow: hidden;
}
.location-picker.open .location-picker-panel { display: block; }
.location-select-all {
    background: #dff0fb;
    border-bottom: 1px solid #b7cfe4;
    padding: 3px 8px;
    color: #222;
    line-height: 22px;
}
.location-picker-search {
    border: 0 !important;
    border-bottom: 1px solid #d7dce0 !important;
    border-radius: 0 !important;
    height: 28px;
    padding: 3px 6px !important;
    width: 100%;
    outline: none;
}
.location-picker-list {
    max-height: 285px;
    overflow-y: auto;
    padding: 4px 8px;
}
.location-picker-option {
    display: flex;
    align-items: center;
    gap: 7px;
    min-height: 28px;
    margin: 0;
    color: #6f6f95;
    font-size: 14px;
    cursor: pointer;
    white-space: nowrap;
}
.location-picker-option:hover { background: #eef7fd; }
.location-picker-option input,
.location-select-all input {
    width: 13px;
    height: 13px;
    margin: 0;
}

.select2-dropdown {
    z-index: 99999 !important;
}


.select2-container .select2-selection--single {
    height: 38px !important;
    border: 1px solid #000 !important;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 36px !important;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 36px !important;
}

.modal-content {
    border-radius: 10px;
    overflow: hidden;
}

.modal-header {
    padding: 14px 20px !important;
}

.modal-body {
    margin: 0 !important;
}


</style>
<style>
  div.dataTables_filter { display: none; }
</style>

<body class="g-sidenav-show bg-gray-100">

  <?php require_once("./include/sidebar.php"); ?>

  <main class="main-content position-relative max-height-vh-100 h-100 border-radius-lg">

    <?php require_once("./include/topnav.php"); ?>

    <div class="container-fluid page-body-wrapper">
      <div class="main-panel">
        <div class="content-wrapper">

          <!-- Filter Bar -->
          <div class="filter-container py-3">
    <div class="container-fluid">

        <!-- FILTERS IN SINGLE ROW -->
      <div class="row align-items-end g-2">

    <!-- General Search -->
   <div class="col-md-2 col-lg-1">
        <label class="form-label text-black fw-bold">
            General Search
        </label>

        <input type="text"
            id="filterSearch"
            placeholder="Type to search..."
            class="form-control">
    </div>

    <!-- Med Error -->
   <div class="col-md-1 col-lg-1">
        <label class="form-label text-black fw-bold">
            MedSafe ID
        </label>

        <input type="text"
            id="filterMedError"
            placeholder="Enter MedSafe ID..."
            class="form-control">
    </div>

    <!-- Location -->
    <div class="col-md-3 filter-location-col">
    <label class="form-label text-black fw-bold">
        Location
    </label>

    <select id="filterLocation"
            class="form-select select2"
            multiple style="width:100%;">
        <?php
        if (isset($locations)) mysqli_data_seek($locations, 0);

        while ($loc = mysqli_fetch_assoc($locations)) {
            $locName = htmlspecialchars($loc['h_loc']);
            echo "<option value='{$locName}' selected>{$locName}</option>";
        }
        ?>
    </select>
    <div class="location-picker" id="locationPicker">
        <button type="button" class="location-picker-control" id="locationPickerControl">
            Select Location(s)
        </button>
        <div class="location-picker-panel" id="locationPickerPanel">
            <label class="location-select-all">
                <input type="checkbox" id="locationSelectAll"> Select All
            </label>
            <input type="text" class="location-picker-search" id="locationSearch" autocomplete="off">
            <div class="location-picker-list" id="locationPickerList"></div>
        </div>
    </div>
</div>

<!-- Apply -->
<div class="filter-action-col">
    <button type="button"
            class="btn btn-info filter-icon-btn"
            title="Apply filters"
            aria-label="Apply filters"
            onclick="applyFilters(event)">
        <i class="fa-solid fa-filter" aria-hidden="true"></i>
    </button>
</div>

<!-- Reset -->
<div class="filter-action-col">
    <button type="button"
            class="btn btn-secondary filter-icon-btn"
            title="Reset filters"
            aria-label="Reset filters"
            onclick="resetFilters(event)">
        <i class="fa-solid fa-rotate-left" aria-hidden="true"></i>
    </button>
</div>

<!-- Excel -->
<div class="filter-action-col">
    <form method="post" class="m-0">
        <button type="submit"
                name="download"
                class="btn btn-success filter-icon-btn"
                title="Download Excel"
                aria-label="Download Excel">
            <i class="fa-solid fa-file-excel" aria-hidden="true"></i>
        </button>
    </form>
</div>

<!-- Monthly Dashboard -->
<div class="col-md-2">
    <a style="top:15px;" href="dashboard_data_entry.php"
       class="btn btn-danger w-100">
       Monthly Dashboard
    </a>
</div>

<!-- Draft Entries -->
<div class="col-md-2">
    <a style="top:15px;" href="medication_drafts.php"
       class="btn btn-primary w-100">
       Draft ID's
    </a>
</div>

    </div>

</div>


    </div>
</div>

          <!-- Table -->
          <div class="col-xl-12 grid-margin stretch-card mt-5">
              
            <div class="table-responsive">
              <table id="medErrorTable" class="display nowrap" style="width:100%">
                <thead>
                  <tr>
                    <th>MedSafe ID</th>
                    <th>Location</th>
                    <th>Date Of Medication Error</th>
                    <th>Reported Date</th>
                    <th>Department</th>
                    <th>Reported By</th>
                    <th>Severity Error Categorization</th>
                    <th>Error Type</th>
                    <th>Error Made By</th>
                    <th>Action Taken</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <?php while ($row = mysqli_fetch_assoc($sql)) {
                    $rowId = $row['id'];
                    $isDrugRecallYes = (strtolower($row['drug_recalls'] ?? '') === 'yes');
                    $isAdrYes        = (strtolower($row['adr_reporting'] ?? '') === 'yes');

                    // Split adr_types CSV into 12 individual fields
                    $adrRaw    = $row['adr_types'] ?? '';
                    $adrValues = array_pad(explode(',', $adrRaw), 12, '');
                  ?>
                    <tr>
                      <td><?= htmlspecialchars($row['med_error_code'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['location_name'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['error_datetime'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['occurrence_time'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['department_name'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['position'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['severity_name'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['error_type_name'] ?? '') ?></td>
                      <td><?= htmlspecialchars($row['error_made_by'] ?? '') ?></td>
                      <td>
                        <?php
                        $actionTaken = htmlspecialchars($row['action_taken'] ?? '');
                        $shortText = mb_substr($actionTaken, 0, 80);

                        if (mb_strlen($actionTaken) > 80) {
                            echo $shortText . '... ';
                            ?>

                            <button type="button"
                                class="btn btn-link p-0 text-primary"
                                data-bs-toggle="modal"
                                data-bs-target="#actionTakenModal<?= $rowId ?>">
                                Read More
                            </button>

                        <?php
                        } else {
                            echo $actionTaken;
                        }
                        ?>
                        </td>
                      <td>
                      <!-- VIEW -->
                      <a href="view_dashboard.php?id=<?= $rowId ?>" 
                        class="text-success me-2">
                          <i class="fas fa-eye"></i>
                      </a>

                      <!-- EDIT ONLY SUPER ADMIN -->
                      <?php if($isSuperAdmin){ ?>
                          <i class="fas fa-edit me-2"
                            style="cursor:pointer; color:#2582A1;"
                            data-bs-toggle="modal"
                            data-bs-target="#editModal<?= $rowId ?>">
                          </i>
                      <?php } ?>

                      <!-- DELETE ONLY SUPER ADMIN -->
                      <?php if($isSuperAdmin){ ?>
                          <i class="fas fa-times text-danger me-2"
                            style="cursor:pointer;"
                            data-bs-toggle="modal"
                            data-bs-target="#deleteModal<?= $rowId ?>">
                          </i>
                      <?php } ?>

                      <!-- ATTACHMENT ONLY SUPER ADMIN + ADMIN -->
                      <?php if(($isSuperAdmin || $isAdmin) && !empty($row['attachment'])){ ?>
                          <a href="../<?= $row['attachment'] ?>"
                            target="_blank"
                            title="View Attachment">
                              <i class="fas fa-paperclip"></i>
                          </a>
                      <?php } ?>

                  </td>
                    </tr>
                      <!-- Action Taken Modal -->
                      <div class="modal fade"
                          id="actionTakenModal<?= $rowId ?>"
                          tabindex="-1"
                          aria-hidden="true">

                          <div class="modal-dialog modal-lg">

                              <div class="modal-content">

                                  <div class="modal-header bg-primary text-white">

                                      <h5 class="modal-title" style="color:white;">
                                          Full Action Taken
                                      </h5>

                                      <button type="button"
                                          class="btn-close btn-close-white"
                                          data-bs-dismiss="modal">
                                      </button>

                                  </div>

                                  <div class="modal-body p-3">
                                    <div style="                          
                                        line-height: 1.7;
                                        font-size: 15px;
                                        color: #4a4a4a;
                                        margin: 0;
                                        padding: 0;
                                    ">
                                        <?= trim(nl2br(htmlspecialchars($row['action_taken'] ?? ''))) ?>
                                    </div>

                                </div>

                              </div>

                          </div>

                      </div>
                    <!-- ===================== EDIT MODAL ===================== -->
                    <div class="modal fade" id="editModal<?= $rowId ?>" tabindex="-1"
                         aria-labelledby="editModalLabel<?= $rowId ?>" aria-hidden="true">
                      <div class="modal-dialog modal-xl">
                        <div class="modal-content">
                          <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="editModalLabel<?= $rowId ?>">
                              Edit Record #<?= $rowId ?>
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                          </div>

                          <form method="post" enctype="multipart/form-data">
                            <div class="modal-body">
                              <input type="hidden" name="id" value="<?= $rowId ?>">
                              <div class="row g-3">

                                <!-- Med Error Code -->
                                <div class="col-md-4">
                                  <label>Med Error Code</label>
                                  <input type="text" class="form-control" name="med_error_code"
                                    value="<?= htmlspecialchars($row['med_error_code'] ?? '') ?>">
                                </div>

                                <!-- Group -->
                                <div class="col-md-4">
                                  <label>Group</label>
                                  <input type="text" class="form-control" name="h_grp"
                                    value="<?= htmlspecialchars($row['h_grp'] ?? '') ?>">
                                </div>

                                <!-- Region -->
                                <div class="col-md-4">
                                  <label>Region</label>
                                  <input type="text" class="form-control" name="h_reg"
                                    value="<?= htmlspecialchars($row['h_reg'] ?? '') ?>">
                                </div>

                                <!-- Location -->
                                <div class="col-md-4">
                                  <label>Location</label>
                                  <select class="form-control" name="h_loc_s">
                                    <option value="">Select Location</option>
                                    <?php
                                    if (isset($locations)) mysqli_data_seek($locations, 0);
                                    while ($loc = mysqli_fetch_assoc($locations)) {
                                        $sel = ($row['h_loc_s'] == $loc['h_id']) ? 'selected' : '';
                                        echo "<option value='{$loc['h_id']}' $sel>{$loc['h_loc']}</option>";
                                    }
                                    ?>
                                  </select>
                                </div>

                                <!-- Position (User) -->
                                <div class="col-md-4">
                                  <label>User</label>
                                  <input type="text" class="form-control" name="position"
                                    value="<?= htmlspecialchars($row['position'] ?? '') ?>">
                                </div>

                                <!-- Position Name (User Name) -->
                                <div class="col-md-4">
                                  <label>User Name</label>
                                  <input type="text" class="form-control" name="position_name"
                                    value="<?= htmlspecialchars($row['position_name'] ?? '') ?>">
                                </div>

                                <!-- Error Datetime -->
                                <div class="col-md-4">
                                  <label>Error Datetime</label>
                                  <input type="datetime-local" class="form-control" name="error_datetime"
                                    value="<?= htmlspecialchars(date('Y-m-d\TH:i', strtotime($row['error_datetime'] ?? 'now'))) ?>">
                                </div>

                                <!-- Occurrence Time (Reported Date) -->
                                <div class="col-md-4">
                                  <label>Reported Date</label>
                                  <input type="datetime-local" class="form-control" name="occurrence_time"
                                    value="<?= htmlspecialchars(date('Y-m-d\TH:i', strtotime($row['occurrence_time'] ?? 'now'))) ?>">
                                </div>

                                <!-- Patient Details -->
                                <div class="col-md-4">
                                  <label>Patient Details</label>
                                  <input type="text" class="form-control" name="patient_details"
                                    value="<?= htmlspecialchars($row['patient_details'] ?? '') ?>">
                                </div>

                                <!-- Doctor Name -->
                                <div class="col-md-4">
                                  <label>Doctor Name</label>
                                  <input type="text" class="form-control" name="doctor_name"
                                    value="<?= htmlspecialchars($row['doctor_name'] ?? '') ?>">
                                </div>

                                <!-- Resident Name -->
                                <div class="col-md-4">
                                  <label>Resident Name</label>
                                  <input type="text" class="form-control" name="resident_name"
                                    value="<?= htmlspecialchars($row['resident_name'] ?? '') ?>">
                                </div>

                                <!-- Ward -->
                                <div class="col-md-4">
                                  <label>Ward</label>
                                  <input type="text" class="form-control" name="ward"
                                    value="<?= htmlspecialchars($row['ward'] ?? '') ?>">
                                </div>

                                <!-- Other Ward -->
                                <div class="col-md-4">
                                  <label>Other Ward</label>
                                  <input type="text" class="form-control" name="other_ward"
                                    value="<?= htmlspecialchars($row['other_ward'] ?? '') ?>">
                                </div>

                                <!-- Department -->
                                <div class="col-md-4">
                                  <label>Department</label>
                                  <select class="form-control" name="department">
                                    <option value="">Select Department</option>
                                    <?php
                                    if (isset($departments)) mysqli_data_seek($departments, 0);
                                    while ($dept = mysqli_fetch_assoc($departments)) {
                                        $sel = ($row['department'] == $dept['id']) ? 'selected' : '';
                                        echo "<option value='{$dept['id']}' $sel>{$dept['department']}</option>";
                                    }
                                    ?>
                                  </select>
                                </div>

                                <!-- Other Department -->
                                <div class="col-md-4">
                                  <label>Other Department</label>
                                  <input type="text" class="form-control" name="other_department"
                                    value="<?= htmlspecialchars($row['other_department'] ?? '') ?>">
                                </div>

                                <!-- Severity -->
                                <div class="col-md-4">
                                  <label>Severity</label>
                                  <select class="form-control" name="severity">
                                    <option value="">Select Severity</option>
                                    <?php
                                    if (isset($severities)) mysqli_data_seek($severities, 0);
                                    while ($sev = mysqli_fetch_assoc($severities)) {
                                        $sel = ($row['severity'] == $sev['id'] || $row['severity'] == $sev['severity_name']) ? 'selected' : '';
                                        echo "<option value='{$sev['id']}' $sel>{$sev['severity_name']}</option>";
                                    }
                                    ?>
                                  </select>
                                </div>

                                <!-- High Alert -->
                                <div class="col-md-4">
                                  <label>High Alert</label>
                                  <select class="form-control" name="high_alert">
                                    <option value="">Select</option>
                                    <option value="Yes" <?= ($row['high_alert'] == 'Yes') ? 'selected' : '' ?>>Yes</option>
                                    <option value="No"  <?= ($row['high_alert'] == 'No')  ? 'selected' : '' ?>>No</option>
                                  </select>
                                </div>

                                <!-- Drug Involved -->
                                <div class="col-md-4">
                                  <label>Drug Involved</label>
                                  <input type="text" class="form-control" name="drug_involved"
                                    value="<?= htmlspecialchars($row['drug_involved'] ?? '') ?>">
                                </div>

                                <!-- Error Type -->
                                <div class="col-md-4">
                                  <label>Error Type</label>
                                  <select class="form-control" name="error_type">
                                    <option value="">Select Error Type</option>
                                    <?php
                                    if (isset($errorTypes)) mysqli_data_seek($errorTypes, 0);
                                    while ($et = mysqli_fetch_assoc($errorTypes)) {
                                        $sel = ($row['error_type'] == $et['id'] || $row['error_type'] == $et['error_type']) ? 'selected' : '';
                                        echo "<option value='{$et['id']}' $sel>{$et['error_type']}</option>";
                                    }
                                    ?>
                                  </select>
                                </div>

                                <!-- Sub Type -->
                                <div class="col-md-4">
                                  <label>Sub Type</label>
                                  <input type="text" class="form-control" name="sub_category"
                                    value="<?= htmlspecialchars($row['sub_type'] ?? '') ?>">
                                </div>

                                <!-- Pharma Category -->
                                <div class="col-md-4">
                                  <label>Pharma Category</label>
                                  <input type="text" class="form-control" name="pharma_category"
                                    value="<?= htmlspecialchars($row['pharma_category_name'] ?? '') ?>">
                                </div>

                                <!-- Admin Error -->
                                <div class="col-md-4">
                                  <label>Admin Error</label>
                                  <input type="text" class="form-control" name="admin_error"
                                    value="<?= htmlspecialchars($row['admin_error'] ?? '') ?>">
                                </div>

                                <!-- Error Description -->
                                <div class="col-md-12">
                                  <label>Error Description</label>
                                  <textarea class="form-control" name="error_description" rows="3"><?= htmlspecialchars($row['error_description'] ?? '') ?></textarea>
                                </div>

                                <!-- Error Made By -->
                                <div class="col-md-4">
                                  <label>Error Made By</label>
                                  <input type="text" class="form-control" name="error_made_by"
                                    value="<?= htmlspecialchars($row['error_made_by'] ?? '') ?>">
                                </div>

                                <!-- Intervention -->
                                <div class="col-md-4">
                                  <label>Intervention</label>
                                  <input type="text" class="form-control" name="intervention"
                                    value="<?= htmlspecialchars($row['intervention'] ?? '') ?>">
                                </div>

                                <!-- Root Cause -->
                                <div class="col-md-4">
                                  <label>Root Cause</label>
                                  <input type="text" class="form-control" name="root_cause"
                                    value="<?= htmlspecialchars($row['root_cause'] ?? '') ?>">
                                </div>

                                <!-- Action Taken -->
                                <div class="col-md-4">
                                  <label>Action Taken</label>
                                  <input type="text" class="form-control" name="action_taken"
                                    value="<?= htmlspecialchars($row['action_taken'] ?? '') ?>">
                                </div>

                                <!-- ===== DRUG RECALL SUBMISSION ===== -->
                                <div class="col-md-12">
                                  <hr class="my-2">
                                  <label class="fw-bold fs-6">Drug Recall Submission</label>
                                  <div class="d-flex gap-4 mt-2">
                                    <div class="form-check">
                                      <input class="form-check-input recall-toggle"
                                             type="radio"
                                             name="drug_recalls"
                                             id="drYes<?= $rowId ?>"
                                             value="yes"
                                             data-target="drSection<?= $rowId ?>"
                                             <?= $isDrugRecallYes ? 'checked' : '' ?>>
                                      <label class="form-check-label fw-semibold" for="drYes<?= $rowId ?>">Yes</label>
                                    </div>
                                    <div class="form-check">
                                      <input class="form-check-input recall-toggle"
                                             type="radio"
                                             name="drug_recalls"
                                             id="drNo<?= $rowId ?>"
                                             value="no"
                                             data-target="drSection<?= $rowId ?>"
                                             <?= !$isDrugRecallYes ? 'checked' : '' ?>>
                                      <label class="form-check-label fw-semibold" for="drNo<?= $rowId ?>">No</label>
                                    </div>
                                  </div>
                                </div>

                                <!-- Drug Recall Sub-fields -->
                                <div id="drSection<?= $rowId ?>"
                                     class="col-md-12"
                                     style="<?= $isDrugRecallYes ? '' : 'display:none;' ?>">
                                  <div class="toggle-section">
                                    <div class="section-title"><i class="fas fa-pills me-1"></i> Drug Recall Details</div>
                                    <div class="row g-3">
                                      <div class="col-md-6">
                                        <label>Product Name</label>
                                        <input type="text" class="form-control" name="product_name"
                                          value="<?= htmlspecialchars($row['product_name'] ?? '') ?>">
                                      </div>
                                      <div class="col-md-6">
                                        <label>Batch Number</label>
                                        <input type="text" class="form-control" name="batch_number"
                                          value="<?= htmlspecialchars($row['batch_number'] ?? '') ?>">
                                      </div>
                                      <div class="col-md-6">
                                        <label>Manufacture</label>
                                        <input type="text" class="form-control" name="manufacture"
                                          value="<?= htmlspecialchars($row['manufacture'] ?? '') ?>">
                                      </div>
                                      <div class="col-md-6">
                                        <label>Reason</label>
                                        <input type="text" class="form-control" name="reason"
                                          value="<?= htmlspecialchars($row['reason'] ?? '') ?>">
                                      </div>
                                      <div class="col-md-6">
                                        <label>Availability</label>
                                        <input type="text" class="form-control" name="availability"
                                          value="<?= htmlspecialchars($row['availability'] ?? '') ?>">
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <!-- ===== ADR REACTION ===== -->
                                <div class="col-md-12">
                                  <hr class="my-2">
                                  <label class="fw-bold fs-6">ADR Reaction</label>
                                  <div class="d-flex gap-4 mt-2">
                                    <div class="form-check">
                                      <input class="form-check-input adr-toggle"
                                             type="radio"
                                             name="adr_reporting"
                                             id="adrYes<?= $rowId ?>"
                                             value="yes"
                                             data-target="adrSection<?= $rowId ?>"
                                             <?= $isAdrYes ? 'checked' : '' ?>>
                                      <label class="form-check-label fw-semibold" for="adrYes<?= $rowId ?>">Yes</label>
                                    </div>
                                    <div class="form-check">
                                      <input class="form-check-input adr-toggle"
                                             type="radio"
                                             name="adr_reporting"
                                             id="adrNo<?= $rowId ?>"
                                             value="no"
                                             data-target="adrSection<?= $rowId ?>"
                                             <?= !$isAdrYes ? 'checked' : '' ?>>
                                      <label class="form-check-label fw-semibold" for="adrNo<?= $rowId ?>">No</label>
                                    </div>
                                  </div>
                                </div>

                                <!-- ===== ADR Sub-fields (split into 12 labeled inputs) ===== -->
                                <div id="adrSection<?= $rowId ?>"
                                     class="col-md-12"
                                     style="<?= $isAdrYes ? '' : 'display:none;' ?>">
                                  <div class="toggle-section">
                                    <div class="section-title">
                                      <i class="fas fa-heartbeat me-1"></i> ADR Details
                                    </div>
                                    <div class="row g-3">

                                      <!-- 1. Suspected Drug -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Suspected Drug</label>
                                        <input type="text" class="form-control" name="adr_suspected_drug"
                                          value="<?= htmlspecialchars(trim($adrValues[0])) ?>">
                                      </div>

                                      <!-- 2. Drug Category -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Drug Category</label>
                                        <input type="text" class="form-control" name="adr_drug_category"
                                          value="<?= htmlspecialchars(trim($adrValues[1])) ?>">
                                      </div>

                                      <!-- 3. Dose Route -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Dose Route</label>
                                        <input type="text" class="form-control" name="adr_dose_route"
                                          value="<?= htmlspecialchars(trim($adrValues[2])) ?>">
                                      </div>

                                      <!-- 4. Date of Reaction -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Date of Reaction</label>
                                        <input type="text" class="form-control" name="adr_date_reaction"
                                          placeholder="e.g. 2026-04-08"
                                          value="<?= htmlspecialchars(trim($adrValues[3])) ?>">
                                      </div>

                                      <!-- 5. Description of Reaction (full width textarea) -->
                                      <div class="col-md-12">
                                        <label class="adr-field-label">Description of Reaction</label>
                                        <textarea class="form-control" name="adr_description" rows="3"><?= htmlspecialchars(trim($adrValues[4])) ?></textarea>
                                      </div>

                                      <!-- 6. Outcome / Follow-up -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Outcome / Follow-up</label>
                                        <input type="text" class="form-control" name="adr_outcome"
                                          value="<?= htmlspecialchars(trim($adrValues[5])) ?>">
                                      </div>

                                      <!-- 7. Rechallenge Details -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Rechallenge Details</label>
                                        <input type="text" class="form-control" name="adr_rechallenge"
                                          value="<?= htmlspecialchars(trim($adrValues[6])) ?>">
                                      </div>

                                      <!-- 8. Severity Level -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Severity Level</label>
                                        <input type="text" class="form-control" name="adr_severity_level"
                                          value="<?= htmlspecialchars(trim($adrValues[7])) ?>">
                                      </div>

                                      <!-- 9. Prevention -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Prevention</label>
                                        <input type="text" class="form-control" name="adr_prevention"
                                          value="<?= htmlspecialchars(trim($adrValues[8])) ?>">
                                      </div>

                                      <!-- 10. Actions -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Actions</label>
                                        <input type="text" class="form-control" name="adr_actions"
                                          value="<?= htmlspecialchars(trim($adrValues[9])) ?>">
                                      </div>

                                      <!-- 11. Reported CP -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Reported CP</label>
                                        <input type="text" class="form-control" name="adr_reported_cp"
                                          value="<?= htmlspecialchars(trim($adrValues[10])) ?>">
                                      </div>

                                      <!-- 12. Reporter Details -->
                                      <div class="col-md-4">
                                        <label class="adr-field-label">Reporter Details</label>
                                        <input type="text" class="form-control" name="adr_reporter_details"
                                          value="<?= htmlspecialchars(trim($adrValues[11])) ?>">
                                      </div>

                                    </div><!-- /row -->
                                  </div><!-- /toggle-section -->
                                </div>
                                <!-- ===== END ADR Sub-fields ===== -->

                                <!-- ===== ATTACHMENT ===== -->
                                <div class="col-md-12">
                                  <hr class="my-2">
                                </div>
                                <div class="col-md-4">
                                  <label>Attachment</label>
                                  <input type="file" class="form-control" name="attachment">
                                  <?php if (!empty($row['attachment'])): ?>
                                    <div class="mt-2">
                                      <small class="text-muted">Current file: <?= htmlspecialchars(basename($row['attachment'])) ?></small><br>
                                      <a href="../<?= htmlspecialchars($row['attachment']) ?>" target="_blank"
                                         class="btn btn-info btn-sm mt-1">
                                        <i class="fas fa-eye"></i> View File
                                      </a>
                                    </div>
                                  <?php endif; ?>
                                </div>

                              </div><!-- /row -->
                            </div><!-- /modal-body -->

                            <div class="modal-footer">
                              <button type="submit" name="edit" class="btn btn-success">
                                <i class="fas fa-save me-1"></i> Update
                              </button>
                              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                          </form>

                        </div>
                      </div>
                    </div>
                    <!-- ===================== END EDIT MODAL ===================== -->


                    <!-- ===================== DELETE MODAL ===================== -->
                    <div class="modal fade" id="deleteModal<?= $rowId ?>" tabindex="-1"
                         aria-labelledby="deleteModalLabel<?= $rowId ?>" aria-hidden="true">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <div class="modal-header bg-danger text-white">
                            <h5 class="modal-title" id="deleteModalLabel<?= $rowId ?>" style="color:white;">
                              Close Form !
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                          </div>
                          <form method="post">
                            <div class="modal-body">
                              <input type="hidden" name="id" value="<?= $rowId ?>">
                              <p>Are you sure you want to close this form?</p>
                            </div>
                            <div class="modal-footer">
                              <button type="submit" name="delete" class="btn btn-danger">Close</button>
                              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            </div>
                          </form>
                        </div>
                      </div>
                    </div>
                    <!-- ===================== END DELETE MODAL ===================== -->

                  <?php } ?>
                </tbody>
              </table>
            </div>
          </div>

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

  </main>

  <!-- Toast -->
  <div class="toast-container position-fixed end-0 p-3" style="bottom:3rem !important;">
    <div id="liveToast" class="toast bg-warning border-0" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="d-flex">
        <div class="toast-body">
          <div class="text-white"><span id="alert-body"></span></div>
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
  <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
  <script>
    let table;

    $(document).ready(function () {

function buildLocationPicker() {
    var $select = $('#filterLocation');
    var $list = $('#locationPickerList');
    $list.empty();

    $select.find('option').each(function (index) {
        var optionId = 'locationOption_' + index;
        var $row = $('<label/>', {
            class: 'location-picker-option',
            for: optionId
        });
        var $checkbox = $('<input/>', {
            type: 'checkbox',
            id: optionId,
            class: 'location-option-check',
            value: this.value,
            checked: this.selected
        });

        $row.append($checkbox).append(document.createTextNode(this.text));
        $list.append($row);
    });

    syncLocationPicker();
}

function syncLocationPicker() {
    var checkedValues = $('.location-option-check:checked').map(function () {
        return this.value;
    }).get();

    $('#filterLocation option').each(function () {
        this.selected = checkedValues.indexOf(this.value) !== -1;
    });

    updateLocationCount();
}

window.updateLocationCount = function () {
    var selected = $('.location-option-check:checked').length;
    var total = $('.location-option-check').length;
    var label = selected > 0 ? selected + ' of ' + total + ' selected' : 'Select Location(s)';

    $('#locationPickerControl').text(label);
    $('#locationSelectAll').prop({
        checked: total > 0 && selected === total,
        indeterminate: selected > 0 && selected < total
    });
};

buildLocationPicker();

$('#locationPickerControl').on('click', function () {
    $('#locationPicker').toggleClass('open');
    if ($('#locationPicker').hasClass('open')) {
        $('#locationSearch').trigger('focus');
    }
});

$('#locationSelectAll').on('change', function () {
    $('.location-option-check:visible').prop('checked', this.checked);
    syncLocationPicker();
});

$(document).on('change', '.location-option-check', function () {
    syncLocationPicker();
});

$('#locationSearch').on('keyup', function () {
    var search = $(this).val().toLowerCase();

    $('.location-picker-option').each(function () {
        $(this).toggle($(this).text().toLowerCase().indexOf(search) !== -1);
    });
});

$(document).on('click', function (event) {
    if (!$(event.target).closest('#locationPicker').length) {
        $('#locationPicker').removeClass('open');
    }
});

      // Init DataTable
     table = $('#medErrorTable').DataTable({
    scrollX: true,
    order: [[0, 'desc']]
});

      // General search box
      $('#filterSearch').on('keyup', function () {
        table.search(this.value).draw();
      });

      // ── Toggle Drug Recall sub-section ──
      $(document).on('change', '.recall-toggle', function () {
        var targetId = $(this).data('target');
        if ($(this).val() === 'yes') {
          $('#' + targetId).slideDown(200);
        } else {
          $('#' + targetId).slideUp(200);
        }
      });

      // ── Toggle ADR sub-section ──
      $(document).on('change', '.adr-toggle', function () {
        var targetId = $(this).data('target');
        if ($(this).val() === 'yes') {
          $('#' + targetId).slideDown(200);
        } else {
          $('#' + targetId).slideUp(200);
        }
      });

    });

    // ── Filter functions ──
    function applyFilters(e) {
      if (e) e.preventDefault();

      var medError = $('#filterMedError').val().toLowerCase();
      var locations = $('#filterLocation').val() || [];
locations = locations.map(x => x.toLowerCase());
      var search   = $('#filterSearch').val().toLowerCase();

      $.fn.dataTable.ext.search = [];
      $.fn.dataTable.ext.search.push(function (settings, data) {
        var rowMed      = (data[0] || '').toLowerCase();
        var rowLocation = (data[1] || '').toLowerCase();
        var rowAll      = data.join(' ').toLowerCase();

        if (medError && !rowMed.includes(medError))           return false;
        if (locations.length > 0) {

    let match = false;

    locations.forEach(function(loc){
        if(rowLocation.includes(loc)){
            match = true;
        }
    });

    if(!match){
        return false;
    }
}
        if (search   && !rowAll.includes(search))             return false;
        return true;
      });

      table.draw();
    }

    function resetFilters(e) {
      if (e) e.preventDefault();
      $('#filterMedError').val('');
      $('.location-option-check').prop('checked', true);
      $('#locationSearch').val('');
      $('.location-picker-option').show();
      syncLocationPicker();
      $('#filterSearch').val('');
      $.fn.dataTable.ext.search = [];
      table.search('').draw();
    }

    $(document).on('click', '.viewAttachment', function () {
      var fileUrl = $(this).data('url');
      $('#attachmentFrame').attr('src', fileUrl);
      $('#attachmentModal').modal('show');
    });
  </script>

</body>
</html>
