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

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

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

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

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

function osc_int($value): int
{
    return max(0, (int)$value);
}

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

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

function osc_csv_ids($value): array
{
    if ($value === null || trim((string)$value) === '') {
        return [];
    }
    $ids = array_map('intval', explode(',', (string)$value));
    return array_values(array_unique(array_filter($ids, static fn($id) => $id > 0)));
}

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

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

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

function osc_component_rows(mysqli $con, int $componentType): array
{
    if ($componentType > 0 && $componentType !== 6) {
        $stmt = osc_stmt($con, "SELECT id,componentname,componenttype,orderby,status,attend_config,functionname FROM jos_app_salarycomponentmaster WHERE componenttype=? AND status!='0' ORDER BY orderby ASC,id ASC");
        $stmt->bind_param('i', $componentType);
    } else {
        $stmt = osc_stmt($con, "SELECT id,componentname,componenttype,orderby,status,attend_config,functionname FROM jos_app_salarycomponentmaster WHERE status!='0' ORDER BY componenttype ASC,orderby ASC,id ASC");
    }
    $stmt->execute();
    $rows = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function osc_existing_rows(mysqli $con, int $orgId, int $componentType): array
{
    if ($orgId <= 0) {
        return [];
    }
    if ($componentType > 0 && $componentType !== 6) {
        $stmt = osc_stmt($con, 'SELECT * FROM jos_app_salaryorganisation WHERE orgid=? AND componenttype=? ORDER BY orderby ASC,id ASC');
        $org = (string)$orgId;
        $stmt->bind_param('si', $org, $componentType);
    } else {
        $stmt = osc_stmt($con, 'SELECT * FROM jos_app_salaryorganisation WHERE orgid=? ORDER BY componenttype ASC,orderby ASC,id ASC');
        $org = (string)$orgId;
        $stmt->bind_param('s', $org);
    }
    $stmt->execute();
    $rows = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[(int)$row['componentname']] = $row;
    }
    $stmt->close();
    return $rows;
}

function osc_report_rows(mysqli $con, int $orgId, int $componentType): array
{
    if ($orgId <= 0) {
        return ['ctc' => [], 'date' => [], 'muster' => []];
    }
    $org = (string)$orgId;
    $maps = ['ctc' => [], 'date' => [], 'muster' => []];

    if ($componentType > 0 && $componentType !== 6) {
        $stmt = osc_stmt($con, 'SELECT componentname FROM jos_app_ctcreport WHERE orgid=? AND componenttype=?');
        $stmt->bind_param('si', $org, $componentType);
    } else {
        $stmt = osc_stmt($con, 'SELECT componentname FROM jos_app_ctcreport WHERE orgid=?');
        $stmt->bind_param('s', $org);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $maps['ctc'][(int)$row['componentname']] = true;
    }
    $stmt->close();

    if ($componentType > 0 && $componentType !== 6) {
        $stmt = osc_stmt($con, 'SELECT componentname,datereport,musterreport FROM jos_app_datewisereport WHERE orgid=? AND componenttype=?');
        $stmt->bind_param('si', $org, $componentType);
    } else {
        $stmt = osc_stmt($con, 'SELECT componentname,datereport,musterreport FROM jos_app_datewisereport WHERE orgid=?');
        $stmt->bind_param('s', $org);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $componentId = (int)$row['componentname'];
        if ((int)$row['datereport'] === 1) {
            $maps['date'][$componentId] = true;
        }
        if ((int)$row['musterreport'] === 1) {
            $maps['muster'][$componentId] = true;
        }
    }
    $stmt->close();

    return $maps;
}

function osc_history_count(mysqli $con, int $orgId): int
{
    if ($orgId <= 0) {
        return 0;
    }
    $org = (string)$orgId;
    $stmt = osc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_salaryorganisation_editlog WHERE orgid=?');
    $stmt->bind_param('s', $org);
    $stmt->execute();
    $count = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    $stmt->close();
    return $count;
}

function osc_history_rows(mysqli $con, int $orgId): array
{
    $org = (string)$orgId;
    $stmt = osc_stmt($con, 'SELECT l.*,sc.componentname AS component_label,ct.componenttype AS type_label FROM jos_app_salaryorganisation_editlog l LEFT JOIN jos_app_salarycomponentmaster sc ON sc.id=l.componentname LEFT JOIN jos_app_componenttype ct ON ct.id=l.componenttype WHERE l.orgid=? ORDER BY l.date DESC,l.id DESC LIMIT 300');
    $stmt->bind_param('s', $org);
    $stmt->execute();
    $rows = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function osc_delete_org(mysqli $con, int $orgId): void
{
    $org = (string)$orgId;
    $stmt = osc_stmt($con, 'DELETE FROM jos_app_salaryorganisation WHERE orgid=?');
    $stmt->bind_param('s', $org);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to delete organization salary configuration.');
    }
    $stmt->close();
}

function osc_replace_configuration(mysqli $con, int $orgId, int $componentType, array $components, array $componentMap, array $post): int
{
    $org = (string)$orgId;
    if ($componentType !== 6) {
        $stmt = osc_stmt($con, 'DELETE FROM jos_app_salaryorganisation WHERE orgid=? AND componenttype=?');
        $stmt->bind_param('si', $org, $componentType);
        $stmt->execute();
        $stmt->close();

        $stmt = osc_stmt($con, 'DELETE FROM jos_app_ctcreport WHERE orgid=? AND componenttype=?');
        $stmt->bind_param('si', $org, $componentType);
        $stmt->execute();
        $stmt->close();

        $stmt = osc_stmt($con, 'DELETE FROM jos_app_datewisereport WHERE orgid=? AND componenttype=?');
        $stmt->bind_param('si', $org, $componentType);
        $stmt->execute();
        $stmt->close();
    } else {
        $stmt = osc_stmt($con, 'DELETE FROM jos_app_salaryorganisation WHERE orgid=?');
        $stmt->bind_param('s', $org);
        $stmt->execute();
        $stmt->close();

        $stmt = osc_stmt($con, 'DELETE FROM jos_app_ctcreport WHERE orgid=?');
        $stmt->bind_param('s', $org);
        $stmt->execute();
        $stmt->close();

        $stmt = osc_stmt($con, 'DELETE FROM jos_app_datewisereport WHERE orgid=?');
        $stmt->bind_param('s', $org);
        $stmt->execute();
        $stmt->close();
    }

    $userId = (int)(current_user()['id'] ?? 0);
    $inserted = 0;
    foreach ($components as $component) {
        $componentId = (int)$component['id'];
        if (empty($post['enabled'][$componentId])) {
            continue;
        }
        $rowComponentType = (int)$component['componenttype'];
        $order = max(0, (int)($post['orderby'][$componentId] ?? 0));
        $color = !empty($post['color'][$componentId]) ? 1 : 0;
        $canCalculate = (int)$component['attend_config'] === 0 && trim((string)$component['functionname']) === '';
        $calculationOn = $canCalculate ? osc_csv((array)($post['calculation_on'][$componentId] ?? [])) : '';
        $calculationMins = $canCalculate ? osc_csv((array)($post['calculation_mins'][$componentId] ?? [])) : '';
        $ctc = !empty($post['ctc'][$componentId]) ? 1 : 0;
        $dateReport = !empty($post['datereport'][$componentId]) ? 1 : 0;
        $musterReport = !empty($post['musterreport'][$componentId]) ? 1 : 0;
        $onlyCalculate = !empty($post['onlycalculate'][$componentId]) ? 1 : 0;

        $stmt = osc_stmt($con, 'INSERT INTO jos_app_salaryorganisation (`date`,sysdate,orgid,componenttype,componentname,orderby,calculation_on,calculation_mins,color,ctc,onlycalculate) VALUES (NOW(),NOW(),?,?,?,?,?,?,?,?,?)');
        $componentName = (string)$componentId;
        $stmt->bind_param('sisissiii', $org, $rowComponentType, $componentName, $order, $calculationOn, $calculationMins, $color, $ctc, $onlyCalculate);
        if (!$stmt->execute()) {
            throw new RuntimeException('Unable to save organization salary component.');
        }
        $savedId = (int)$con->insert_id;
        $stmt->close();

        if ($ctc === 1) {
            $stmt = osc_stmt($con, 'INSERT INTO jos_app_ctcreport (`date`,sysdate,orgid,componenttype,componentname,orderby,calculation_on,calculation_mins,color,ctc) VALUES (NOW(),NOW(),?,?,?,?,?,?,?,1)');
            $stmt->bind_param('sisissi', $org, $rowComponentType, $componentName, $order, $calculationOn, $calculationMins, $color);
            if (!$stmt->execute()) {
                throw new RuntimeException('Unable to save CTC report configuration.');
            }
            $stmt->close();
        }

        if ($dateReport === 1 || $musterReport === 1) {
            $musterOrder = $order;
            $stmt = osc_stmt($con, 'INSERT INTO jos_app_datewisereport (`date`,sysdate,orgid,componenttype,componentname,orderby,calculation_on,calculation_mins,color,datereport,musterreport,musterorderby) VALUES (NOW(),NOW(),?,?,?,?,?,?,?,?,?,?,?)');
            $stmt->bind_param('sisissiiii', $org, $rowComponentType, $componentName, $order, $calculationOn, $calculationMins, $color, $dateReport, $musterReport, $musterOrder);
            if (!$stmt->execute()) {
                throw new RuntimeException('Unable to save datewise report configuration.');
            }
            $stmt->close();
        }

        $stmt = osc_stmt($con, 'INSERT INTO jos_app_salaryorganisation_editlog (salid,`date`,orgid,componenttype,componentname,calculation_on,calculation_mins,orderby,modify_by,ctc,onlycalculate) VALUES (?,NOW(),?,?,?,?,?,?,?,?,?,?)');
        $logComponentType = $componentType;
        $stmt->bind_param('isisssiiii', $savedId, $org, $logComponentType, $componentName, $calculationOn, $calculationMins, $order, $userId, $ctc, $onlyCalculate);
        if (!$stmt->execute()) {
            throw new RuntimeException('Unable to save organization salary history.');
        }
        $stmt->close();
        $inserted++;
    }

    return $inserted;
}

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

$payrollLocations = osc_options($con, 'SELECT id,name,status FROM jos_app_payrolllocation ORDER BY name ASC,id ASC');
$payrollMap = [];
foreach ($payrollLocations as $row) {
    $payrollMap[(int)$row['id']] = (string)$row['name'];
}
$componentTypes = osc_options($con, 'SELECT id,componenttype,payscale_status FROM jos_app_componenttype ORDER BY id ASC');
$componentTypeMap = [];
foreach ($componentTypes as $row) {
    $componentTypeMap[(int)$row['id']] = (string)$row['componenttype'];
}
$allComponents = osc_options($con, "SELECT id,componentname,componenttype,orderby,status,attend_config,functionname FROM jos_app_salarycomponentmaster WHERE status!='0' ORDER BY orderby ASC,id ASC");
$componentMap = [];
foreach ($allComponents as $row) {
    $componentMap[(int)$row['id']] = (string)$row['componentname'];
}

$mode = (string)($_GET['mode'] ?? '');
$isForm = $mode === 'add' || $mode === 'edit';
$isHistory = false;
$historyOrgId = isset($_GET['history']) ? osc_int($_GET['history']) : 0;
$selectedOrgId = osc_int($_GET['orgid'] ?? $_GET['edit_orgid'] ?? '');
$selectedComponentType = osc_int($_GET['componenttype'] ?? '');

if ($mode === 'edit' && $selectedOrgId <= 0) {
    $selectedOrgId = osc_int($_GET['orgid'] ?? 0);
}

if ($isForm && $mode === 'add' && empty($acl['can_add'])) {
    http_response_code(403);
    exit('Access denied.');
}
if ($isForm && $mode === 'edit' && empty($acl['can_edit'])) {
    http_response_code(403);
    exit('Access denied.');
}
if ($historyOrgId > 0) {
    $isHistory = true;
    $isForm = false;
}

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 === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete organization salary configurations.';
        }
        $orgId = osc_int($_POST['orgid'] ?? 0);
        if (!osc_payroll_exists($con, $orgId)) {
            $errors[] = 'Select a valid Payroll Location.';
        }
        if (!$errors) {
            try {
                osc_delete_org($con, $orgId);
                $_SESSION['flash_org_salary_configuration'] = 'Organisation Salary Configuration deleted successfully.';
                redirect('/payroll/organization-salary-configuration.php');
            } catch (Throwable $e) {
                $errors[] = 'Unable to delete the organization salary configuration.';
            }
        }
    } elseif ($action === 'save') {
        $selectedOrgId = osc_int($_POST['orgid'] ?? 0);
        $selectedComponentType = osc_int($_POST['componenttype'] ?? 0);
        $hadExistingRows = $selectedOrgId > 0 ? (bool)osc_existing_rows($con, $selectedOrgId, $selectedComponentType) : false;
        if ($hadExistingRows && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit organization salary configurations.';
        }
        if (!$hadExistingRows && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add organization salary configurations.';
        }
        if (!osc_payroll_exists($con, $selectedOrgId)) {
            $errors[] = 'Payroll Location is required.';
        }
        if (!osc_component_type_exists($con, $selectedComponentType)) {
            $errors[] = 'Component Type is required.';
        }
        $componentsForSave = osc_component_rows($con, $selectedComponentType);
        if (!$componentsForSave) {
            $errors[] = 'No active salary components are available for this component type.';
        }
        $enabledCount = 0;
        foreach ($componentsForSave as $component) {
            if (!empty($_POST['enabled'][(int)$component['id']])) {
                $enabledCount++;
            }
        }
        if ($enabledCount === 0) {
            $errors[] = 'Select at least one salary component.';
        }

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedCount = osc_replace_configuration($con, $selectedOrgId, $selectedComponentType, $componentsForSave, $componentMap, $_POST);
                $con->commit();
                $_SESSION['flash_org_salary_configuration'] = 'Organisation Salary Configuration saved successfully. Components saved: ' . $savedCount . '.';
                redirect('/payroll/organization-salary-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the organization salary configuration. No changes were committed.';
            }
        }
        $isForm = true;
        $isHistory = false;
        $mode = $hadExistingRows ? 'edit' : 'add';
    }
}

$formComponents = [];
$existingRows = [];
$reportRows = ['ctc' => [], 'date' => [], 'muster' => []];
if ($isForm && $selectedComponentType > 0) {
    $formComponents = osc_component_rows($con, $selectedComponentType);
}
if ($isForm && $selectedOrgId > 0 && $selectedComponentType > 0) {
    $existingRows = osc_existing_rows($con, $selectedOrgId, $selectedComponentType);
    $reportRows = osc_report_rows($con, $selectedOrgId, $selectedComponentType);
    usort($formComponents, static function ($a, $b) use ($existingRows) {
        $aExisting = isset($existingRows[(int)$a['id']]) ? 0 : 1;
        $bExisting = isset($existingRows[(int)$b['id']]) ? 0 : 1;
        if ($aExisting !== $bExisting) {
            return $aExisting <=> $bExisting;
        }
        $aOrder = $existingRows[(int)$a['id']]['orderby'] ?? $a['orderby'];
        $bOrder = $existingRows[(int)$b['id']]['orderby'] ?? $b['orderby'];
        return ((int)$aOrder <=> (int)$bOrder) ?: ((int)$a['id'] <=> (int)$b['id']);
    });
}

$historyRows = [];
if ($isHistory) {
    if (!osc_payroll_exists($con, $historyOrgId)) {
        $_SESSION['flash_org_salary_configuration'] = 'Organisation Salary Configuration was not found.';
        redirect('/payroll/organization-salary-configuration.php');
    }
    $historyRows = osc_history_rows($con, $historyOrgId);
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterOrg = osc_int($_GET['orgid_filter'] ?? 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[] = 'pl.name LIKE ?';
        $types .= 's';
        $params[] = '%' . $filterQ . '%';
    }
    if ($filterOrg > 0) {
        $where[] = 'so.orgid=?';
        $types .= 's';
        $params[] = (string)$filterOrg;
    }
    $whereSql = implode(' AND ', $where);

    $stmt = osc_stmt($con, 'SELECT COUNT(*) AS total FROM (SELECT so.orgid FROM jos_app_salaryorganisation so LEFT JOIN jos_app_payrolllocation pl ON pl.id=CAST(so.orgid AS UNSIGNED) WHERE ' . $whereSql . ' GROUP BY so.orgid) x');
    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 = osc_stmt($con, 'SELECT so.orgid,pl.name AS payroll_location,COUNT(*) AS component_count,(SELECT COUNT(*) FROM jos_app_salaryorganisation_editlog l WHERE l.orgid=so.orgid) AS history_count FROM jos_app_salaryorganisation so LEFT JOIN jos_app_payrolllocation pl ON pl.id=CAST(so.orgid AS UNSIGNED) WHERE ' . $whereSql . ' GROUP BY so.orgid,pl.name ORDER BY pl.name ASC,so.orgid ASC 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();
}

$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';
$miniInput = 'w-full rounded-lg border border-slate-200 bg-white px-2 py-1.5 text-xs text-slate-800 outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';

console_header('Organisation Salary 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">Organisation Salary Configuration</span></div>
    <h1 class="text-2xl font-bold text-slate-900">Organisation Salary Configuration</h1>
    <p class="mt-1 text-sm text-slate-500">Configure organisation salary components exactly like the old payroll master.</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">Organisation Salary Configuration History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h($payrollMap[$historyOrgId] ?? ('Payroll Location #' . $historyOrgId)) ?></p></div><a href="/payroll/organization-salary-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-[1100px] 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">Component Type</th><th class="px-5 py-4">Component</th><th class="px-5 py-4">Order</th><th class="px-5 py-4">Calculation Add</th><th class="px-5 py-4">Calculation Minus</th><th class="px-5 py-4">Only Calculate</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="8" 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(osc_text($row, 'date')) ?></td><td class="px-5 py-4"><?= h(osc_text($row, 'type_label', $componentTypeMap[osc_int_row($row, 'componenttype')] ?? '')) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(osc_text($row, 'component_label', $componentMap[osc_int_row($row, 'componentname')] ?? ('#' . osc_text($row, 'componentname')))) ?></td><td class="px-5 py-4"><?= osc_int_row($row, 'orderby') ?></td><td class="px-5 py-4"><?= h(osc_names(osc_text($row, 'calculation_on'), $componentMap)) ?></td><td class="px-5 py-4"><?= h(osc_names(osc_text($row, 'calculation_mins'), $componentMap)) ?></td><td class="px-5 py-4"><?= osc_int_row($row, 'onlycalculate') ? 'Yes' : 'No' ?></td><td class="px-5 py-4"><?= osc_int_row($row, 'modify_by') ?></td></tr><?php endforeach; ?>
  </tbody></table></div>
</section>
<?php elseif ($isForm): ?>
<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">Organisation Salary Configuration</h2>
      <p class="mt-1 text-sm font-medium text-slate-400">Select organisation and component type, then configure salary report columns.</p>
    </div>
    <a href="/payroll/organization-salary-configuration.php" class="inline-flex items-center justify-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-bold text-slate-600 shadow-sm hover:bg-slate-50"><i class="fa-solid fa-arrow-left"></i>Back to List</a>
  </div>
  <form method="get" class="grid items-end gap-4 border-b border-slate-100 p-5 md:grid-cols-[minmax(240px,360px)_minmax(220px,300px)_120px_1fr]">
    <input type="hidden" name="mode" value="<?= h($mode === 'edit' ? 'edit' : 'add') ?>">
    <label class="text-sm font-bold text-slate-700">Organisation
      <select name="orgid" required class="<?= $input ?>">
        <option value="">Select Organisation</option>
        <?php foreach ($payrollLocations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $selectedOrgId === (int)$option['id'] ? 'selected' : '' ?>><?= h($option['name']) ?></option><?php endforeach; ?>
      </select>
    </label>
    <label class="text-sm font-bold text-slate-700">Component Type
      <select name="componenttype" required class="<?= $input ?>">
        <option value="">Select Component Type</option>
        <?php foreach ($componentTypes as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $selectedComponentType === (int)$option['id'] ? 'selected' : '' ?>><?= h($option['componenttype']) ?></option><?php endforeach; ?>
      </select>
    </label>
    <button class="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-bold text-white hover:bg-slate-800"><i class="fa-solid fa-arrow-right mr-2"></i>Go</button>
  </form>

  <?php if ($selectedOrgId > 0 && $selectedComponentType > 0): ?>
  <form method="post">
    <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="orgid" value="<?= (int)$selectedOrgId ?>"><input type="hidden" name="componenttype" value="<?= (int)$selectedComponentType ?>">
  <?php endif; ?>
    <div class="overflow-x-auto">
      <table class="w-full min-w-[1320px] text-left text-sm">
        <thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600">
          <tr>
            <th class="px-4 py-4">Sr No</th>
            <th class="px-4 py-4">Component Name</th>
            <th class="px-4 py-4">Order</th>
            <th class="px-4 py-4 text-center">Color</th>
            <th class="px-4 py-4">Calculation On Add (+)</th>
            <th class="px-4 py-4">Calculation On Mins (-)</th>
            <th class="px-4 py-4 text-center">On CTC Report</th>
            <th class="px-4 py-4 text-center">On Date Wise Report</th>
            <th class="px-4 py-4 text-center">On Muster Report</th>
            <th class="px-4 py-4 text-center">Only Calculated</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-100">
      <?php if (!$formComponents): ?><tr><td colspan="10" class="px-6 py-14 text-center font-semibold text-slate-400">Select Organisation and Component Type to load components.</td></tr><?php endif; ?>
      <?php foreach ($formComponents as $component): ?>
        <?php
          $cid = (int)$component['id'];
          $existing = $existingRows[$cid] ?? [];
          $checked = $existing || !empty($_POST['enabled'][$cid]);
          $orderValue = $_POST['orderby'][$cid] ?? ($existing['orderby'] ?? $component['orderby']);
          $colorValue = isset($_POST['color'][$cid]) || (!$_POST && osc_int_row($existing, 'color') === 1);
          $ctcValue = isset($_POST['ctc'][$cid]) || (!$_POST && (!empty($reportRows['ctc'][$cid]) || osc_int_row($existing, 'ctc') === 1));
          $dateValue = isset($_POST['datereport'][$cid]) || (!$_POST && !empty($reportRows['date'][$cid]));
          $musterValue = isset($_POST['musterreport'][$cid]) || (!$_POST && !empty($reportRows['muster'][$cid]));
          $onlyValue = isset($_POST['onlycalculate'][$cid]) || (!$_POST && osc_int_row($existing, 'onlycalculate') === 1);
          $calcOn = isset($_POST['calculation_on'][$cid]) ? osc_csv_ids(implode(',', (array)$_POST['calculation_on'][$cid])) : osc_csv_ids($existing['calculation_on'] ?? '');
          $calcMinus = isset($_POST['calculation_mins'][$cid]) ? osc_csv_ids(implode(',', (array)$_POST['calculation_mins'][$cid])) : osc_csv_ids($existing['calculation_mins'] ?? '');
          $canCalculate = (int)$component['attend_config'] === 0 && trim((string)$component['functionname']) === '';
        ?>
        <tr class="align-top hover:bg-slate-50/70">
          <td class="px-4 py-4 text-center"><input type="checkbox" name="enabled[<?= $cid ?>]" value="1" <?= $checked ? 'checked' : '' ?> class="h-4 w-4 rounded border-slate-300 text-brand-600"></td>
          <td class="px-4 py-4 font-bold text-slate-800"><?= h($component['componentname']) ?></td>
          <td class="px-4 py-4"><input type="number" min="0" name="orderby[<?= $cid ?>]" value="<?= h((string)$orderValue) ?>" class="w-20 rounded-lg border border-slate-200 px-2 py-1.5 text-sm outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100"></td>
          <td class="px-4 py-4 text-center"><input type="checkbox" name="color[<?= $cid ?>]" value="1" <?= $colorValue ? 'checked' : '' ?> class="h-4 w-4 rounded border-slate-300 text-brand-600"></td>
          <td class="px-4 py-4"><?php if ($canCalculate): ?><select name="calculation_on[<?= $cid ?>][]" multiple size="5" class="w-full min-w-[220px] rounded-lg border border-slate-200 bg-white px-2 py-1.5 text-xs outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100"><?php foreach ($allComponents as $option): ?><option value="<?= (int)$option['id'] ?>" <?= in_array((int)$option['id'], $calcOn, true) ? 'selected' : '' ?>><?= h($option['componentname']) ?></option><?php endforeach; ?></select><?php else: ?><span class="inline-flex rounded-md bg-red-50 px-2 py-1 text-xs font-bold text-red-600"><?= (int)$component['attend_config'] === 1 ? 'Component Master Attendance Report Yes' : 'Component Master Function Name Yes' ?></span><?php endif; ?></td>
          <td class="px-4 py-4"><?php if ($canCalculate): ?><select name="calculation_mins[<?= $cid ?>][]" multiple size="5" class="w-full min-w-[220px] rounded-lg border border-slate-200 bg-white px-2 py-1.5 text-xs outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100"><?php foreach ($allComponents as $option): ?><option value="<?= (int)$option['id'] ?>" <?= in_array((int)$option['id'], $calcMinus, true) ? 'selected' : '' ?>><?= h($option['componentname']) ?></option><?php endforeach; ?></select><?php else: ?><span class="inline-flex rounded-md bg-red-50 px-2 py-1 text-xs font-bold text-red-600"><?= (int)$component['attend_config'] === 1 ? 'Component Master Attendance Report Yes' : 'Component Master Function Name Yes' ?></span><?php endif; ?></td>
          <td class="px-4 py-4 text-center"><input type="checkbox" name="ctc[<?= $cid ?>]" value="1" <?= $ctcValue ? 'checked' : '' ?> class="h-4 w-4 rounded border-slate-300 text-brand-600"></td>
          <td class="px-4 py-4 text-center"><input type="checkbox" name="datereport[<?= $cid ?>]" value="1" <?= $dateValue ? 'checked' : '' ?> class="h-4 w-4 rounded border-slate-300 text-brand-600"></td>
          <td class="px-4 py-4 text-center"><input type="checkbox" name="musterreport[<?= $cid ?>]" value="1" <?= $musterValue ? 'checked' : '' ?> class="h-4 w-4 rounded border-slate-300 text-brand-600"></td>
          <td class="px-4 py-4 text-center"><input type="checkbox" name="onlycalculate[<?= $cid ?>]" value="1" <?= $onlyValue ? 'checked' : '' ?> class="h-4 w-4 rounded border-slate-300 text-brand-600"></td>
        </tr>
      <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <div class="flex justify-end gap-2 border-t border-slate-100 px-5 py-5">
      <a href="/payroll/organization-salary-configuration.php" class="rounded-lg border border-slate-200 bg-white px-5 py-2.5 text-sm font-bold text-slate-600 hover:bg-slate-50">Cancel</a>
      <?php if ($selectedOrgId > 0 && $selectedComponentType > 0): ?><button class="rounded-lg bg-brand-600 px-5 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 Configuration</button><?php endif; ?>
    </div>
  <?php if ($selectedOrgId > 0 && $selectedComponentType > 0): ?></form><?php endif; ?>
</section>
<?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">Organisation Salary Configuration List</h2><p class="mt-1 text-sm font-medium text-slate-400">Salary configurations are grouped by payroll location.</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"><select name="orgid_filter" class="<?= $filterInput ?>"><option value="">All Payroll Locations</option><?php foreach ($payrollLocations as $option): ?><option value="<?= (int)$option['id'] ?>" <?= $filterOrg === (int)$option['id'] ? 'selected' : '' ?>><?= h($option['name']) ?></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/organization-salary-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-[780px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600"><tr><th class="w-20 px-5 py-4">Sr No</th><th class="px-5 py-4">Payroll Location</th><th class="w-36 px-5 py-4">Components</th><th class="w-32 px-5 py-4">History</th><th class="w-48 px-5 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100">
    <?php if (!$rows): ?><tr><td colspan="5" class="px-6 py-14 text-center font-semibold text-slate-400">No organisation salary configurations found.</td></tr><?php endif; ?>
    <?php foreach ($rows as $index => $row): $orgId = (int)$row['orgid']; ?><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(osc_text($row, 'payroll_location', 'Payroll Location #' . $orgId)) ?></td><td class="px-5 py-4 font-semibold text-slate-600"><?= osc_int_row($row, 'component_count') ?></td><td class="px-5 py-4 font-semibold text-slate-600"><?= osc_int_row($row, 'history_count') ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (!empty($acl['can_edit'])): ?><a href="?mode=edit&orgid=<?= $orgId ?>" 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 (osc_int_row($row, 'history_count') > 1): ?><a href="?history=<?= $orgId ?>" 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_delete'])): ?><form method="post" class="inline" onsubmit="return confirm('Delete this organisation salary configuration?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="orgid" value="<?= $orgId ?>"><button type="submit" class="rounded-lg border border-slate-200 px-3 py-2 text-red-600 hover:bg-red-50" title="Delete"><i class="fa-solid fa-trash"></i></button></form><?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, 'orgid_filter' => $filterOrg ?: '']; 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(); ?>
