<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();

$pageLink = 'organization/terminal-location.php';
$errors = [];
$flash = $_SESSION['flash_terminal_location'] ?? null;
unset($_SESSION['flash_terminal_location']);

function tl_stmt(mysqli $con, string $sql): mysqli_stmt
{
    $stmt = $con->prepare($sql);
    if (!$stmt) {
        throw new RuntimeException('Unable to prepare terminal location query.');
    }
    return $stmt;
}

function tl_col_exists(mysqli $con, string $table, string $column): bool
{
    $stmt = tl_stmt($con, 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?');
    $stmt->bind_param('ss', $table, $column);
    $stmt->execute();
    $exists = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0) > 0;
    $stmt->close();
    return $exists;
}

function tl_table_exists(mysqli $con, string $table): bool
{
    $stmt = tl_stmt($con, 'SELECT COUNT(*) AS total FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?');
    $stmt->bind_param('s', $table);
    $stmt->execute();
    $exists = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0) > 0;
    $stmt->close();
    return $exists;
}

function tl_ensure_menu(mysqli $con): void
{
    foreach ([
        'parent_id' => 'INT UNSIGNED NOT NULL DEFAULT 0',
        'show_in_menu' => 'TINYINT(1) NOT NULL DEFAULT 1',
        'url' => 'VARCHAR(255) NULL',
        'section' => 'VARCHAR(100) NULL',
        'sort_order' => 'INT NOT NULL DEFAULT 0',
    ] as $column => $definition) {
        if (!tl_col_exists($con, 'jos_admin_menus', $column)) {
            $con->query('ALTER TABLE jos_admin_menus ADD COLUMN `' . $column . '` ' . $definition);
        }
    }

    $parentId = 0;
    $stmt = tl_stmt($con, "SELECT id FROM jos_admin_menus WHERE menu_link='#organisation-settings' OR url='#organisation-settings' OR menu_name IN ('Organisation Settings','Organization Settings') ORDER BY id ASC LIMIT 1");
    $stmt->execute();
    $parent = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($parent) {
        $parentId = (int)$parent['id'];
        $stmt = tl_stmt($con, "UPDATE jos_admin_menus SET menu_name='Organisation Settings', menu_link='#organisation-settings', url='#organisation-settings', section='D. Masters', icon='fa-solid fa-building', remarks='Company and organisation masters', status=1, show_in_menu=1, can_view=1, sort_order=115, orderby=115 WHERE id=?");
        $stmt->bind_param('i', $parentId);
        $stmt->execute();
        $stmt->close();
    } else {
        $stmt = tl_stmt($con, "INSERT INTO jos_admin_menus (menu_name,menu_link,parent_id,icon,orderby,status,show_in_menu,can_view,remarks,url,section,sort_order) VALUES ('Organisation Settings','#organisation-settings',0,'fa-solid fa-building',115,1,1,1,'Company and organisation masters','#organisation-settings','D. Masters',115)");
        $stmt->execute();
        $parentId = (int)$con->insert_id;
        $stmt->close();
    }

    $stmt = tl_stmt($con, 'SELECT id FROM jos_admin_menus WHERE menu_link=? OR url=? ORDER BY id ASC LIMIT 1');
    $stmt->bind_param('ss', $GLOBALS['pageLink'], $GLOBALS['pageLink']);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($row) {
        $menuId = (int)$row['id'];
        $stmt = tl_stmt($con, "UPDATE jos_admin_menus SET menu_name='Terminal Location', parent_id=?, menu_link=?, url=?, icon='fa-solid fa-location-dot', remarks='Manage terminal locations used for attendance and user access.', section='Organisation Settings', status=1, show_in_menu=1, can_view=1, sort_order=118, orderby=118 WHERE id=?");
        $stmt->bind_param('issi', $parentId, $GLOBALS['pageLink'], $GLOBALS['pageLink'], $menuId);
        $stmt->execute();
        $stmt->close();
    } else {
        $stmt = tl_stmt($con, "INSERT INTO jos_admin_menus (menu_name,menu_link,parent_id,icon,orderby,status,show_in_menu,can_view,remarks,url,section,sort_order) VALUES ('Terminal Location',?,?,'fa-solid fa-location-dot',118,1,1,1,'Manage terminal locations used for attendance and user access.',?,'Organisation Settings',118)");
        $stmt->bind_param('sis', $GLOBALS['pageLink'], $parentId, $GLOBALS['pageLink']);
        $stmt->execute();
        $menuId = (int)$con->insert_id;
        $stmt->close();
    }

    $roleIds = [1];
    if (tl_table_exists($con, 'jos_admin_roles')) {
        $roleNameColumn = tl_col_exists($con, 'jos_admin_roles', 'role_name') ? 'role_name' : (tl_col_exists($con, 'jos_admin_roles', 'name') ? 'name' : '');
        if ($roleNameColumn !== '') {
            $stmt = tl_stmt($con, "SELECT id FROM jos_admin_roles WHERE status=1 AND (id=1 OR LOWER(`$roleNameColumn`) IN ('administrator','admin','super admin'))");
            $stmt->execute();
            $result = $stmt->get_result();
            while ($role = $result->fetch_assoc()) {
                $roleIds[] = (int)$role['id'];
            }
            $stmt->close();
        }
    }
    foreach (array_values(array_unique($roleIds)) as $roleId) {
        $stmt = tl_stmt($con, 'SELECT id FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1');
        $stmt->bind_param('ii', $roleId, $menuId);
        $stmt->execute();
        $existing = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($existing) {
            $id = (int)$existing['id'];
            $stmt = tl_stmt($con, 'UPDATE jos_admin_rolemenus SET can_view=1, can_add=1, can_edit=1, can_delete=1, status=1 WHERE id=?');
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();
        } else {
            $stmt = tl_stmt($con, 'INSERT INTO jos_admin_rolemenus (role_id, menu_id, can_view, can_add, can_edit, can_delete, status) VALUES (?, ?, 1, 1, 1, 1, 1)');
            $stmt->bind_param('ii', $roleId, $menuId);
            $stmt->execute();
            $stmt->close();
        }
    }
}

function tl_text(array $row, string $key, string $default = ''): string
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (string)$row[$key] : $default;
}

function tl_int(array $row, string $key, int $default = 0): int
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (int)$row[$key] : $default;
}

function tl_bool_label($value): string
{
    return (int)$value === 1 ? 'Yes' : 'No';
}

function tl_gatepass_label($value): string
{
    return (int)$value === 0 ? 'Yes' : 'No';
}

function tl_type_label(int $value): string
{
    $labels = [
        0 => 'Plus',
        1 => 'Minus',
    ];
    return $labels[$value] ?? 'Plus';
}

function tl_options(mysqli $con, string $sql): array
{
    $rows = [];
    $result = $con->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function tl_fetch(mysqli $con, int $id): ?array
{
    if ($id <= 0) {
        return null;
    }
    $stmt = tl_stmt($con, 'SELECT * FROM jos_app_orglocation WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    return $row;
}

function tl_duplicate_name(mysqli $con, string $name, int $excludeId = 0): bool
{
    if ($excludeId > 0) {
        $stmt = tl_stmt($con, 'SELECT id FROM jos_app_orglocation WHERE LOWER(TRIM(name))=LOWER(TRIM(?)) AND id<>? LIMIT 1');
        $stmt->bind_param('si', $name, $excludeId);
    } else {
        $stmt = tl_stmt($con, 'SELECT id FROM jos_app_orglocation WHERE LOWER(TRIM(name))=LOWER(TRIM(?)) LIMIT 1');
        $stmt->bind_param('s', $name);
    }
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function tl_duplicate_code(mysqli $con, string $code, int $excludeId = 0): bool
{
    if ($code === '') {
        return false;
    }
    if ($excludeId > 0) {
        $stmt = tl_stmt($con, 'SELECT id FROM jos_app_orglocation WHERE LOWER(TRIM(code))=LOWER(TRIM(?)) AND id<>? LIMIT 1');
        $stmt->bind_param('si', $code, $excludeId);
    } else {
        $stmt = tl_stmt($con, 'SELECT id FROM jos_app_orglocation WHERE LOWER(TRIM(code))=LOWER(TRIM(?)) LIMIT 1');
        $stmt->bind_param('s', $code);
    }
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function tl_history(mysqli $con, int $id): void
{
    $row = tl_fetch($con, $id);
    if (!$row || !tl_table_exists($con, 'jos_app_orglocation_editlog')) {
        return;
    }
    $userId = (int)(current_user()['id'] ?? 0);
    $stmt = tl_stmt($con, 'INSERT INTO jos_app_orglocation_editlog (orgid,name,gatepass,newgatepass,sysdate,modify_by,lmarkconfig,code) VALUES (?,?,?,?,NOW(),?,?,?)');
    $orgId = (int)$row['id'];
    $name = tl_text($row, 'name');
    $gatepass = tl_int($row, 'gatepass');
    $newgatepass = tl_text($row, 'newgatepass', '0');
    $lmarkconfig = tl_int($row, 'lmarkconfig');
    $code = tl_text($row, 'code');
    $stmt->bind_param('isiisis', $orgId, $name, $gatepass, $newgatepass, $userId, $lmarkconfig, $code);
    $stmt->execute();
    $stmt->close();
}

function tl_save(mysqli $con, int $id, array $data): int
{
    if (!tl_col_exists($con, 'jos_app_orglocation', 'department')) {
        $con->query('ALTER TABLE jos_app_orglocation ADD COLUMN department INT NOT NULL DEFAULT 0 AFTER name');
    }
    if ($id > 0) {
        $stmt = tl_stmt($con, 'UPDATE jos_app_orglocation SET name=?, department=?, gatepass=?, newgatepass=?, lmarkconfig=?, code=?, terminal_type=? WHERE id=?');
        $stmt->bind_param('siisisii', $data['name'], $data['department'], $data['gatepass'], $data['newgatepass'], $data['lmarkconfig'], $data['code'], $data['terminal_type'], $id);
        $stmt->execute();
        $stmt->close();
        return $id;
    }
    $stmt = tl_stmt($con, 'INSERT INTO jos_app_orglocation (name, department, gatepass, newgatepass, lmarkconfig, code, terminal_type) VALUES (?,?,?,?,?,?,?)');
    $stmt->bind_param('siisisi', $data['name'], $data['department'], $data['gatepass'], $data['newgatepass'], $data['lmarkconfig'], $data['code'], $data['terminal_type']);
    $stmt->execute();
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function tl_dependency_count(mysqli $con, int $id): int
{
    if ($id <= 0) {
        return 0;
    }
    $checks = [
        ['jos_app_employee', 'branch_location'],
        ['jos_app_employee_locationlog', 'orglocation'],
        ['jos_app_employeeface_locationlog', 'orglocation'],
        ['jos_app_empshift_locationlog', 'orglocation'],
        ['jos_app_empshiftgroup_locationlog', 'orglocation'],
        ['jos_app_jobtype_locationlog', 'orglocation'],
        ['jos_app_designation_locationlog', 'orglocation'],
        ['jos_app_location_log', 'orglocation'],
    ];
    $total = 0;
    foreach ($checks as [$table, $column]) {
        if (!tl_table_exists($con, $table) || !tl_col_exists($con, $table, $column)) {
            continue;
        }
        $safeTable = preg_replace('/[^A-Za-z0-9_]/', '', $table);
        $safeColumn = preg_replace('/[^A-Za-z0-9_]/', '', $column);
        $stmt = tl_stmt($con, 'SELECT COUNT(*) AS total FROM `' . $safeTable . '` WHERE `' . $safeColumn . '`=?');
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $total += (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0);
        $stmt->close();
    }
    return $total;
}

function tl_history_count(mysqli $con, int $id): int
{
    if (!tl_table_exists($con, 'jos_app_orglocation_editlog')) {
        return 0;
    }
    $stmt = tl_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_orglocation_editlog WHERE orgid=?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $total = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    $stmt->close();
    return $total;
}

function tl_history_rows(mysqli $con, int $id): array
{
    if (!tl_table_exists($con, 'jos_app_orglocation_editlog')) {
        return [];
    }
    $stmt = tl_stmt($con, 'SELECT * FROM jos_app_orglocation_editlog WHERE orgid=? ORDER BY id DESC');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $rows = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

try {
    tl_ensure_menu($con);
} catch (Throwable $e) {
    $errors[] = 'Terminal Location menu setup could not be completed.';
}

$acl = require_acl('can_view', $pageLink);
$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$viewId = max(0, (int)($_GET['view'] ?? 0));
$isForm = $mode === 'add' || $editId > 0;
$viewRow = null;
$editRow = [
    'id' => 0,
    'name' => '',
    'department' => 0,
    'gatepass' => 0,
    'newgatepass' => '0',
    'lmarkconfig' => 0,
    'code' => '',
    'terminal_type' => 0,
];

if ($mode === 'add' && empty($acl['can_add'])) {
    http_response_code(403);
    exit('Access denied.');
}

if ($editId > 0) {
    if (empty($acl['can_edit'])) {
        http_response_code(403);
        exit('Access denied.');
    }
    $editRow = tl_fetch($con, $editId) ?: [];
    if (!$editRow) {
        $_SESSION['flash_terminal_location'] = 'Terminal Location was not found.';
        redirect('/organization/terminal-location.php');
    }
}

if ($viewId > 0) {
    $viewRow = tl_fetch($con, $viewId);
    if (!$viewRow) {
        $_SESSION['flash_terminal_location'] = 'Terminal Location was not found.';
        redirect('/organization/terminal-location.php');
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'save') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit terminal locations.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add terminal locations.';
        }
        if ($id > 0 && !tl_fetch($con, $id)) {
            $errors[] = 'Terminal Location was not found.';
        }

        $name = trim((string)($_POST['name'] ?? ''));
        $department = max(0, (int)($_POST['department'] ?? 0));
        $code = strtoupper(trim((string)($_POST['code'] ?? '')));
        $gatepass = (int)($_POST['gatepass'] ?? 1) === 0 ? 0 : 1;
        $newgatepass = '0';
        $lmarkconfig = 0;
        $terminalType = (int)($_POST['terminal_type'] ?? 0) === 1 ? 1 : 0;

        if ($name === '') {
            $errors[] = 'Terminal Location name is required.';
        } elseif (strlen($name) > 250) {
            $errors[] = 'Terminal Location name must be 250 characters or fewer.';
        } elseif (tl_duplicate_name($con, $name, $id)) {
            $errors[] = 'Terminal Location name already exists.';
        }
        if (strlen($code) > 200) {
            $errors[] = 'Terminal Location code must be 200 characters or fewer.';
        } elseif ($code !== '' && !preg_match('/^[A-Z0-9._\-\/ ]+$/', $code)) {
            $errors[] = 'Terminal Location code can contain letters, numbers, space, dot, slash, underscore, and hyphen only.';
        } elseif (tl_duplicate_code($con, $code, $id)) {
            $errors[] = 'Terminal Location code already exists.';
        }

        $editRow = [
            'id' => $id,
            'name' => $name,
            'department' => $department,
            'gatepass' => $gatepass,
            'newgatepass' => $newgatepass,
            'lmarkconfig' => $lmarkconfig,
            'code' => $code,
            'terminal_type' => $terminalType,
        ];

        if (!$errors) {
            try {
                $con->begin_transaction();
                $savedId = tl_save($con, $id, $editRow);
                tl_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_terminal_location'] = $id > 0 ? 'Terminal Location updated successfully.' : 'Terminal Location added successfully.';
                redirect('/organization/terminal-location.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save terminal location. No changes were committed.';
            }
        }
        $isForm = true;
    } elseif ($action === 'delete') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete terminal locations.';
        } elseif (!tl_fetch($con, $id)) {
            $errors[] = 'Terminal Location was not found.';
        } else {
            $dependencyCount = tl_dependency_count($con, $id);
            if ($dependencyCount > 0) {
                $errors[] = 'This terminal location is already used in employee, shift, designation, or attendance mappings and cannot be deleted.';
            } else {
                try {
                    $con->begin_transaction();
                    if (tl_table_exists($con, 'jos_app_orglocation_editlog')) {
                        $stmt = tl_stmt($con, 'DELETE FROM jos_app_orglocation_editlog WHERE orgid=?');
                        $stmt->bind_param('i', $id);
                        $stmt->execute();
                        $stmt->close();
                    }
                    $stmt = tl_stmt($con, 'DELETE FROM jos_app_orglocation WHERE id=?');
                    $stmt->bind_param('i', $id);
                    $stmt->execute();
                    $stmt->close();
                    $con->commit();
                    $_SESSION['flash_terminal_location'] = 'Terminal Location deleted successfully.';
                    redirect('/organization/terminal-location.php');
                } catch (Throwable $e) {
                    $con->rollback();
                    $errors[] = 'Unable to delete terminal location.';
                }
            }
        }
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterGatepass = isset($_GET['gatepass']) && $_GET['gatepass'] !== '' ? (int)$_GET['gatepass'] : -1;
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 15;
$where = [];
$types = '';
$params = [];
if ($filterQ !== '') {
    $like = '%' . $filterQ . '%';
    $where[] = '(name LIKE ? OR code LIKE ?)';
    $types .= 'ss';
    $params[] = $like;
    $params[] = $like;
}
if ($filterGatepass === 0 || $filterGatepass === 1) {
    $where[] = 'gatepass=?';
    $types .= 'i';
    $params[] = $filterGatepass;
}
$whereSql = $where ? implode(' AND ', $where) : '1=1';

$countStmt = tl_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_orglocation WHERE ' . $whereSql);
if ($types !== '') {
    $countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$totalRows = (int)($countStmt->get_result()->fetch_assoc()['total'] ?? 0);
$countStmt->close();
$pages = max(1, (int)ceil($totalRows / $perPage));
$page = min($page, $pages);
$offset = ($page - 1) * $perPage;

$rows = [];
$stmt = tl_stmt($con, 'SELECT * FROM jos_app_orglocation WHERE ' . $whereSql . ' ORDER BY id DESC LIMIT ? OFFSET ?');
$listTypes = $types . 'ii';
$listParams = array_merge($params, [$perPage, $offset]);
$stmt->bind_param($listTypes, ...$listParams);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}
$stmt->close();

$departments = tl_options($con, 'SELECT id, department AS name FROM jos_app_department ORDER BY department ASC, id ASC');
$departmentMap = [];
foreach ($departments as $departmentRow) {
    $departmentMap[(int)$departmentRow['id']] = (string)$departmentRow['name'];
}

$value = static function (string $key, $default = '') use (&$editRow) {
    return $editRow[$key] ?? $default;
};
$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
$filterInput = 'rounded-xl border border-slate-200 px-3 py-2.5 text-sm';

console_header('Terminal Location', $pageLink);
?>
<div class="mb-6">
  <div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>D. Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Organisation Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Terminal Location</span></div>
  <h1 class="text-2xl font-bold text-slate-900">Terminal Location</h1>
  <p class="mt-1 text-sm text-slate-500">Manage terminal locations, departments, gatepass terminals, calculation type, and terminal code.</p>
</div>

<?php if ($flash): ?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?= h($flash) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><div class="font-bold">Please fix the following</div><ul class="mt-2 list-inside list-disc"><?php foreach ($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<?php if ($viewRow): ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div class="flex items-center gap-3"><span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="fa-solid fa-eye"></i></span><div><h2 class="text-lg font-bold text-slate-800">Terminal Location History</h2><p class="mt-1 text-sm font-medium text-slate-400"><?= h(tl_text($viewRow, 'name')) ?></p></div></div><a href="/organization/terminal-location.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
  <div class="overflow-x-auto"><table class="w-full min-w-[760px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600"><tr><th class="px-5 py-4">Sr No</th><th class="px-5 py-4">Date</th><th class="px-5 py-4">Terminal Location</th><th class="px-5 py-4">Gate Pass</th><th class="px-5 py-4">Terminal Code</th><th class="px-5 py-4">User</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php $historyRows = tl_history_rows($con, (int)$viewRow['id']); if (!$historyRows): ?><tr><td colspan="6" class="px-6 py-12 text-center font-semibold text-slate-400">No history found.</td></tr><?php endif; ?>
    <?php foreach ($historyRows as $index => $history): ?><tr class="hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-500"><?= $index + 1 ?></td><td class="px-5 py-4 font-semibold text-slate-700"><?= h(tl_text($history, 'sysdate', '-')) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(tl_text($history, 'name')) ?></td><td class="px-5 py-4"><?= h(tl_gatepass_label(tl_int($history, 'gatepass', 1))) ?></td><td class="px-5 py-4 font-semibold text-slate-600"><?= h(tl_text($history, 'code', '')) ?></td><td class="px-5 py-4 font-semibold text-slate-600"><?= h(tl_text($history, 'modify_by', '-')) ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<form method="post">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= (int)$value('id') ?>">
  <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
    <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div class="flex items-center gap-3"><span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="fa-solid fa-location-dot"></i></span><div><h2 class="text-lg font-bold text-slate-800"><?= (int)$value('id') > 0 ? 'Edit Terminal Location' : 'New Terminal Location' ?></h2><p class="mt-1 text-sm font-medium text-slate-400">Fields marked with * are required.</p></div></div><a href="/organization/terminal-location.php" class="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a></div>
    <div class="grid gap-x-6 gap-y-5 p-5 md:grid-cols-2 xl:grid-cols-5">
      <label class="text-sm font-bold text-slate-700">Terminal Location *<input name="name" required maxlength="250" value="<?= h((string)$value('name')) ?>" class="<?= $input ?>" placeholder="name"></label>
      <label class="text-sm font-bold text-slate-700">Department<select name="department" class="<?= $input ?>"><option value="0">Select Department</option><?php foreach ($departments as $department): ?><option value="<?= (int)$department['id'] ?>" <?= (int)$value('department') === (int)$department['id'] ? 'selected' : '' ?>><?= h((string)$department['name']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-bold text-slate-700">Activate Gatepass Terminal<select name="gatepass" class="<?= $input ?>"><option value="1" <?= (int)$value('gatepass', 1) !== 0 ? 'selected' : '' ?>>No</option><option value="0" <?= (int)$value('gatepass', 1) === 0 ? 'selected' : '' ?>>Yes</option></select></label>
      <label class="text-sm font-bold text-slate-700">Calculation Type<select name="terminal_type" class="<?= $input ?>"><option value="0" <?= (int)$value('terminal_type') !== 1 ? 'selected' : '' ?>>Plus</option><option value="1" <?= (int)$value('terminal_type') === 1 ? 'selected' : '' ?>>Minus</option></select></label>
      <label class="text-sm font-bold text-slate-700">Terminal Code<input name="code" maxlength="200" value="<?= h((string)$value('code')) ?>" class="<?= $input ?>" placeholder="Terminal Code"></label>
    </div>
  </section>
  <div class="mt-5 flex justify-center gap-3"><button class="rounded-lg bg-brand-600 px-8 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Save Terminal</button><a href="/organization/terminal-location.php" class="rounded-lg border border-slate-200 bg-white px-8 py-2.5 text-sm font-bold text-slate-600 hover:bg-slate-50">Cancel</a></div>
</form>
<?php else: ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="text-lg font-bold text-slate-800">Terminal Location List</h2><p class="mt-1 text-sm font-medium text-slate-400">Terminal records are ordered by latest record.</p></div><?php if (!empty($acl['can_add'])): ?><a href="?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>Add</a><?php endif; ?></div>
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-5"><input name="q" value="<?= h($filterQ) ?>" class="<?= $filterInput ?>" placeholder="Search terminal or code"><select name="gatepass" class="<?= $filterInput ?>"><option value="">All Gate Pass</option><option value="1" <?= $filterGatepass === 1 ? 'selected' : '' ?>>Gate Pass No</option><option value="0" <?= $filterGatepass === 0 ? 'selected' : '' ?>>Gate Pass Yes</option></select><div class="flex gap-2 xl:col-span-3"><button class="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button><a href="/organization/terminal-location.php" class="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-bold text-slate-600">Clear</a></div></form>
  <div class="overflow-x-auto"><table class="w-full min-w-[900px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600"><tr><th class="px-5 py-4">Sr No</th><th class="px-5 py-4">Terminal Location</th><th class="px-5 py-4">Department</th><th class="px-5 py-4">Gate Pass</th><th class="px-5 py-4">Calculation Type</th><th class="px-5 py-4">Terminal Code</th><th class="px-5 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if (!$rows): ?><tr><td colspan="7" class="px-6 py-14 text-center font-semibold text-slate-400">No terminal locations found.</td></tr><?php endif; ?>
    <?php foreach ($rows as $index => $row): $historyTotal = tl_history_count($con, (int)$row['id']); ?>
      <tr class="align-top hover:bg-slate-50/70">
        <td class="px-5 py-4 font-semibold text-slate-500"><?= (($page - 1) * $perPage) + $index + 1 ?></td>
        <td class="px-5 py-4 font-bold text-slate-800"><?= h(tl_text($row, 'name')) ?></td>
        <td class="px-5 py-4 font-semibold text-slate-600"><?= h($departmentMap[tl_int($row, 'department')] ?? '') ?></td>
        <td class="px-5 py-4"><span class="inline-flex rounded-full px-2.5 py-1 text-xs font-extrabold <?= tl_int($row, 'gatepass') === 0 ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500' ?>"><?= h(tl_gatepass_label(tl_int($row, 'gatepass', 1))) ?></span></td>
        <td class="px-5 py-4"><?= h(tl_type_label(tl_int($row, 'terminal_type'))) ?></td>
        <td class="px-5 py-4 font-semibold text-slate-600"><?= h(tl_text($row, 'code', '')) ?></td>
        <td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (!empty($acl['can_edit'])): ?><a href="?edit=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="Edit"><i class="fa-solid fa-pen-to-square"></i></a><?php endif; ?><?php if ($historyTotal > 1): ?><a href="?view=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="View"><i class="fa-solid fa-eye"></i></a><?php endif; ?></div></td>
      </tr>
    <?php endforeach; ?>
  </tbody></table></div>
  <?php if ($totalRows > $perPage): ?><div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm"><span class="font-medium text-slate-500"><?= $totalRows ?> terminal locations</span><div class="flex gap-2"><?php $base = ['q' => $filterQ, 'gatepass' => $filterGatepass >= 0 ? $filterGatepass : '']; if ($page > 1): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page' => $page - 1])) ?>">Previous</a><?php endif; ?><?php if ($page < $pages): ?><a class="rounded-lg border border-slate-200 px-4 py-2 font-semibold" href="?<?= h(http_build_query($base + ['page' => $page + 1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<?php endif; ?>
<?php console_footer(); ?>
