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

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

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

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

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

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

function ptc_money($value, string $label, array &$errors): 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 amount.';
        return '0';
    }
    $amount = (float)$raw;
    if ($amount < 0 || $amount > 999999999) {
        $errors[] = $label . ' is outside the allowed range.';
    }
    return rtrim(rtrim(number_format($amount, 2, '.', ''), '0'), '.');
}

function ptc_save_row(mysqli $con, int $id, array $data): int
{
    if ($id > 0) {
        $stmt = ptc_stmt($con, 'UPDATE jos_app_ptaxconfig SET gender=?, sal_from=?, sal_to=?, ptax=? WHERE id=?');
        $stmt->bind_param('idddi', $data['gender'], $data['sal_from'], $data['sal_to'], $data['ptax'], $id);
        if (!$stmt->execute()) {
            throw new RuntimeException('Unable to update P-Tax configuration.');
        }
        $stmt->close();
        return $id;
    }

    $stmt = ptc_stmt($con, 'INSERT INTO jos_app_ptaxconfig (gender, sal_from, sal_to, ptax) VALUES (?,?,?,?)');
    $stmt->bind_param('iddd', $data['gender'], $data['sal_from'], $data['sal_to'], $data['ptax']);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to add P-Tax configuration.');
    }
    $savedId = (int)$con->insert_id;
    $stmt->close();
    return $savedId;
}

function ptc_insert_history(mysqli $con, int $configId): void
{
    $row = ptc_fetch_row($con, $configId);
    if (!$row) {
        return;
    }
    $userId = (int)(current_user()['id'] ?? 0);
    $stmt = ptc_stmt($con, 'INSERT INTO jos_app_ptaxconfig_editlog (ptaxid, date, gender, sal_from, sal_to, ptax, modify_by) VALUES (?, NOW(), ?, ?, ?, ?, ?)');
    $gender = (int)$row['gender'];
    $salFrom = (float)$row['sal_from'];
    $salTo = (float)$row['sal_to'];
    $ptax = (float)$row['ptax'];
    $stmt->bind_param('iidddi', $configId, $gender, $salFrom, $salTo, $ptax, $userId);
    if (!$stmt->execute()) {
        throw new RuntimeException('Unable to save P-Tax configuration history.');
    }
    $stmt->close();
}

function ptc_history_rows(mysqli $con, int $configId): array
{
    $rows = [];
    $stmt = ptc_stmt($con, 'SELECT * FROM jos_app_ptaxconfig_editlog WHERE ptaxid=? 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 ptc_text(array $row, string $key, string $default = ''): string
{
    return array_key_exists($key, $row) && $row[$key] !== null ? (string)$row[$key] : $default;
}

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

function ptc_amount_label($value): string
{
    $number = (float)$value;
    return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}

function ptc_gender_label(int $gender): string
{
    return $gender === 1 ? 'Male' : ($gender === 2 ? 'Female' : '');
}

$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, 'gender' => '', 'sal_from' => '', 'sal_to' => '', 'ptax' => ''];
$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 = ptc_fetch_row($con, $editId) ?: [];
    if (!$editRow) {
        $_SESSION['flash_ptax_configuration'] = 'P-Tax Configuration was not found.';
        redirect('/payroll/p-tax-configuration.php');
    }
}

if ($historyId > 0) {
    $isHistory = true;
    $historyParent = ptc_fetch_row($con, $historyId);
    if (!$historyParent) {
        $_SESSION['flash_ptax_configuration'] = 'P-Tax Configuration was not found.';
        redirect('/payroll/p-tax-configuration.php');
    }
    $historyRows = ptc_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 P-Tax configurations.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add P-Tax configurations.';
        }
        if ($id > 0 && !ptc_exists($con, $id)) {
            $errors[] = 'P-Tax Configuration was not found.';
        }

        $gender = (int)($_POST['gender'] ?? 0);
        if (!in_array($gender, [1, 2], true)) {
            $errors[] = 'Select a valid Gender.';
        }
        $salFrom = ptc_money($_POST['sal_from'] ?? '', 'Salary From', $errors);
        $salTo = ptc_money($_POST['sal_to'] ?? '', 'Salary To', $errors);
        $ptax = ptc_money($_POST['ptax'] ?? '', 'P-Tax', $errors);
        if ((float)$salTo < (float)$salFrom) {
            $errors[] = 'Salary To must be greater than or equal to Salary From.';
        }

        $data = [
            'gender' => $gender,
            'sal_from' => $salFrom,
            'sal_to' => $salTo,
            'ptax' => $ptax,
        ];

        if (!$errors) {
            $con->begin_transaction();
            try {
                $savedId = ptc_save_row($con, $id, $data);
                ptc_insert_history($con, $savedId);
                $con->commit();
                $_SESSION['flash_ptax_configuration'] = $id > 0 ? 'P-Tax Configuration updated successfully.' : 'P-Tax Configuration added successfully.';
                redirect('/payroll/p-tax-configuration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save the P-Tax configuration. No changes were committed.';
            }
        }
        $isForm = true;
        $isHistory = false;
        $editRow = $data + ['id' => $id];
    }
}

$filterQ = trim((string)($_GET['q'] ?? ''));
$filterGender = isset($_GET['gender']) && $_GET['gender'] !== '' ? (int)$_GET['gender'] : 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[] = '(CAST(c.sal_from AS CHAR) LIKE ? OR CAST(c.sal_to AS CHAR) LIKE ? OR CAST(c.ptax AS CHAR) LIKE ?)';
        $types .= 'sss';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
        $params[] = '%' . $filterQ . '%';
    }
    if (in_array($filterGender, [1, 2], true)) {
        $where[] = 'c.gender=?';
        $types .= 'i';
        $params[] = $filterGender;
    }
    $whereSql = implode(' AND ', $where);

    $stmt = ptc_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_ptaxconfig 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 = ptc_stmt($con, 'SELECT c.*,(SELECT COUNT(*) FROM jos_app_ptaxconfig_editlog e WHERE e.ptaxid=c.id) AS history_count FROM jos_app_ptaxconfig c WHERE ' . $whereSql . ' ORDER BY c.gender ASC,c.sal_from 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();
}

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

console_header('P-Tax 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">P-Tax Configuration</span></div>
    <h1 class="text-2xl font-bold text-slate-900">P-Tax Configuration</h1>
    <p class="mt-1 text-sm text-slate-500">Configure professional tax salary slabs by gender.</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">P-Tax Configuration History</h2><p class="mt-1 text-xs font-medium text-slate-400"><?= h(ptc_gender_label(ptc_int_row($historyParent ?? [], 'gender'))) ?>, <?= h(ptc_amount_label(ptc_text($historyParent ?? [], 'sal_from'))) ?> - <?= h(ptc_amount_label(ptc_text($historyParent ?? [], 'sal_to'))) ?></p></div><a href="/payroll/p-tax-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-[840px] 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">Gender</th><th class="px-5 py-4">Salary From</th><th class="px-5 py-4">Salary To</th><th class="px-5 py-4">P-Tax</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="6" 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(ptc_text($row, 'date')) ?></td><td class="px-5 py-4"><?= h(ptc_gender_label(ptc_int_row($row, 'gender'))) ?></td><td class="px-5 py-4"><?= h(ptc_amount_label(ptc_text($row, 'sal_from'))) ?></td><td class="px-5 py-4"><?= h(ptc_amount_label(ptc_text($row, 'sal_to'))) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(ptc_amount_label(ptc_text($row, 'ptax'))) ?></td><td class="px-5 py-4"><?= (int)ptc_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-receipt"></i></span><div><h2 class="font-bold text-slate-800"><?= (int)$value('id', 0) > 0 ? 'Edit P-Tax Configuration' : 'New P-Tax Configuration' ?></h2><p class="text-xs text-slate-400">Fields marked with * are required.</p></div></div><a href="/payroll/p-tax-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 xl:grid-cols-4">
      <label class="text-sm font-semibold text-slate-700">Gender *<select name="gender" required class="<?= $input ?>"><option value="">Select Gender</option><option value="1" <?= (int)$value('gender') === 1 ? 'selected' : '' ?>>Male</option><option value="2" <?= (int)$value('gender') === 2 ? 'selected' : '' ?>>Female</option></select></label>
      <label class="text-sm font-semibold text-slate-700">Salary From *<input type="number" step="0.01" min="0" name="sal_from" required value="<?= h((string)$value('sal_from')) ?>" class="<?= $input ?>" placeholder="Salary From"></label>
      <label class="text-sm font-semibold text-slate-700">Salary To *<input type="number" step="0.01" min="0" name="sal_to" required value="<?= h((string)$value('sal_to')) ?>" class="<?= $input ?>" placeholder="Salary To"></label>
      <label class="text-sm font-semibold text-slate-700">P-Tax *<input type="number" step="0.01" min="0" name="ptax" required value="<?= h((string)$value('ptax')) ?>" class="<?= $input ?>" placeholder="P-Tax"></label>
    </div>
  </section>
  <div class="flex flex-wrap justify-end gap-2"><a href="/payroll/p-tax-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">P-Tax Configuration List</h2><p class="mt-1 text-xs font-medium text-slate-400">P-Tax slabs are ordered by gender and salary range.</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>
  <div class="border-b border-amber-100 bg-amber-50 px-5 py-3 text-sm font-semibold text-amber-700"><i class="fa-solid fa-circle-info mr-2"></i>Rupees 300 will be deducted in month of February.</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 salary or P-Tax amount"><select name="gender" class="<?= $filterInput ?>"><option value="">All Genders</option><option value="1" <?= $filterGender === 1 ? 'selected' : '' ?>>Male</option><option value="2" <?= $filterGender === 2 ? 'selected' : '' ?>>Female</option></select><div class="flex gap-2 xl:col-span-3"><button class="rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button><a href="/payroll/p-tax-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-[860px] 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">Gender</th><th class="px-5 py-4">Salary From</th><th class="px-5 py-4">Salary To</th><th class="px-5 py-4">P-Tax</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 P-Tax 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(ptc_gender_label(ptc_int_row($row, 'gender'))) ?><?php if (ptc_int_row($row, 'history_count') > 0): ?><div class="mt-1 text-xs font-semibold text-slate-400">History <?= ptc_int_row($row, 'history_count') ?></div><?php endif; ?></td><td class="px-5 py-4"><?= h(ptc_amount_label(ptc_text($row, 'sal_from'))) ?></td><td class="px-5 py-4"><?= h(ptc_amount_label(ptc_text($row, 'sal_to'))) ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(ptc_amount_label(ptc_text($row, 'ptax'))) ?></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (ptc_int_row($row, 'history_count') > 0): ?><a href="?history=<?= ptc_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=<?= ptc_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, 'gender' => $filterGender ?: '']; 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(); ?>
