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

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

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

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

function ploc_table_exists(mysqli $con, string $table): bool
{
    $stmt = ploc_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 ploc_columns(mysqli $con, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) {
        return $cache[$table];
    }
    $safeTable = preg_replace('/[^A-Za-z0-9_]/', '', $table);
    $columns = [];
    $result = $con->query('SHOW COLUMNS FROM `' . $safeTable . '`');
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $columns[] = (string)$row['Field'];
        }
        $result->free();
    }
    $cache[$table] = $columns;
    return $columns;
}

function ploc_col_exists(mysqli $con, string $table, string $column): bool
{
    return in_array($column, ploc_columns($con, $table), true);
}

function ploc_pick(array $columns, array $candidates): string
{
    foreach ($candidates as $candidate) {
        if (in_array($candidate, $columns, true)) {
            return $candidate;
        }
    }
    return '';
}

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

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

function ploc_duplicate(mysqli $con, string $column, string $value, int $excludeId = 0): bool
{
    if ($column === '' || $value === '') {
        return false;
    }
    $safeColumn = preg_replace('/[^A-Za-z0-9_]/', '', $column);
    if ($excludeId > 0) {
        $stmt = ploc_stmt($con, 'SELECT id FROM jos_app_payrolllocation WHERE LOWER(TRIM(`' . $safeColumn . '`))=LOWER(TRIM(?)) AND id<>? LIMIT 1');
        $stmt->bind_param('si', $value, $excludeId);
    } else {
        $stmt = ploc_stmt($con, 'SELECT id FROM jos_app_payrolllocation WHERE LOWER(TRIM(`' . $safeColumn . '`))=LOWER(TRIM(?)) LIMIT 1');
        $stmt->bind_param('s', $value);
    }
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function ploc_upload(string $field, string $existing = ''): string
{
    if (empty($_FILES[$field]) || !isset($_FILES[$field]['error']) || (int)$_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE) {
        return $existing;
    }
    if ((int)$_FILES[$field]['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Upload failed.');
    }
    $extension = strtolower(pathinfo((string)$_FILES[$field]['name'], PATHINFO_EXTENSION));
    if (!in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true)) {
        throw new RuntimeException('Only image files are allowed.');
    }
    if ((int)$_FILES[$field]['size'] > 3 * 1024 * 1024) {
        throw new RuntimeException('Image file must be 3MB or smaller.');
    }
    $dir = __DIR__ . '/../uploads/payroll-location';
    if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
        throw new RuntimeException('Upload directory is not available.');
    }
    $file = $field . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
    if (!move_uploaded_file((string)$_FILES[$field]['tmp_name'], $dir . '/' . $file)) {
        throw new RuntimeException('Unable to save uploaded image.');
    }
    return 'uploads/payroll-location/' . $file;
}

function ploc_save(mysqli $con, int $id, array $data): int
{
    if ($id > 0) {
        $sets = [];
        $values = [];
        foreach ($data as $column => $value) {
            $sets[] = '`' . preg_replace('/[^A-Za-z0-9_]/', '', (string)$column) . '`=?';
            $values[] = $value;
        }
        $values[] = $id;
        $stmt = ploc_stmt($con, 'UPDATE jos_app_payrolllocation SET ' . implode(',', $sets) . ' WHERE id=?');
        $stmt->bind_param(str_repeat('s', count($data)) . 'i', ...$values);
        $stmt->execute();
        $stmt->close();
        return $id;
    }

    $fields = array_keys($data);
    $safeFields = array_map(static fn($field) => preg_replace('/[^A-Za-z0-9_]/', '', (string)$field), $fields);
    $stmt = ploc_stmt($con, 'INSERT INTO jos_app_payrolllocation (`' . implode('`,`', $safeFields) . '`) VALUES (' . implode(',', array_fill(0, count($fields), '?')) . ')');
    $stmt->bind_param(str_repeat('s', count($fields)), ...array_values($data));
    $stmt->execute();
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function ploc_display_status(string $value): string
{
    $clean = trim($value);
    if ($clean === '1') {
        return 'Main';
    }
    if ($clean === '2') {
        return 'Additional';
    }
    if ($clean === '0') {
        return 'Inactive';
    }
    return $clean !== '' ? $clean : 'Main';
}

function ploc_file_cell(string $path): string
{
    if ($path === '') {
        return '-';
    }
    $href = '/' . ltrim($path, '/');
    return '<a class="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:bg-brand-50 hover:text-brand-600" href="' . h($href) . '" target="_blank" rel="noopener"><i class="fa-solid fa-eye"></i></a>';
}

function ploc_option_label(array $options, string $value, string $defaultKey): string
{
    $clean = trim($value);
    if (isset($options[$clean])) {
        return (string)$options[$clean];
    }
    foreach ($options as $key => $label) {
        if (strcasecmp($clean, (string)$label) === 0) {
            return (string)$label;
        }
    }
    return (string)($options[$defaultKey] ?? reset($options));
}

function ploc_option_key(array $options, string $value, string $defaultKey): string
{
    $clean = trim($value);
    if (isset($options[$clean])) {
        return $clean;
    }
    foreach ($options as $key => $label) {
        if (strcasecmp($clean, (string)$label) === 0) {
            return (string)$key;
        }
    }
    return $defaultKey;
}

$acl = require_acl('can_view', $pageLink);

if (!ploc_table_exists($con, 'jos_app_payrolllocation')) {
    console_header('Payroll Location', $pageLink);
    echo '<div class="rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700">Payroll Location table is not available.</div>';
    console_footer();
    exit;
}

$columns = ploc_columns($con, 'jos_app_payrolllocation');
$colName = ploc_pick($columns, ['name', 'location', 'payroll_location', 'payrolllocation']);
$colStatus = ploc_pick($columns, ['payroll_location_status', 'location_status', 'plstatus', 'status', 'published']);
$colContact = ploc_pick($columns, ['phoneno', 'contact_no', 'contactno', 'contact_number', 'contact', 'phone', 'mobile']);
$colPan = ploc_pick($columns, ['pan_no', 'panno', 'pan']);
$colTan = ploc_pick($columns, ['tan_no', 'tanno', 'tan']);
$colAddress = ploc_pick($columns, ['address', 'location_address']);
$colPresentLimit = ploc_pick($columns, ['mwday_limit', 'present_hrs_limit', 'present_hr_limit', 'presenthrslimit', 'presenthrs_limit', 'present_hrs', 'per_hour_payroll']);
$colLostLmType = ploc_pick($columns, ['lmarkconfig', 'lost_lm_calculation_type', 'lost_lm_type', 'lostandlmcalculationtype', 'losthrs_latemark_calculation_type', 'calculation_type', 'lm_lost_calculation']);
$colEmployer = ploc_pick($columns, ['employer_name', 'employername', 'employer']);
$colLogo = ploc_pick($columns, ['logo', 'location_logo', 'image']);
$colStamp = ploc_pick($columns, ['stamp', 'stamp_image', 'location_stamp']);
$colOrder = ploc_pick($columns, ['orderby', 'ordering', 'sort_order']);

if ($colName === '') {
    console_header('Payroll Location', $pageLink);
    echo '<div class="rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700">Payroll Location name column is not available.</div>';
    console_footer();
    exit;
}

$statusOptions = ['Main', 'Additional', 'Inactive'];
$presentOptions = [
    '0' => 'No',
    '1' => 'Set Shift Hours as Total Hours',
    '2' => "Don't Calculate Time Before and After Shift",
    '3' => "Don't Calculate Time After Shift",
];
$lostLmOptions = [
    '0' => 'Regular (LM OR LOST)',
    '1' => 'Lost hrs and Late mark greater value will be Deducted',
];

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$isForm = $mode === 'add' || $editId > 0;
$editRow = ['id' => 0, $colName => ''];
foreach ([
    $colStatus => 'Main',
    $colContact => '',
    $colPan => '',
    $colTan => '',
    $colAddress => '',
    $colPresentLimit => '0',
    $colLostLmType => '0',
    $colEmployer => '',
    $colLogo => '',
    $colStamp => '',
    $colOrder => '0',
] as $column => $defaultValue) {
    if ($column !== '') {
        $editRow[$column] = $defaultValue;
    }
}

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 = ploc_fetch($con, $editId) ?: [];
    if (!$editRow) {
        $_SESSION['flash_payroll_location'] = 'Payroll Location was not found.';
        redirect('/organization/payroll-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 payroll locations.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add payroll locations.';
        }
        $existing = $id > 0 ? ploc_fetch($con, $id) : null;
        if ($id > 0 && !$existing) {
            $errors[] = 'Payroll Location was not found.';
        }

        $name = trim((string)($_POST['name'] ?? ''));
        $status = trim((string)($_POST['status'] ?? 'Main'));
        $contact = trim((string)($_POST['contact'] ?? ''));
        $pan = trim((string)($_POST['pan'] ?? ''));
        $tan = trim((string)($_POST['tan'] ?? ''));
        $address = trim((string)($_POST['address'] ?? ''));
        $presentLimit = trim((string)($_POST['present_limit'] ?? 'No'));
        $lostLmType = trim((string)($_POST['lost_lm_type'] ?? 'Regular (LM OR LOST)'));
        $employer = trim((string)($_POST['employer'] ?? ''));

        if (!in_array($status, $statusOptions, true)) {
            $status = 'Main';
        }
        if (!array_key_exists($presentLimit, $presentOptions)) {
            $presentLimit = ploc_option_key($presentOptions, $presentLimit, '0');
        }
        if (!array_key_exists($lostLmType, $lostLmOptions)) {
            $lostLmType = ploc_option_key($lostLmOptions, $lostLmType, '0');
        }

        if ($name === '') {
            $errors[] = 'Payroll Location is required.';
        } elseif (strlen($name) > 250) {
            $errors[] = 'Payroll Location must be 250 characters or fewer.';
        } elseif (ploc_duplicate($con, $colName, $name, $id)) {
            $errors[] = 'Payroll Location already exists.';
        }
        foreach (['Contact No' => $contact, 'PAN No' => $pan, 'TAN No' => $tan, 'Employer Name' => $employer] as $label => $valueToCheck) {
            if (strlen($valueToCheck) > 250) {
                $errors[] = $label . ' must be 250 characters or fewer.';
            }
        }
        if (strlen($address) > 1000) {
            $errors[] = 'Address must be 1000 characters or fewer.';
        }

        $data = [$colName => $name];
        if ($colStatus !== '') {
            $data[$colStatus] = $status;
        }
        if ($colContact !== '') {
            $data[$colContact] = $contact;
        }
        if ($colPan !== '') {
            $data[$colPan] = $pan;
        }
        if ($colTan !== '') {
            $data[$colTan] = $tan;
        }
        if ($colAddress !== '') {
            $data[$colAddress] = $address;
        }
        if ($colPresentLimit !== '') {
            $data[$colPresentLimit] = $presentLimit;
        }
        if ($colLostLmType !== '') {
            $data[$colLostLmType] = $lostLmType;
        }
        if ($colEmployer !== '') {
            $data[$colEmployer] = $employer;
        }

        try {
            if (!$errors && $colLogo !== '') {
                $data[$colLogo] = ploc_upload('logo', $existing ? ploc_text($existing, $colLogo) : '');
            }
            if (!$errors && $colStamp !== '') {
                $data[$colStamp] = ploc_upload('stamp', $existing ? ploc_text($existing, $colStamp) : '');
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }

        if ($colOrder !== '' && $id === 0) {
            $data[$colOrder] = '0';
        }

        $editRow = array_merge(['id' => $id], $data);
        if (!$errors) {
            try {
                ploc_save($con, $id, $data);
                $_SESSION['flash_payroll_location'] = $id > 0 ? 'Payroll Location updated successfully.' : 'Payroll Location added successfully.';
                redirect('/organization/payroll-location.php');
            } catch (Throwable $e) {
                $errors[] = 'Unable to save payroll location.';
            }
        }
        $isForm = true;
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 15;
$where = [];
$types = '';
$params = [];
if ($filterQ !== '') {
    $like = '%' . $filterQ . '%';
    $parts = [];
    foreach ([$colName, $colContact, $colPan, $colTan, $colAddress, $colEmployer] as $searchColumn) {
        if ($searchColumn !== '') {
            $parts[] = '`' . preg_replace('/[^A-Za-z0-9_]/', '', $searchColumn) . '` LIKE ?';
            $types .= 's';
            $params[] = $like;
        }
    }
    if ($parts) {
        $where[] = '(' . implode(' OR ', $parts) . ')';
    }
}
if ($colStatus !== '' && in_array($filterStatus, $statusOptions, true)) {
    $where[] = '`' . preg_replace('/[^A-Za-z0-9_]/', '', $colStatus) . '`=?';
    $types .= 's';
    $params[] = $filterStatus;
}
$whereSql = $where ? implode(' AND ', $where) : '1=1';

$countStmt = ploc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_payrolllocation 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;

$orderSql = $colOrder !== '' ? '`' . preg_replace('/[^A-Za-z0-9_]/', '', $colOrder) . '` ASC, id DESC' : 'id DESC';
$rows = [];
$stmt = ploc_stmt($con, 'SELECT * FROM jos_app_payrolllocation WHERE ' . $whereSql . ' ORDER BY ' . $orderSql . ' 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();

$value = static function (string $key, $default = '') use (&$editRow) {
    return $key !== '' && array_key_exists($key, $editRow) ? $editRow[$key] : $default;
};
$input = 'mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm font-semibold 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 font-semibold text-slate-700 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';

console_header('Payroll 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">Payroll Location</span></div>
  <h1 class="text-2xl font-bold text-slate-900">Payroll Location</h1>
  <p class="mt-1 text-sm text-slate-500">Manage payroll location details, statutory numbers, hour limits, and calculation rules.</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 ($isForm): ?>
<form method="post" enctype="multipart/form-data">
  <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-map-location-dot"></i></span><div><h2 class="text-lg font-bold text-slate-800"><?= (int)$value('id') > 0 ? 'Edit Payroll Location' : 'New Payroll Location' ?></h2><p class="mt-1 text-sm font-medium text-slate-400">Fields marked with * are required.</p></div></div>
      <a href="/organization/payroll-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-4">
      <label class="text-sm font-bold text-slate-700">Payroll Location *<input name="name" required maxlength="250" value="<?= h((string)$value($colName)) ?>" class="<?= $input ?>" placeholder="Payroll Location"></label>
      <?php if ($colStatus !== ''): ?><label class="text-sm font-bold text-slate-700">Payroll Location Status<select name="status" class="<?= $input ?>"><?php foreach ($statusOptions as $option): ?><option value="<?= h($option) ?>" <?= ploc_display_status((string)$value($colStatus, 'Main')) === $option ? 'selected' : '' ?>><?= h($option) ?></option><?php endforeach; ?></select></label><?php endif; ?>
      <?php if ($colContact !== ''): ?><label class="text-sm font-bold text-slate-700">Contact No<input name="contact" maxlength="250" value="<?= h((string)$value($colContact)) ?>" class="<?= $input ?>" placeholder="Contact No"></label><?php endif; ?>
      <?php if ($colLogo !== ''): ?><label class="text-sm font-bold text-slate-700">Logo<input name="logo" type="file" accept="image/*" class="<?= $input ?>"></label><?php endif; ?>
      <?php if ($colStamp !== ''): ?><label class="text-sm font-bold text-slate-700">Stamp<input name="stamp" type="file" accept="image/*" class="<?= $input ?>"></label><?php endif; ?>
      <?php if ($colPan !== ''): ?><label class="text-sm font-bold text-slate-700">PAN No<input name="pan" maxlength="250" value="<?= h((string)$value($colPan)) ?>" class="<?= $input ?>" placeholder="PAN No"></label><?php endif; ?>
      <?php if ($colTan !== ''): ?><label class="text-sm font-bold text-slate-700">TAN No<input name="tan" maxlength="250" value="<?= h((string)$value($colTan)) ?>" class="<?= $input ?>" placeholder="TAN No"></label><?php endif; ?>
      <?php if ($colAddress !== ''): ?><label class="text-sm font-bold text-slate-700 xl:col-span-2">Address<textarea name="address" maxlength="1000" rows="3" class="<?= $input ?>" placeholder="Address"><?= h((string)$value($colAddress)) ?></textarea></label><?php endif; ?>
      <?php if ($colPresentLimit !== ''): ?><label class="text-sm font-bold text-slate-700">Present Hrs limit (For Per Hour Payroll)<select name="present_limit" class="<?= $input ?>"><?php $currentPresent = ploc_option_key($presentOptions, (string)$value($colPresentLimit, '0'), '0'); foreach ($presentOptions as $optionValue => $optionLabel): ?><option value="<?= h((string)$optionValue) ?>" <?= $currentPresent === (string)$optionValue ? 'selected' : '' ?>><?= h($optionLabel) ?></option><?php endforeach; ?></select></label><?php endif; ?>
      <?php if ($colLostLmType !== ''): ?><label class="text-sm font-bold text-slate-700">Lost Hrs and Late Mark Calculation type<select name="lost_lm_type" class="<?= $input ?>"><?php $currentLostLm = ploc_option_key($lostLmOptions, (string)$value($colLostLmType, '0'), '0'); foreach ($lostLmOptions as $optionValue => $optionLabel): ?><option value="<?= h((string)$optionValue) ?>" <?= $currentLostLm === (string)$optionValue ? 'selected' : '' ?>><?= h($optionLabel) ?></option><?php endforeach; ?></select></label><?php endif; ?>
      <?php if ($colEmployer !== ''): ?><label class="text-sm font-bold text-slate-700">Employer Name<input name="employer" maxlength="250" value="<?= h((string)$value($colEmployer)) ?>" class="<?= $input ?>" placeholder="Employer Name"></label><?php endif; ?>
    </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>Submit</button><a href="/organization/payroll-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">Payroll Location List</h2><p class="mt-1 text-sm font-medium text-slate-400">Payroll location 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 payroll location">
    <?php if ($colStatus !== ''): ?><select name="status" class="<?= $filterInput ?>"><option value="">All Status</option><?php foreach ($statusOptions as $option): ?><option value="<?= h($option) ?>" <?= $filterStatus === $option ? 'selected' : '' ?>><?= h($option) ?></option><?php endforeach; ?></select><?php endif; ?>
    <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/payroll-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-[1400px] 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">Payroll Location</th><th class="px-5 py-4">Status</th><th class="px-5 py-4">Contact Number / PAN No / TAN No</th><th class="px-5 py-4">Address</th><th class="px-5 py-4">Present Hrs limit</th><th class="px-5 py-4">Lost and LM Calculation type</th><th class="px-5 py-4">Logo</th><th class="px-5 py-4">Stamp</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="10" class="px-6 py-14 text-center font-semibold text-slate-400">No payroll locations found.</td></tr><?php endif; ?>
    <?php foreach ($rows as $index => $row): ?>
      <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(ploc_text($row, $colName, '-')) ?></td>
        <td class="px-5 py-4 font-semibold text-slate-700"><?= h($colStatus !== '' ? ploc_display_status(ploc_text($row, $colStatus, 'Main')) : '-') ?></td>
        <td class="px-5 py-4 text-slate-700"><div>Contact :- <?= h($colContact !== '' ? ploc_text($row, $colContact, '-') : '-') ?></div><div>PAN NO :- <?= h($colPan !== '' ? ploc_text($row, $colPan, '-') : '-') ?></div><div>TAN NO :- <?= h($colTan !== '' ? ploc_text($row, $colTan, '-') : '-') ?></div></td>
        <td class="px-5 py-4 text-slate-700"><?= h($colAddress !== '' ? ploc_text($row, $colAddress, '-') : '-') ?></td>
        <td class="px-5 py-4 font-semibold text-slate-700"><?= h($colPresentLimit !== '' ? strtoupper(ploc_option_label($presentOptions, ploc_text($row, $colPresentLimit, '0'), '0')) : '-') ?></td>
        <td class="px-5 py-4 text-slate-700"><?= h($colLostLmType !== '' ? ploc_option_label($lostLmOptions, ploc_text($row, $colLostLmType, '0'), '0') : '-') ?></td>
        <td class="px-5 py-4"><?= $colLogo !== '' ? ploc_file_cell(ploc_text($row, $colLogo)) : '-' ?></td>
        <td class="px-5 py-4"><?= $colStamp !== '' ? ploc_file_cell(ploc_text($row, $colStamp)) : '-' ?></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; ?></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 ?> payroll locations</span><div class="flex gap-2"><?php $base = ['q' => $filterQ, 'status' => $filterStatus]; 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(); ?>
