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

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

$pageLink = 'payroll/schedule-report-configuration.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_schedule_report_configuration'] ?? null;
unset($_SESSION['flash_schedule_report_configuration']);

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

function src_options(mysqli $con, string $sql): array
{
    $rows = [];
    $stmt = src_stmt($con, $sql);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function src_exists(mysqli $con, int $id): bool
{
    if ($id <= 0) {
        return false;
    }
    $stmt = src_stmt($con, 'SELECT id FROM jos_app_schedulereport_config WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function src_fetch_row(mysqli $con, int $id): ?array
{
    $stmt = src_stmt($con, 'SELECT * FROM jos_app_schedulereport_config WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    return $row;
}

function src_sanitize_ids(array $ids): array
{
    return array_values(array_unique(array_filter(array_map('intval', $ids), static fn($id) => $id > 0)));
}

function src_csv_ids($csv): array
{
    if ($csv === null || trim((string)$csv) === '') {
        return [];
    }
    return src_sanitize_ids(explode(',', (string)$csv));
}

function src_valid_component_ids(mysqli $con, array $ids): array
{
    $ids = src_sanitize_ids($ids);
    if (!$ids) {
        return [];
    }
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $types = str_repeat('i', count($ids));
    $stmt = src_stmt($con, "SELECT id FROM jos_app_salarycomponentmaster WHERE id IN ($placeholders)");
    $stmt->bind_param($types, ...$ids);
    $stmt->execute();
    $result = $stmt->get_result();
    $valid = [];
    while ($row = $result->fetch_assoc()) {
        $valid[] = (int)$row['id'];
    }
    $stmt->close();
    $lookup = array_flip($valid);
    return array_values(array_filter($ids, static fn($id) => isset($lookup[$id])));
}

function src_filter_allowed_ids(array $postedIds, array $validIds, array $legacyIds): array
{
    $validLookup = array_flip(src_sanitize_ids($validIds));
    $legacyLookup = array_flip(src_sanitize_ids($legacyIds));
    $allowed = [];
    foreach (src_sanitize_ids($postedIds) as $id) {
        if (isset($validLookup[$id]) || isset($legacyLookup[$id])) {
            $allowed[] = $id;
        }
    }
    return $allowed;
}

function src_report_options(): array
{
    return [
        1 => 'PF Report',
        2 => 'ESI Report',
        3 => 'P-TAX Report',
        4 => 'MLWF Report',
    ];
}

function src_report_label($value): string
{
    $options = src_report_options();
    return $options[(int)$value] ?? 'Unknown Report';
}

function src_names($csv, array $map): string
{
    $names = [];
    foreach (src_csv_ids($csv) as $id) {
        $names[] = $map[$id] ?? ('#' . $id);
    }
    return implode(', ', $names);
}

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

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

function src_save_row(mysqli $con, int $id, array $data): int
{
    if ($id > 0) {
        $stmt = src_stmt($con, 'UPDATE jos_app_schedulereport_config SET name=?, reportname=?, components=?, total=? WHERE id=?');
        $stmt->bind_param('sissi', $data['name'], $data['reportname'], $data['components'], $data['total'], $id);
        if (!$stmt->execute()) {
            throw new RuntimeException('Unable to update schedule report configuration.');
        }
        $stmt->close();
        return $id;
    }

    $stmt = src_stmt($con, 'INSERT INTO jos_app_schedulereport_config (name, reportname, components, total) VALUES (?,?,?,?)');
    $stmt->bind_param('siss', $data['name'], $data['reportname'], $data['components'], $data['total']);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to add schedule report configuration.');
    }
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function src_insert_history(mysqli $con, int $configId): void
{
    $row = src_fetch_row($con, $configId);
    if (!$row) {
        return;
    }
    $userId = (int)(current_user()['id'] ?? 0);
    $reportName = (int)$row['reportname'];
    $components = (string)$row['components'];
    $total = (string)$row['total'];
    $stmt = src_stmt($con, 'INSERT INTO jos_app_schedulereport_config_editlog (scheduleid, date, reportname, components, total, modify_by) VALUES (?, NOW(), ?, ?, ?, ?)');
    $stmt->bind_param('iissi', $configId, $reportName, $components, $total, $userId);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to save schedule report configuration history.');
    }
    $stmt->close();
}

function src_history_rows(mysqli $con, int $configId): array
{
    $rows = [];
    $stmt = src_stmt($con, 'SELECT * FROM jos_app_schedulereport_config_editlog WHERE scheduleid=? ORDER BY date DESC,id DESC');
    $stmt->bind_param('i', $configId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function src_ensure_component_options(array &$components, array $selectedIds, array $componentMap): void
{
    $known = [];
    foreach ($components as $row) {
        $known[(int)$row['id']] = true;
    }
    foreach ($selectedIds as $id) {
        if ($id > 0 && !isset($known[$id])) {
            $components[] = ['id' => $id, 'componentname' => $componentMap[$id] ?? ('#' . $id)];
            $known[$id] = true;
        }
    }
}

$components = src_options($con, 'SELECT id,componentname,status,orderby FROM jos_app_salarycomponentmaster ORDER BY orderby ASC,id ASC');
$componentMap = [];
foreach ($components as $row) {
    $componentMap[(int)$row['id']] = (string)$row['componentname'];
}
$reportOptions = src_report_options();

$mode = (string)($_GET['mode'] ?? '');
$isForm = $mode === 'add';
$isHistory = false;
$editId = isset($_GET['edit']) ? max(0, (int)$_GET['edit']) : 0;
$historyId = isset($_GET['history']) ? max(0, (int)$_GET['history']) : 0;
$editRow = ['id' => 0, 'name' => '', 'reportname' => '', 'components' => '', 'total' => ''];
$historyRows = [];
$historyParent = null;

if ($isForm && 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.');
    }
    $isForm = true;
    $editRow = src_fetch_row($con, $editId) ?: [];
    if (!$editRow) {
        $_SESSION['flash_schedule_report_configuration'] = 'Schedule Report Configuration was not found.';
        redirect('/payroll/schedule-report-configuration.php');
    }
    src_ensure_component_options($components, array_merge(src_csv_ids(src_text($editRow, 'components')), src_csv_ids(src_text($editRow, 'total'))), $componentMap);
}

if ($historyId > 0) {
    $isHistory = true;
    $historyParent = src_fetch_row($con, $historyId);
    if (!$historyParent) {
        $_SESSION['flash_schedule_report_configuration'] = 'Schedule Report Configuration was not found.';
        redirect('/payroll/schedule-report-configuration.php');
    }
    $historyRows = src_history_rows($con, $historyId);
}

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 schedule report configurations.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add schedule report configurations.';
        }
        if ($id > 0 && !src_exists($con, $id)) {
            $errors[] = 'Schedule Report Configuration was not found.';
        }

        $name = trim((string)($_POST['name'] ?? ''));
        $reportName = (int)($_POST['reportname'] ?? 0);
        $postedComponentIds = src_sanitize_ids((array)($_POST['components'] ?? []));
        $postedTotalIds = src_sanitize_ids((array)($_POST['total'] ?? []));
        $validComponentIds = src_valid_component_ids($con, $postedComponentIds);
        $validTotalIds = src_valid_component_ids($con, $postedTotalIds);
        $legacyComponentIds = [];
        $legacyTotalIds = [];
        if ($id > 0) {
            $existingRow = src_fetch_row($con, $id);
            $legacyComponentIds = $existingRow ? src_csv_ids(src_text($existingRow, 'components')) : [];
            $legacyTotalIds = $existingRow ? src_csv_ids(src_text($existingRow, 'total')) : [];
        }
        $componentIds = src_filter_allowed_ids($postedComponentIds, $validComponentIds, $legacyComponentIds);
        $totalIds = src_filter_allowed_ids($postedTotalIds, $validTotalIds, $legacyTotalIds);

        if ($name === '') {
            $errors[] = 'Configuration Name is required.';
        } elseif (strlen($name) > 255) {
            $errors[] = 'Configuration Name must be 255 characters or fewer.';
        }
        if (!isset($reportOptions[$reportName])) {
            $errors[] = 'Select a valid Schedule Report Name.';
        }
        if (count($componentIds) !== count($postedComponentIds)) {
            $errors[] = 'Select valid Component values.';
        }
        if (count($totalIds) !== count($postedTotalIds)) {
            $errors[] = 'Select valid Total Component values.';
        }
        if (!$componentIds && !$totalIds) {
            $errors[] = 'Select at least one Component or Total Component.';
        }

        $data = [
            'name' => $name,
            'reportname' => $reportName,
            'components' => implode(',', $componentIds),
            'total' => implode(',', $totalIds),
        ];

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedId = src_save_row($con, $id, $data);
                src_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_schedule_report_configuration'] = $id > 0 ? 'Schedule Report Configuration updated successfully.' : 'Schedule Report Configuration added successfully.';
                redirect('/payroll/schedule-report-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the schedule report configuration. No changes were committed.';
            }
        }
        $isForm = true;
        $isHistory = false;
        $editRow = $data + ['id' => $id];
        src_ensure_component_options($components, array_merge($componentIds, $totalIds), $componentMap);
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterReport = isset($_GET['reportname']) && $_GET['reportname'] !== '' ? (int)$_GET['reportname'] : 0;
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$rows = [];
$totalRows = 0;
$pages = 1;

if (!$isForm && !$isHistory) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterQ !== '') {
        $where[] = '(c.name LIKE ? OR c.components LIKE ? OR c.total LIKE ? OR EXISTS (SELECT 1 FROM jos_app_salarycomponentmaster sc WHERE sc.componentname LIKE ? AND (FIND_IN_SET(sc.id, c.components) OR FIND_IN_SET(sc.id, c.total))))';
        $types .= 'ssss';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
    }
    if ($filterReport > 0) {
        $where[] = 'c.reportname=?';
        $types .= 'i';
        $params[] = $filterReport;
    }
    $whereSql = implode(' AND ', $where);

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

    $stmt = src_stmt($con, 'SELECT c.*,(SELECT COUNT(*) FROM jos_app_schedulereport_config_editlog e WHERE e.scheduleid=c.id) AS history_count FROM jos_app_schedulereport_config c WHERE ' . $whereSql . ' ORDER BY c.id DESC LIMIT ? OFFSET ?');
    $listTypes = $types . 'ii';
    $listParams = $params;
    $listParams[] = $perPage;
    $listParams[] = $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 $editRow[$key] ?? $default;
};
$selectedComponents = src_csv_ids($value('components'));
$selectedTotals = src_csv_ids($value('total'));
$componentPickerOptions = [];
foreach ($components as $option) {
    $componentPickerOptions[] = ['id' => (int)$option['id'], 'name' => (string)$option['componentname']];
}
$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('Schedule Report Configuration', $pageLink);
?>
<div class="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
  <div>
    <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>Payroll Settings</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Schedule Report Configuration</span></div>
    <h1 class="text-2xl font-bold text-slate-900">Schedule Report Configuration</h1>
    <p class="mt-1 text-sm text-slate-500">Configure statutory report component presets for PF, ESI, P-TAX, and MLWF reports.</p>
  </div>
</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 ($isHistory): ?>
<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="font-bold text-slate-800">Schedule Report Configuration History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h(src_text($historyParent ?? [], 'name')) ?> · <?= h(src_report_label(src_int_row($historyParent ?? [], 'reportname'))) ?></p></div><a href="/payroll/schedule-report-configuration.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-[900px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-700"><tr><th class="px-5 py-4">Date</th><th class="px-5 py-4">Report Name</th><th class="px-5 py-4">Components</th><th class="px-5 py-4">Total Components</th><th class="px-5 py-4">Modified By</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if (!$historyRows): ?><tr><td colspan="5" class="px-6 py-14 text-center font-semibold text-slate-400">No history found.</td></tr><?php endif; ?>
    <?php foreach ($historyRows as $row): ?><tr class="align-top hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-700"><?= h(src_text($row, 'date')) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(src_report_label(src_int_row($row, 'reportname'))) ?></td><td class="px-5 py-4"><?= h(src_names(src_text($row, 'components'), $componentMap)) ?></td><td class="px-5 py-4"><?= h(src_names(src_text($row, 'total'), $componentMap)) ?></td><td class="px-5 py-4"><?= (int)src_int_row($row, 'modify_by') ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<form method="post" class="space-y-4">
  <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', 0) ?>">
  <section class="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
    <div class="mb-4 flex flex-wrap items-center justify-between gap-3"><div class="flex items-center gap-3"><span class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-brand-600"><i class="fa-solid fa-file-lines"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id', 0) > 0 ? 'Edit Schedule Report Configuration' : 'New Schedule Report Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/payroll/schedule-report-configuration.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-3 md:grid-cols-2">
      <label class="text-sm font-semibold text-slate-700">Configuration Name *<input name="name" maxlength="255" required value="<?= h((string)$value('name')) ?>" class="<?= $input ?>" placeholder="Example: PF Report Components"></label>
      <label class="text-sm font-semibold text-slate-700">Schedule Report Name *<select name="reportname" required class="<?= $input ?>"><option value="">Select Schedule Report</option><?php foreach ($reportOptions as $id => $label): ?><option value="<?= (int)$id ?>" <?= (int)$value('reportname') === (int)$id ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <div class="text-sm font-semibold text-slate-700">Component
        <div class="relative mt-1 js-schedule-component-picker" data-name="components[]" data-placeholder="Type or select component name" data-heading="-Select Component Name-" data-empty="No components found" data-options='<?= h(json_encode($componentPickerOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?>' data-selected='<?= h(json_encode($selectedComponents)) ?>'>
          <div class="js-picker-control min-h-[46px] w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 outline-none focus-within:border-brand-500 focus-within:ring-2 focus-within:ring-brand-100">
            <div class="js-picker-tags mb-1 flex flex-wrap gap-1.5"></div>
            <input type="text" class="js-picker-search w-full border-0 bg-transparent p-0 text-sm font-medium text-slate-800 outline-none placeholder:text-slate-400" placeholder="Type or select component name" autocomplete="off">
          </div>
          <div class="js-picker-dropdown hidden absolute left-0 right-0 top-full z-40 max-h-72 overflow-y-auto border border-slate-300 bg-white shadow-xl"></div>
          <div class="js-picker-inputs"></div>
        </div>
      </div>
      <div class="text-sm font-semibold text-slate-700">Total Component
        <div class="relative mt-1 js-schedule-component-picker" data-name="total[]" data-placeholder="Type or select total component" data-heading="-Select Total Component-" data-empty="No total components found" data-options='<?= h(json_encode($componentPickerOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?>' data-selected='<?= h(json_encode($selectedTotals)) ?>'>
          <div class="js-picker-control min-h-[46px] w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-slate-800 outline-none focus-within:border-brand-500 focus-within:ring-2 focus-within:ring-brand-100">
            <div class="js-picker-tags mb-1 flex flex-wrap gap-1.5"></div>
            <input type="text" class="js-picker-search w-full border-0 bg-transparent p-0 text-sm font-medium text-slate-800 outline-none placeholder:text-slate-400" placeholder="Type or select total component" autocomplete="off">
          </div>
          <div class="js-picker-dropdown hidden absolute left-0 right-0 top-full z-40 max-h-72 overflow-y-auto border border-slate-300 bg-white shadow-xl"></div>
          <div class="js-picker-inputs"></div>
        </div>
      </div>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/payroll/schedule-report-configuration.php" class="rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-sm font-bold text-slate-600">Cancel</a><button class="rounded-lg bg-brand-600 px-5 py-2.5 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Save Configuration</button></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="font-bold text-slate-800">Schedule Report Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">Report component presets 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 name or component"><select name="reportname" class="<?= $filterInput ?>"><option value="">All Reports</option><?php foreach ($reportOptions as $id => $label): ?><option value="<?= (int)$id ?>" <?= $filterReport === (int)$id ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></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="/payroll/schedule-report-configuration.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-[980px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-700"><tr><th class="px-5 py-4 w-20">Sr No</th><th class="px-5 py-4">Configuration</th><th class="px-5 py-4">Report Name</th><th class="px-5 py-4">Component</th><th class="px-5 py-4">Total Component</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="6" class="px-6 py-14 text-center font-semibold text-slate-400">No schedule report configurations 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(src_text($row, 'name')) ?><?php if (src_int_row($row, 'history_count') > 0): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= src_int_row($row, 'history_count') ?></div><?php endif; ?></td><td class="px-5 py-4"><?= h(src_report_label(src_int_row($row, 'reportname'))) ?></td><td class="px-5 py-4"><?= h(src_names(src_text($row, 'components'), $componentMap)) ?></td><td class="px-5 py-4"><?= h(src_names(src_text($row, 'total'), $componentMap)) ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (src_int_row($row, 'history_count') > 1): ?><a href="?history=<?= src_int_row($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="History"><i class="fa-solid fa-eye"></i></a><?php endif; ?><?php if (!empty($acl['can_edit'])): ?><a href="?edit=<?= src_int_row($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"></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 ?> configurations</span><div class="flex gap-2"><?php $base = ['q' => $filterQ, 'reportname' => $filterReport ?: '']; 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 if ($isForm): ?>
<script>
document.querySelectorAll('.js-schedule-component-picker').forEach(function (picker) {
  const options = JSON.parse(picker.dataset.options || '[]');
  const fieldName = picker.dataset.name || 'components[]';
  const placeholderText = picker.dataset.placeholder || 'Type or select component name';
  const headingText = picker.dataset.heading || '-Select Component Name-';
  const emptyText = picker.dataset.empty || 'No components found';
  let selected = JSON.parse(picker.dataset.selected || '[]').map(Number);
  const control = picker.querySelector('.js-picker-control');
  const search = picker.querySelector('.js-picker-search');
  const tags = picker.querySelector('.js-picker-tags');
  const dropdown = picker.querySelector('.js-picker-dropdown');
  const inputs = picker.querySelector('.js-picker-inputs');

  function labelFor(id) {
    const option = options.find(function (item) { return Number(item.id) === Number(id); });
    return option ? option.name : '#' + id;
  }

  function syncInputs() {
    inputs.innerHTML = '';
    selected.forEach(function (id) {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = fieldName;
      input.value = String(id);
      inputs.appendChild(input);
    });
  }

  function drawTags() {
    tags.innerHTML = '';
    if (!selected.length) {
      tags.classList.add('hidden');
      search.placeholder = placeholderText;
    } else {
      tags.classList.remove('hidden');
      search.placeholder = '';
    }
    selected.forEach(function (id) {
      const tag = document.createElement('span');
      tag.className = 'inline-flex items-center gap-1 rounded-md bg-brand-50 px-2 py-1 text-xs font-bold text-brand-700';
      tag.textContent = labelFor(id);
      const remove = document.createElement('button');
      remove.type = 'button';
      remove.className = 'ml-1 text-brand-500 hover:text-red-600';
      remove.innerHTML = '&times;';
      remove.addEventListener('click', function () {
        selected = selected.filter(function (value) { return Number(value) !== Number(id); });
        render();
        openDropdown();
        search.focus();
      });
      tag.appendChild(remove);
      tags.appendChild(tag);
    });
  }

  function drawOptions() {
    const term = search.value.trim().toLowerCase();
    dropdown.innerHTML = '';
    const placeholder = document.createElement('button');
    placeholder.type = 'button';
    placeholder.className = 'block w-full bg-brand-600 px-3 py-2 text-left text-sm font-semibold text-white';
    placeholder.textContent = headingText;
    placeholder.addEventListener('click', function () {
      search.value = '';
      drawOptions();
      search.focus();
    });
    dropdown.appendChild(placeholder);

    const available = options.filter(function (option) {
      return !selected.includes(Number(option.id)) && (!term || option.name.toLowerCase().includes(term));
    });
    if (!available.length) {
      const empty = document.createElement('div');
      empty.className = 'px-3 py-3 text-sm font-medium text-slate-400';
      empty.textContent = emptyText;
      dropdown.appendChild(empty);
      return;
    }
    available.forEach(function (option) {
      const item = document.createElement('button');
      item.type = 'button';
      item.className = 'block w-full px-3 py-2 text-left text-sm font-medium text-slate-700 hover:bg-brand-50 hover:text-brand-700';
      item.textContent = option.name;
      item.addEventListener('click', function () {
        selected.push(Number(option.id));
        search.value = '';
        render();
        openDropdown();
        search.focus();
      });
      dropdown.appendChild(item);
    });
  }

  function openDropdown() {
    drawOptions();
    dropdown.classList.remove('hidden');
  }

  function render() {
    drawTags();
    syncInputs();
    drawOptions();
  }

  control.addEventListener('click', function () {
    search.focus();
    openDropdown();
  });
  search.addEventListener('focus', openDropdown);
  search.addEventListener('input', openDropdown);
  search.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
      dropdown.classList.add('hidden');
    }
  });
  document.addEventListener('click', function (event) {
    if (!picker.contains(event.target)) {
      dropdown.classList.add('hidden');
    }
  });
  render();
});
</script>
<?php endif; ?>
<?php console_footer(); ?>
