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

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

$pageLink = 'form16/form16-component-master.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_form16_component_master'] ?? null;
unset($_SESSION['flash_form16_component_master']);

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

function f16cm_rows(mysqli $con, string $sql, string $types = '', array $params = []): array
{
    $rows = [];
    $stmt = f16cm_stmt($con, $sql);
    if ($types !== '') {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
    return $rows;
}

function f16cm_row(mysqli $con, string $sql, string $types = '', array $params = []): ?array
{
    $rows = f16cm_rows($con, $sql, $types, $params);
    return $rows[0] ?? null;
}

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

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

function f16cm_sections(): array
{
    return [1 => 'Amount', 2 => 'Gross Amount', 3 => 'Qualifying', 4 => 'Deductible'];
}

function f16cm_calc_columns(): array
{
    return [1 => 'Amount', 2 => 'Gross', 3 => 'Qualifying', 4 => 'Deductible'];
}

function f16cm_calc_types(): array
{
    return [1 => 'Add', 2 => 'Minus'];
}

function f16cm_ass_types(): array
{
    return [0 => 'New', 1 => 'Old'];
}

function f16cm_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 f16cm_csv_positive_ids($value): array
{
    $ids = f16cm_csv_ids($value);
    return array_values(array_filter($ids, static fn($id) => $id > 0));
}

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

function f16cm_label_list(array $ids, array $map): string
{
    $labels = [];
    foreach ($ids as $id) {
        if (isset($map[$id])) {
            $labels[] = $map[$id];
        }
    }
    return $labels ? implode(', ', $labels) : '-';
}

function f16cm_money($value): string
{
    if ($value === null || $value === '') {
        return '-';
    }
    $number = (float)$value;
    return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}

function f16cm_form_number($value, string $default = ''): string
{
    if ($value === null || $value === '') {
        return $default;
    }
    $number = (float)$value;
    return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}

function f16cm_number($value, string $label, array &$errors, float $max = 999999999.0): string
{
    $raw = trim((string)$value);
    if ($raw === '') {
        $errors[] = $label . ' is required.';
        return '0';
    }
    if (!preg_match('/^\d+(\.\d{1,2})?$/', $raw)) {
        $errors[] = $label . ' must be a valid non-negative number.';
        return '0';
    }
    $number = (float)$raw;
    if ($number < 0 || $number > $max) {
        $errors[] = $label . ' is outside the allowed range.';
    }
    return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}

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

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

function f16cm_id_exists(mysqli $con, string $table, int $id): bool
{
    if ($id <= 0) {
        return false;
    }
    $allowed = [
        'jos_app_year' => true,
        'jos_app_salarycomponentmaster' => true,
        'jos_app_f16component' => true,
    ];
    if (!isset($allowed[$table])) {
        throw new InvalidArgumentException('Unsupported validation table.');
    }
    $stmt = f16cm_stmt($con, 'SELECT id FROM ' . $table . ' WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function f16cm_grid(mysqli $con, int $componentId): array
{
    $grouped = [];
    foreach (f16cm_sections() as $showIn => $label) {
        $grouped[$showIn] = [];
    }
    if ($componentId <= 0) {
        return $grouped;
    }
    $rows = f16cm_rows($con, 'SELECT * FROM jos_app_f16component_grid WHERE comp_id=? ORDER BY showin ASC,id ASC', 'i', [$componentId]);
    foreach ($rows as $row) {
        $showIn = (int)$row['showin'];
        if (isset($grouped[$showIn])) {
            $grouped[$showIn][] = $row;
        }
    }
    return $grouped;
}

function f16cm_blank_sections(): array
{
    $sections = [];
    foreach (f16cm_sections() as $showIn => $label) {
        $sections[$showIn] = [
            'enabled' => false,
            'source' => 'amount',
            'amount' => '',
            'salary_comp' => 0,
            'percent' => '',
            'calc_rows' => [['calc_colm' => 1, 'calc_type' => 1, 'calc_addmins' => 0, 'com_percent' => '100']],
        ];
    }
    return $sections;
}

function f16cm_sections_from_grid(array $grid): array
{
    $sections = f16cm_blank_sections();
    foreach ($grid as $showIn => $rows) {
        if (!$rows) {
            continue;
        }
        $sections[$showIn]['enabled'] = true;
        $hasCalc = false;
        foreach ($rows as $row) {
            if ((int)($row['calc_colm'] ?? 0) > 0) {
                $hasCalc = true;
                break;
            }
        }
        if ($hasCalc) {
            $sections[$showIn]['source'] = 'calc';
            $sections[$showIn]['calc_rows'] = [];
            foreach ($rows as $row) {
                if ((int)($row['calc_colm'] ?? 0) > 0) {
                    $sections[$showIn]['calc_rows'][] = [
                        'calc_colm' => (int)$row['calc_colm'],
                        'calc_type' => (int)$row['calc_type'],
                        'calc_addmins' => (int)$row['calc_addmins'],
                        'com_percent' => f16cm_form_number($row['com_percent'] ?? null, '100'),
                    ];
                }
            }
        } elseif ((int)($rows[0]['salary_comp'] ?? 0) > 0) {
            $sections[$showIn]['source'] = 'salary';
            $sections[$showIn]['salary_comp'] = (int)$rows[0]['salary_comp'];
            $sections[$showIn]['percent'] = f16cm_form_number($rows[0]['percent'] ?? null);
        } else {
            $sections[$showIn]['source'] = 'amount';
            $sections[$showIn]['amount'] = f16cm_form_number($rows[0]['amount'] ?? null);
        }
    }
    return $sections;
}

function f16cm_parse_sections(mysqli $con, array $post, int $componentId, array &$errors): array
{
    $enabled = is_array($post['enabled'] ?? null) ? $post['enabled'] : [];
    $source = is_array($post['source'] ?? null) ? $post['source'] : [];
    $amounts = is_array($post['amount'] ?? null) ? $post['amount'] : [];
    $salaryComponents = is_array($post['salary_comp'] ?? null) ? $post['salary_comp'] : [];
    $percents = is_array($post['percent'] ?? null) ? $post['percent'] : [];
    $calcColumns = is_array($post['calc_colm'] ?? null) ? $post['calc_colm'] : [];
    $calcTypes = is_array($post['calc_type'] ?? null) ? $post['calc_type'] : [];
    $calcComponents = is_array($post['calc_addmins'] ?? null) ? $post['calc_addmins'] : [];
    $calcPercents = is_array($post['com_percent'] ?? null) ? $post['com_percent'] : [];

    $rows = [];
    foreach (f16cm_sections() as $showIn => $label) {
        if (empty($enabled[$showIn])) {
            continue;
        }
        $mode = (string)($source[$showIn] ?? 'amount');
        if (!in_array($mode, ['amount', 'salary', 'calc'], true)) {
            $errors[] = $label . ' has an invalid configuration type.';
            continue;
        }
        if ($mode === 'amount') {
            $amount = f16cm_number($amounts[$showIn] ?? '', $label . ' fixed amount', $errors);
            $rows[] = ['showin' => $showIn, 'amount' => $amount, 'salary_comp' => 0, 'percent' => 0, 'calc_colm' => 0, 'calc_type' => 0, 'calc_addmins' => 0, 'com_percent' => 0];
            continue;
        }
        if ($mode === 'salary') {
            $salaryId = (int)($salaryComponents[$showIn] ?? 0);
            if (!f16cm_id_exists($con, 'jos_app_salarycomponentmaster', $salaryId)) {
                $errors[] = $label . ' requires a valid Salary Component.';
            }
            $percent = f16cm_number($percents[$showIn] ?? '', $label . ' salary component percent', $errors, 100.0);
            $rows[] = ['showin' => $showIn, 'amount' => 0, 'salary_comp' => $salaryId, 'percent' => $percent, 'calc_colm' => 0, 'calc_type' => 0, 'calc_addmins' => 0, 'com_percent' => 0];
            continue;
        }

        $columns = is_array($calcColumns[$showIn] ?? null) ? $calcColumns[$showIn] : [];
        $types = is_array($calcTypes[$showIn] ?? null) ? $calcTypes[$showIn] : [];
        $components = is_array($calcComponents[$showIn] ?? null) ? $calcComponents[$showIn] : [];
        $rowPercents = is_array($calcPercents[$showIn] ?? null) ? $calcPercents[$showIn] : [];
        $count = max(count($columns), count($types), count($components), count($rowPercents));
        $added = 0;
        $seen = [];
        for ($i = 0; $i < $count; $i++) {
            $columnId = (int)($columns[$i] ?? 0);
            $typeId = (int)($types[$i] ?? 0);
            $calcComponentId = (int)($components[$i] ?? 0);
            $percent = trim((string)($rowPercents[$i] ?? ''));
            if ($columnId <= 0 && $typeId <= 0 && $calcComponentId <= 0 && $percent === '') {
                continue;
            }
            $rowNo = $i + 1;
            if (!array_key_exists($columnId, f16cm_calc_columns())) {
                $errors[] = $label . ' calculation row ' . $rowNo . ' requires a valid column.';
            }
            if (!array_key_exists($typeId, f16cm_calc_types())) {
                $errors[] = $label . ' calculation row ' . $rowNo . ' requires a valid add/minus type.';
            }
            if (!f16cm_id_exists($con, 'jos_app_f16component', $calcComponentId)) {
                $errors[] = $label . ' calculation row ' . $rowNo . ' requires a valid component.';
            }
            if ($componentId > 0 && $calcComponentId === $componentId) {
                $errors[] = $label . ' calculation row ' . $rowNo . ' cannot reference the same component being edited.';
            }
            $percent = f16cm_number($percent === '' ? '100' : $percent, $label . ' calculation row ' . $rowNo . ' percent', $errors, 100.0);
            $key = $columnId . ':' . $typeId . ':' . $calcComponentId;
            if (isset($seen[$key])) {
                $errors[] = $label . ' calculation row ' . $rowNo . ' duplicates another calculation row.';
            }
            $seen[$key] = true;
            $rows[] = ['showin' => $showIn, 'amount' => 0, 'salary_comp' => 0, 'percent' => 0, 'calc_colm' => $columnId, 'calc_type' => $typeId, 'calc_addmins' => $calcComponentId, 'com_percent' => $percent];
            $added++;
        }
        if ($added === 0) {
            $errors[] = $label . ' needs at least one calculation row.';
        }
    }

    if (!$rows) {
        $errors[] = 'Enable at least one Form 16 output section.';
    }
    return $rows;
}

function f16cm_section_summary(array $rows, array $salaryMap, array $componentMap): string
{
    if (!$rows) {
        return '-';
    }
    $parts = [];
    foreach ($rows as $row) {
        if ((int)($row['calc_colm'] ?? 0) > 0) {
            $column = f16cm_calc_columns()[(int)$row['calc_colm']] ?? 'Column';
            $type = f16cm_calc_types()[(int)$row['calc_type']] ?? 'Calc';
            $component = $componentMap[(int)$row['calc_addmins']] ?? ('Component #' . (int)$row['calc_addmins']);
            $parts[] = $column . ' ' . $type . ' ' . $component . ' (' . f16cm_money($row['com_percent']) . '%)';
        } elseif ((int)($row['salary_comp'] ?? 0) > 0) {
            $component = $salaryMap[(int)$row['salary_comp']] ?? ('Salary Component #' . (int)$row['salary_comp']);
            $parts[] = $component . ' (' . f16cm_money($row['percent']) . '%)';
        } else {
            $parts[] = 'Fixed ' . f16cm_money($row['amount']);
        }
    }
    return implode('; ', $parts);
}

$years = f16cm_rows($con, 'SELECT id,year,assessment FROM jos_app_year ORDER BY id DESC');
$yearMap = [];
foreach ($years as $year) {
    $yearMap[(int)$year['id']] = trim((string)($year['assessment'] ?: $year['year']));
}

$salaryComponents = f16cm_rows($con, 'SELECT id,componentname,orderby,status FROM jos_app_salarycomponentmaster ORDER BY orderby ASC,id ASC');
$salaryMap = [];
foreach ($salaryComponents as $component) {
    $salaryMap[(int)$component['id']] = (string)$component['componentname'];
}

$componentOptions = f16cm_rows($con, 'SELECT id,componentname,parent,status,orderby FROM jos_app_f16component ORDER BY orderby ASC,id ASC');
$componentMap = [];
foreach ($componentOptions as $component) {
    $componentMap[(int)$component['id']] = (string)$component['componentname'];
}

$mode = (string)($_GET['mode'] ?? '');
$editId = isset($_GET['edit']) ? max(0, (int)$_GET['edit']) : 0;
$isForm = $mode === 'add' || $editId > 0;

$lastOrderRow = f16cm_row($con, 'SELECT COALESCE(MAX(orderby),0) AS max_order FROM jos_app_f16component');
$formRow = [
    'id' => 0,
    'componentname' => '',
    'parent' => 0,
    'status' => '1',
    'orderby' => ((int)($lastOrderRow['max_order'] ?? 0)) + 1,
    'editable' => 0,
    'qualify' => 0,
    'taxslab' => 0,
    'preform' => 0,
    'calculate' => 0,
    'assyear' => '',
    'asstype' => '',
];
$formSections = f16cm_blank_sections();

if ($isForm && $editId <= 0 && 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.');
    }
    $existing = f16cm_row($con, 'SELECT * FROM jos_app_f16component WHERE id=? LIMIT 1', 'i', [$editId]);
    if (!$existing) {
        $_SESSION['flash_form16_component_master'] = 'Form 16 Component Master record was not found.';
        redirect('/form16/form16-component-master.php');
    }
    $formRow = $existing;
    $formSections = f16cm_sections_from_grid(f16cm_grid($con, $editId));
}

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 Form 16 components.';
        }
        if ($id <= 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add Form 16 components.';
        }
        if ($id > 0 && !f16cm_exists($con, $id)) {
            $errors[] = 'Form 16 Component Master record was not found.';
        }

        $componentName = trim((string)($_POST['componentname'] ?? ''));
        $parent = max(0, (int)($_POST['parent'] ?? 0));
        $status = (string)((int)($_POST['status'] ?? 0) === 1 ? '1' : '0');
        $orderby = max(0, (int)($_POST['orderby'] ?? 0));
        $editable = (int)($_POST['editable'] ?? 0) === 1 ? 1 : 0;
        $qualify = (int)($_POST['qualify'] ?? 0) === 1 ? 1 : 0;
        $taxslab = (int)($_POST['taxslab'] ?? 0) === 1 ? 1 : 0;
        $preform = (int)($_POST['preform'] ?? 0) === 1 ? 1 : 0;
        $calculate = (int)($_POST['calculate'] ?? 0) === 1 ? 1 : 0;
        $assYears = is_array($_POST['assyear'] ?? null) ? array_values(array_unique(array_map('intval', $_POST['assyear']))) : [];
        $assTypes = is_array($_POST['asstype'] ?? null) ? array_values(array_unique(array_map('intval', $_POST['asstype']))) : [];

        if ($componentName === '') {
            $errors[] = 'Component Name is required.';
        } elseif (strlen($componentName) > 255) {
            $errors[] = 'Component Name must be 255 characters or fewer.';
        } elseif (f16cm_duplicate_name($con, $componentName, $id)) {
            $errors[] = 'A Form 16 component with this name already exists.';
        }
        if ($parent > 0) {
            if ($parent === $id) {
                $errors[] = 'Parent component cannot be the same component.';
            } elseif (!f16cm_id_exists($con, 'jos_app_f16component', $parent)) {
                $errors[] = 'Select a valid Parent Component.';
            }
        }
        foreach ($assYears as $yearId) {
            if (!f16cm_id_exists($con, 'jos_app_year', $yearId)) {
                $errors[] = 'Select valid Assessment Years only.';
                break;
            }
        }
        foreach ($assTypes as $typeId) {
            if (!array_key_exists($typeId, f16cm_ass_types())) {
                $errors[] = 'Select valid Assessment Types only.';
                break;
            }
        }

        $gridRows = f16cm_parse_sections($con, $_POST, $id, $errors);
        $assYearCsv = f16cm_csv($assYears);
        $assTypeCsv = f16cm_csv($assTypes);

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $stmt = f16cm_stmt($con, 'UPDATE jos_app_f16component SET date=CURDATE(), componentname=?, parent=?, status=?, orderby=?, editable=?, qualify=?, taxslab=?, preform=?, calculate=?, assyear=?, asstype=? WHERE id=?');
                    $stmt->bind_param('sisiiiiiissi', $componentName, $parent, $status, $orderby, $editable, $qualify, $taxslab, $preform, $calculate, $assYearCsv, $assTypeCsv, $id);
                    if (!$stmt->execute()) {
                        throw new RuntimeException('Unable to update Form 16 component.');
                    }
                    $stmt->close();
                } else {
                    $functionName = '';
                    $stmt = f16cm_stmt($con, 'INSERT INTO jos_app_f16component (date, componentname, parent, functionname, status, orderby, editable, qualify, taxslab, preform, calculate, assyear, asstype) VALUES (CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                    $stmt->bind_param('sissiiiiiiss', $componentName, $parent, $functionName, $status, $orderby, $editable, $qualify, $taxslab, $preform, $calculate, $assYearCsv, $assTypeCsv);
                    if (!$stmt->execute()) {
                        throw new RuntimeException('Unable to add Form 16 component.');
                    }
                    $id = (int)$stmt->insert_id;
                    $stmt->close();
                }

                $stmt = f16cm_stmt($con, 'DELETE FROM jos_app_f16component_grid WHERE comp_id=?');
                $stmt->bind_param('i', $id);
                if (!$stmt->execute()) {
                    throw new RuntimeException('Unable to replace Form 16 component details.');
                }
                $stmt->close();

                $stmt = f16cm_stmt($con, 'INSERT INTO jos_app_f16component_grid (comp_id, showin, amount, salary_comp, percent, calc_colm, calc_type, calc_addmins, com_percent, assyear, asstype) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                foreach ($gridRows as $row) {
                    $showIn = (int)$row['showin'];
                    $amount = (float)$row['amount'];
                    $salaryComp = (int)$row['salary_comp'];
                    $percent = (float)$row['percent'];
                    $calcColm = (int)$row['calc_colm'];
                    $calcType = (int)$row['calc_type'];
                    $calcAddMins = (int)$row['calc_addmins'];
                    $comPercent = (float)$row['com_percent'];
                    $stmt->bind_param('iididiiidss', $id, $showIn, $amount, $salaryComp, $percent, $calcColm, $calcType, $calcAddMins, $comPercent, $assYearCsv, $assTypeCsv);
                    if (!$stmt->execute()) {
                        $stmt->close();
                        throw new RuntimeException('Unable to save Form 16 component detail rows.');
                    }
                }
                $stmt->close();
                $con->commit();
                $_SESSION['flash_form16_component_master'] = ((int)($_POST['id'] ?? 0) > 0) ? 'Form 16 Component Master updated successfully.' : 'Form 16 Component Master added successfully.';
                redirect('/form16/form16-component-master.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the Form 16 Component Master record. No changes were committed.';
            }
        }

        $isForm = true;
        $editId = $id;
        $formRow = [
            'id' => $id,
            'componentname' => $componentName,
            'parent' => $parent,
            'status' => $status,
            'orderby' => $orderby,
            'editable' => $editable,
            'qualify' => $qualify,
            'taxslab' => $taxslab,
            'preform' => $preform,
            'calculate' => $calculate,
            'assyear' => $assYearCsv,
            'asstype' => $assTypeCsv,
        ];
        $formSections = f16cm_blank_sections();
        foreach (f16cm_sections() as $showIn => $label) {
            if (!empty($_POST['enabled'][$showIn])) {
                $formSections[$showIn]['enabled'] = true;
                $formSections[$showIn]['source'] = (string)($_POST['source'][$showIn] ?? 'amount');
                $formSections[$showIn]['amount'] = (string)($_POST['amount'][$showIn] ?? '');
                $formSections[$showIn]['salary_comp'] = (int)($_POST['salary_comp'][$showIn] ?? 0);
                $formSections[$showIn]['percent'] = (string)($_POST['percent'][$showIn] ?? '');
                $calcRows = [];
                $cols = is_array($_POST['calc_colm'][$showIn] ?? null) ? $_POST['calc_colm'][$showIn] : [];
                $types = is_array($_POST['calc_type'][$showIn] ?? null) ? $_POST['calc_type'][$showIn] : [];
                $components = is_array($_POST['calc_addmins'][$showIn] ?? null) ? $_POST['calc_addmins'][$showIn] : [];
                $percents = is_array($_POST['com_percent'][$showIn] ?? null) ? $_POST['com_percent'][$showIn] : [];
                $count = max(count($cols), count($types), count($components), count($percents), 1);
                for ($i = 0; $i < $count; $i++) {
                    $calcRows[] = ['calc_colm' => (int)($cols[$i] ?? 1), 'calc_type' => (int)($types[$i] ?? 1), 'calc_addmins' => (int)($components[$i] ?? 0), 'com_percent' => (string)($percents[$i] ?? '100')];
                }
                $formSections[$showIn]['calc_rows'] = $calcRows;
            }
        }
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete Form 16 components.';
        }
        $id = max(0, (int)($_POST['id'] ?? 0));
        if (!f16cm_exists($con, $id)) {
            $errors[] = 'Form 16 Component Master record was not found.';
        }
        if (!$errors) {
            $con->begin_transaction();
            try {
                $stmt = f16cm_stmt($con, 'DELETE FROM jos_app_f16component_grid WHERE comp_id=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                $stmt = f16cm_stmt($con, 'DELETE FROM jos_app_f16component WHERE id=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();
                $con->commit();
                $_SESSION['flash_form16_component_master'] = 'Form 16 Component Master deleted successfully.';
                redirect('/form16/form16-component-master.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to delete the Form 16 Component Master record.';
            }
        }
    } elseif ($action === 'toggle_status') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to activate or deactivate Form 16 components.';
        }
        $id = max(0, (int)($_POST['id'] ?? 0));
        $status = (int)($_POST['status'] ?? 0) === 1 ? '1' : '0';
        if (!f16cm_exists($con, $id)) {
            $errors[] = 'Form 16 Component Master record was not found.';
        }
        if (!$errors) {
            $stmt = f16cm_stmt($con, 'UPDATE jos_app_f16component SET status=? WHERE id=?');
            $stmt->bind_param('si', $status, $id);
            if ($stmt->execute()) {
                $_SESSION['flash_form16_component_master'] = $status === '1' ? 'Form 16 Component Master activated successfully.' : 'Form 16 Component Master deactivated successfully.';
                $stmt->close();
                redirect('/form16/form16-component-master.php');
            }
            $stmt->close();
            $errors[] = 'Unable to update Form 16 Component Master status.';
        }
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterStatus = isset($_GET['status']) && $_GET['status'] !== '' ? (string)((int)$_GET['status']) : '';
$filterYear = isset($_GET['assyear']) && $_GET['assyear'] !== '' ? (int)$_GET['assyear'] : 0;
$filterType = isset($_GET['asstype']) && $_GET['asstype'] !== '' ? (int)$_GET['asstype'] : -1;
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$rows = [];
$totalRows = 0;
$pages = 1;

if (!$isForm) {
    $where = ['1=1'];
    $types = '';
    $params = [];
    if ($filterQ !== '') {
        $where[] = '(c.componentname LIKE ? OR CAST(c.orderby AS CHAR) LIKE ?)';
        $types .= 'ss';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
    }
    if ($filterStatus !== '') {
        $where[] = 'c.status=?';
        $types .= 's';
        $params[] = $filterStatus;
    }
    if ($filterYear > 0) {
        $where[] = 'FIND_IN_SET(?, c.assyear)';
        $types .= 'i';
        $params[] = $filterYear;
    }
    if ($filterType >= 0) {
        $where[] = 'FIND_IN_SET(?, c.asstype)';
        $types .= 'i';
        $params[] = $filterType;
    }
    $whereSql = implode(' AND ', $where);

    $stmt = f16cm_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_f16component 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;

    $listParams = $params;
    $listParams[] = $perPage;
    $listParams[] = $offset;
    $stmt = f16cm_stmt($con, 'SELECT c.*,p.componentname AS parent_name FROM jos_app_f16component c LEFT JOIN jos_app_f16component p ON p.id=c.parent WHERE ' . $whereSql . ' ORDER BY c.orderby ASC,c.id DESC LIMIT ? OFFSET ?');
    $stmt->bind_param($types . 'ii', ...$listParams);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $row['grid'] = f16cm_grid($con, (int)$row['id']);
        $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';
$selectedYears = f16cm_csv_positive_ids($formRow['assyear'] ?? '');
$selectedTypes = f16cm_csv_ids($formRow['asstype'] ?? '');
$componentOptionsJson = json_encode(array_values(array_filter(array_map(static function ($row) use ($editId) {
    $id = (int)$row['id'];
    if ($editId > 0 && $id === $editId) {
        return null;
    }
    return ['id' => $id, 'name' => (string)$row['componentname']];
}, $componentOptions))), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

console_header('Form 16 Component Master', $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>Form 16 Configuration</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Form 16 Component Master</span></div>
    <h1 class="text-2xl font-bold text-slate-900">Form 16 Component Master</h1>
    <p class="mt-1 text-sm text-slate-500">Configure Form 16 components, assessment mapping, and amount/gross/qualifying/deductible calculation rules.</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 ($isForm): ?>
<form method="post" class="space-y-4" id="f16-component-form">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
  <input type="hidden" name="action" value="save">
  <input type="hidden" name="id" value="<?= f16cm_int_row($formRow, 'id') ?>">
  <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-list-check"></i></span><div><h2 class="font-bold text-slate-800"><?= f16cm_int_row($formRow, 'id') > 0 ? 'Edit Form 16 Component' : 'New Form 16 Component' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/form16/form16-component-master.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 xl:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700 xl:col-span-2">Component Name *<input name="componentname" required maxlength="255" value="<?= h(f16cm_text($formRow, 'componentname')) ?>" class="<?= $input ?>" placeholder="Example: Section 80C"></label>
      <label class="text-sm font-semibold text-slate-700">Parent Component<select name="parent" class="<?= $input ?>"><option value="0">No Parent</option><?php foreach ($componentOptions as $option): $optionId = (int)$option['id']; if (f16cm_int_row($formRow, 'id') === $optionId) { continue; } ?><option value="<?= $optionId ?>" <?= f16cm_int_row($formRow, 'parent') === $optionId ? 'selected' : '' ?>><?= h((string)$option['componentname']) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Order<input name="orderby" type="number" min="0" value="<?= f16cm_int_row($formRow, 'orderby') ?>" class="<?= $input ?>"></label>
      <label class="text-sm font-semibold text-slate-700">Status<select name="status" class="<?= $input ?>"><option value="1" <?= f16cm_text($formRow, 'status', '1') === '1' ? 'selected' : '' ?>>Active</option><option value="0" <?= f16cm_text($formRow, 'status', '1') === '0' ? 'selected' : '' ?>>Inactive</option></select></label>
      <label class="text-sm font-semibold text-slate-700">Assessment Years<select name="assyear[]" multiple size="4" class="<?= $input ?>"><?php foreach ($years as $year): $yearId = (int)$year['id']; ?><option value="<?= $yearId ?>" <?= in_array($yearId, $selectedYears, true) ? 'selected' : '' ?>><?= h($yearMap[$yearId] ?? (string)$yearId) ?></option><?php endforeach; ?></select></label>
      <label class="text-sm font-semibold text-slate-700">Assessment Types<select name="asstype[]" multiple size="4" class="<?= $input ?>"><?php foreach (f16cm_ass_types() as $typeId => $label): ?><option value="<?= $typeId ?>" <?= in_array($typeId, $selectedTypes, true) ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select></label>
      <div class="xl:col-span-2 grid gap-3 sm:grid-cols-2">
        <?php foreach (['calculate' => 'Calculate', 'qualify' => 'Qualify', 'editable' => 'Editable', 'taxslab' => 'Tax Slab', 'preform' => 'Pre Form'] as $field => $label): ?>
        <label class="flex items-center gap-3 rounded-xl border border-slate-200 px-3 py-3 text-sm font-semibold text-slate-700"><input type="checkbox" name="<?= h($field) ?>" value="1" class="h-4 w-4 rounded border-slate-300 text-brand-600" <?= f16cm_int_row($formRow, $field) === 1 ? 'checked' : '' ?>><?= h($label) ?></label>
        <?php endforeach; ?>
      </div>
    </div>
  </section>

  <section class="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
    <div class="mb-4"><h2 class="font-bold text-slate-800">Output Sections</h2><p class="mt-1 text-xs font-medium text-slate-400">Match the old Joomla show-in sections: Amount, Gross Amount, Qualifying, and Deductible.</p></div>
    <div class="grid gap-4 xl:grid-cols-2">
      <?php foreach (f16cm_sections() as $showIn => $label): $section = $formSections[$showIn]; ?>
      <div class="f16-section rounded-2xl border border-slate-100 bg-slate-50/50 p-4" data-section="<?= $showIn ?>">
        <div class="mb-3 flex items-center justify-between gap-3">
          <label class="flex items-center gap-3 text-sm font-bold text-slate-800"><input type="checkbox" name="enabled[<?= $showIn ?>]" value="1" class="section-toggle h-4 w-4 rounded border-slate-300 text-brand-600" <?= !empty($section['enabled']) ? 'checked' : '' ?>><?= h($label) ?></label>
          <select name="source[<?= $showIn ?>]" class="source-select rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-bold text-slate-700">
            <option value="amount" <?= $section['source'] === 'amount' ? 'selected' : '' ?>>Fixed Amount</option>
            <option value="salary" <?= $section['source'] === 'salary' ? 'selected' : '' ?>>Salary Component</option>
            <option value="calc" <?= $section['source'] === 'calc' ? 'selected' : '' ?>>Calculation</option>
          </select>
        </div>
        <div class="section-body space-y-3">
          <div class="source-panel source-amount"><label class="text-sm font-semibold text-slate-700">Amount<input type="number" step="0.01" min="0" name="amount[<?= $showIn ?>]" value="<?= h((string)$section['amount']) ?>" class="<?= $input ?>" placeholder="0"></label></div>
          <div class="source-panel source-salary grid gap-3 md:grid-cols-2">
            <label class="text-sm font-semibold text-slate-700">Salary Component<select name="salary_comp[<?= $showIn ?>]" class="<?= $input ?>"><option value="0">Select Component</option><?php foreach ($salaryComponents as $component): $componentId = (int)$component['id']; ?><option value="<?= $componentId ?>" <?= (int)$section['salary_comp'] === $componentId ? 'selected' : '' ?>><?= h((string)$component['componentname']) ?></option><?php endforeach; ?></select></label>
            <label class="text-sm font-semibold text-slate-700">Percent<input type="number" step="0.01" min="0" max="100" name="percent[<?= $showIn ?>]" value="<?= h((string)$section['percent']) ?>" class="<?= $input ?>" placeholder="100"></label>
          </div>
          <div class="source-panel source-calc">
            <div class="mb-2 flex items-center justify-between gap-2"><span class="text-xs font-bold uppercase tracking-wide text-slate-500">Calculation Rows</span><button type="button" class="add-calc-row rounded-lg border border-brand-200 bg-brand-50 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-100"><i class="fa-solid fa-plus mr-1"></i>Add Row</button></div>
            <div class="calc-rows space-y-2">
              <?php foreach (($section['calc_rows'] ?: [['calc_colm' => 1, 'calc_type' => 1, 'calc_addmins' => 0, 'com_percent' => '100']]) as $calc): ?>
              <div class="calc-row grid gap-2 rounded-xl border border-slate-200 bg-white p-3 md:grid-cols-[1fr_1fr_1.4fr_1fr_auto]">
                <select name="calc_colm[<?= $showIn ?>][]" class="<?= $input ?>"><?php foreach (f16cm_calc_columns() as $value => $name): ?><option value="<?= $value ?>" <?= (int)$calc['calc_colm'] === $value ? 'selected' : '' ?>><?= h($name) ?></option><?php endforeach; ?></select>
                <select name="calc_type[<?= $showIn ?>][]" class="<?= $input ?>"><?php foreach (f16cm_calc_types() as $value => $name): ?><option value="<?= $value ?>" <?= (int)$calc['calc_type'] === $value ? 'selected' : '' ?>><?= h($name) ?></option><?php endforeach; ?></select>
                <select name="calc_addmins[<?= $showIn ?>][]" class="<?= $input ?> calc-component-select"><option value="0">Select Component</option><?php foreach ($componentOptions as $component): $componentId = (int)$component['id']; if (f16cm_int_row($formRow, 'id') === $componentId) { continue; } ?><option value="<?= $componentId ?>" <?= (int)$calc['calc_addmins'] === $componentId ? 'selected' : '' ?>><?= h((string)$component['componentname']) ?></option><?php endforeach; ?></select>
                <input type="number" step="0.01" min="0" max="100" name="com_percent[<?= $showIn ?>][]" value="<?= h((string)$calc['com_percent']) ?>" class="<?= $input ?>" placeholder="100">
                <button type="button" class="remove-calc-row mt-1 rounded-lg border border-slate-200 px-3 py-2 text-red-600 hover:bg-red-50" title="Remove row"><i class="fa-solid fa-xmark"></i></button>
              </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/form16/form16-component-master.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 Component</button></div>
</form>
<script>
const f16ComponentOptions = <?= $componentOptionsJson ?: '[]' ?>;
function f16ComponentSelectHtml(sectionId) {
  let html = '<select name="calc_addmins[' + sectionId + '][]" class="<?= h($input) ?> calc-component-select"><option value="0">Select Component</option>';
  f16ComponentOptions.forEach(function (option) {
    html += '<option value="' + String(option.id) + '">' + String(option.name).replace(/[&<>"']/g, function (m) { return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]; }) + '</option>';
  });
  return html + '</select>';
}
function refreshSection(section) {
  const enabled = section.querySelector('.section-toggle').checked;
  const source = section.querySelector('.source-select').value;
  section.querySelectorAll('.section-body input, .section-body select, .section-body button').forEach(function (el) {
    if (!el.classList.contains('section-toggle')) el.disabled = !enabled;
  });
  section.querySelectorAll('.source-panel').forEach(function (panel) { panel.classList.add('hidden'); });
  if (enabled) {
    section.querySelector('.source-' + source).classList.remove('hidden');
    section.querySelectorAll('.source-panel.hidden input, .source-panel.hidden select, .source-panel.hidden button').forEach(function (el) { el.disabled = true; });
    section.querySelectorAll('.source-' + source + ' input, .source-' + source + ' select, .source-' + source + ' button').forEach(function (el) { el.disabled = false; });
  }
}
document.querySelectorAll('.f16-section').forEach(refreshSection);
document.addEventListener('change', function (event) {
  const section = event.target.closest('.f16-section');
  if (section && (event.target.classList.contains('section-toggle') || event.target.classList.contains('source-select'))) {
    refreshSection(section);
  }
});
document.addEventListener('click', function (event) {
  const addButton = event.target.closest('.add-calc-row');
  const removeButton = event.target.closest('.remove-calc-row');
  if (addButton) {
    const section = addButton.closest('.f16-section');
    const sectionId = section.getAttribute('data-section');
    const wrapper = section.querySelector('.calc-rows');
    const row = document.createElement('div');
    row.className = 'calc-row grid gap-2 rounded-xl border border-slate-200 bg-white p-3 md:grid-cols-[1fr_1fr_1.4fr_1fr_auto]';
    row.innerHTML = '<select name="calc_colm[' + sectionId + '][]" class="<?= h($input) ?>"><option value="1">Amount</option><option value="2">Gross</option><option value="3">Qualifying</option><option value="4">Deductible</option></select><select name="calc_type[' + sectionId + '][]" class="<?= h($input) ?>"><option value="1">Add</option><option value="2">Minus</option></select>' + f16ComponentSelectHtml(sectionId) + '<input type="number" step="0.01" min="0" max="100" name="com_percent[' + sectionId + '][]" value="100" class="<?= h($input) ?>" placeholder="100"><button type="button" class="remove-calc-row mt-1 rounded-lg border border-slate-200 px-3 py-2 text-red-600 hover:bg-red-50" title="Remove row"><i class="fa-solid fa-xmark"></i></button>';
    wrapper.appendChild(row);
    refreshSection(section);
  }
  if (removeButton) {
    const rows = removeButton.closest('.calc-rows').querySelectorAll('.calc-row');
    if (rows.length > 1) {
      removeButton.closest('.calc-row').remove();
    }
  }
});
</script>
<?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">Form 16 Component Master List</h2><p class="mt-1 text-xs font-medium text-slate-400">Components are ordered by configured order and 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-6"><input name="q" value="<?= h($filterQ) ?>" class="<?= $filterInput ?>" placeholder="Search component or order"><select name="status" class="<?= $filterInput ?>"><option value="">All Status</option><option value="1" <?= $filterStatus === '1' ? 'selected' : '' ?>>Active</option><option value="0" <?= $filterStatus === '0' ? 'selected' : '' ?>>Inactive</option></select><select name="assyear" class="<?= $filterInput ?>"><option value="">All Assessment Years</option><?php foreach ($years as $year): $yearId = (int)$year['id']; ?><option value="<?= $yearId ?>" <?= $filterYear === $yearId ? 'selected' : '' ?>><?= h($yearMap[$yearId] ?? (string)$yearId) ?></option><?php endforeach; ?></select><select name="asstype" class="<?= $filterInput ?>"><option value="">All Assessment Types</option><?php foreach (f16cm_ass_types() as $value => $label): ?><option value="<?= $value ?>" <?= $filterType === $value ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?></select><div class="flex gap-2 xl:col-span-2"><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="/form16/form16-component-master.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-[1300px] 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">Component</th><th class="px-5 py-4">Parent</th><th class="px-5 py-4">Assessment</th><th class="px-5 py-4">Flags</th><th class="px-5 py-4">Sections</th><th class="px-5 py-4">Status</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="8" class="px-6 py-14 text-center font-semibold text-slate-400">No Form 16 component master records found.</td></tr><?php endif; ?>
    <?php foreach ($rows as $index => $row): $grid = $row['grid'] ?? []; ?>
    <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"><div class="font-bold text-slate-800"><?= h(f16cm_text($row, 'componentname')) ?></div><div class="mt-1 text-xs font-semibold text-slate-400">Order <?= f16cm_int_row($row, 'orderby') ?> · ID <?= f16cm_int_row($row, 'id') ?></div></td>
      <td class="px-5 py-4 font-semibold text-slate-600"><?= h(f16cm_text($row, 'parent_name', '-')) ?></td>
      <td class="px-5 py-4"><div class="font-semibold text-slate-700"><?= h(f16cm_label_list(f16cm_csv_positive_ids($row['assyear'] ?? ''), $yearMap)) ?></div><div class="mt-1 text-xs font-semibold text-slate-400"><?= h(f16cm_label_list(f16cm_csv_ids($row['asstype'] ?? ''), f16cm_ass_types())) ?></div></td>
      <td class="px-5 py-4"><div class="flex max-w-xs flex-wrap gap-1"><?php foreach (['calculate' => 'Calculate', 'qualify' => 'Qualify', 'editable' => 'Editable', 'taxslab' => 'Tax Slab', 'preform' => 'Pre Form'] as $field => $label): if (f16cm_int_row($row, $field) === 1): ?><span class="rounded-md bg-brand-50 px-2 py-1 text-[10px] font-bold text-brand-700"><?= h($label) ?></span><?php endif; endforeach; ?></div></td>
      <td class="px-5 py-4"><div class="space-y-2"><?php foreach (f16cm_sections() as $showIn => $label): $summary = f16cm_section_summary($grid[$showIn] ?? [], $salaryMap, $componentMap); if ($summary === '-') { continue; } ?><div><span class="text-xs font-extrabold uppercase tracking-wide text-slate-400"><?= h($label) ?></span><div class="max-w-md text-xs font-semibold text-slate-700"><?= h($summary) ?></div></div><?php endforeach; ?></div></td>
      <td class="px-5 py-4"><?php if (f16cm_text($row, 'status') === '1'): ?><span class="rounded-full bg-emerald-50 px-3 py-1 text-xs font-bold text-emerald-700">Active</span><?php else: ?><span class="rounded-full bg-slate-100 px-3 py-1 text-xs font-bold text-slate-600">Inactive</span><?php endif; ?></td>
      <td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (!empty($acl['can_edit'])): ?><a href="?edit=<?= f16cm_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; ?><?php if (!empty($acl['can_delete'])): ?><form method="post" class="inline" onsubmit="return confirm('<?= f16cm_text($row, 'status') === '1' ? 'Deactivate' : 'Activate' ?> this Form 16 component?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="toggle_status"><input type="hidden" name="id" value="<?= f16cm_int_row($row, 'id') ?>"><input type="hidden" name="status" value="<?= f16cm_text($row, 'status') === '1' ? '0' : '1' ?>"><button type="submit" class="rounded-lg border border-slate-200 px-3 py-2 <?= f16cm_text($row, 'status') === '1' ? 'text-amber-600 hover:bg-amber-50' : 'text-emerald-600 hover:bg-emerald-50' ?>" title="<?= f16cm_text($row, 'status') === '1' ? 'Deactivate' : 'Activate' ?>"><i class="fa-solid <?= f16cm_text($row, 'status') === '1' ? 'fa-ban' : 'fa-check' ?>"></i></button></form><form method="post" class="inline" onsubmit="return confirm('Delete this Form 16 component?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= f16cm_int_row($row, 'id') ?>"><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 ?> components</span><div class="flex gap-2"><?php $base = ['q' => $filterQ, 'status' => $filterStatus, 'assyear' => $filterYear ?: '', 'asstype' => $filterType >= 0 ? $filterType : '']; 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(); ?>
