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

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

$pageLink = 'masters/categories.php';
$acl = require_acl('can_view', $pageLink);

$errors = [];
$flash = $_SESSION['flash_categories'] ?? null;
unset($_SESSION['flash_categories']);

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$historyId = max(0, (int)($_GET['history'] ?? 0));
$hasCategoryLogTable = false;
$logTableCheck = $con->query("SHOW TABLES LIKE 'jos_app_edit_category_log'");
if ($logTableCheck && $logTableCheck->num_rows > 0) {
    $hasCategoryLogTable = true;
}
$isHistoryView = $historyId > 0;
$isFormView = !$isHistoryView && ($mode === 'add' || $editId > 0);
$search = trim((string)($_GET['q'] ?? ''));
$editItem = null;
$historyItem = null;
$historyRows = [];

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));
        $categoryName = trim((string)($_POST['designation_name'] ?? ''));

        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit categories.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add categories.';
        }
        if ($categoryName === '') {
            $errors[] = 'Category name is required.';
        } elseif (strlen($categoryName) > 255) {
            $errors[] = 'Category name must be 255 characters or fewer.';
        }

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $stmt = $con->prepare('UPDATE jos_app_emp_category SET designation_name=? WHERE id=?');
                    $stmt->bind_param('si', $categoryName, $id);
                    $stmt->execute();
                    $stmt->close();
                    $categoryId = $id;
                    audit_log('category.update', 'jos_app_emp_category', (string)$categoryId, $categoryName);
                } else {
                    $stmt = $con->prepare('INSERT INTO jos_app_emp_category (designation_name) VALUES (?)');
                    $stmt->bind_param('s', $categoryName);
                    $stmt->execute();
                    $categoryId = (int)$con->insert_id;
                    $stmt->close();
                    audit_log('category.create', 'jos_app_emp_category', (string)$categoryId, $categoryName);
                }

                if ($hasCategoryLogTable) {
                    $userId = (int)(current_user()['id'] ?? 0);
                    $stmt = $con->prepare('INSERT INTO jos_app_edit_category_log (designationid, designation_name, date, time, modify_by) VALUES (?, ?, NOW(), NOW(), ?)');
                    if ($stmt) {
                        $stmt->bind_param('isi', $categoryId, $categoryName, $userId);
                        $stmt->execute();
                        $stmt->close();
                    }
                }

                $con->commit();
                $_SESSION['flash_categories'] = $id > 0 ? 'Category updated successfully.' : 'Category saved successfully.';
                redirect('/masters/categories.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save category. Please try again.';
            }
        }

        $isFormView = true;
        $editId = $id;
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete categories.';
        }

        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0) {
            $errors[] = 'Invalid category selected.';
        }

        if (!$errors) {
            $name = '';
            $stmt = $con->prepare('SELECT designation_name FROM jos_app_emp_category WHERE id=? LIMIT 1');
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            $name = (string)($row['designation_name'] ?? '');

            $con->begin_transaction();
            try {
                if ($hasCategoryLogTable) {
                    $stmt = $con->prepare('DELETE FROM jos_app_edit_category_log WHERE designationid=?');
                    if ($stmt) {
                        $stmt->bind_param('i', $id);
                        $stmt->execute();
                        $stmt->close();
                    }
                }

                $stmt = $con->prepare('DELETE FROM jos_app_emp_category WHERE id=?');
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();

                $con->commit();
                audit_log('category.delete', 'jos_app_emp_category', (string)$id, $name);
                $_SESSION['flash_categories'] = 'Category deleted successfully.';
                redirect('/masters/categories.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to delete category. Please try again.';
            }
        }
    }
}

if ($editId > 0) {
    $stmt = $con->prepare('SELECT id, designation_name FROM jos_app_emp_category WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editItem = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();

    if (!$editItem && !$errors) {
        $_SESSION['flash_categories'] = 'Category record was not found.';
        redirect('/masters/categories.php');
    }
}

if ($historyId > 0) {
    $stmt = $con->prepare('SELECT id, designation_name FROM jos_app_emp_category WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $historyId);
    $stmt->execute();
    $historyItem = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();

    if (!$historyItem && !$errors) {
        $_SESSION['flash_categories'] = 'Category record was not found.';
        redirect('/masters/categories.php');
    }

    if ($hasCategoryLogTable && $historyItem) {
        $stmt = $con->prepare('SELECT id, designation_name, date, time, modify_by FROM jos_app_edit_category_log WHERE designationid=? ORDER BY id DESC');
        $stmt->bind_param('i', $historyId);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $historyRows[] = $row;
        }
        $stmt->close();
    }
}

$categories = [];
if (!$isFormView) {
    if ($search !== '') {
        $like = '%' . $search . '%';
        $sql = $hasCategoryLogTable
            ? 'SELECT c.id, c.designation_name, (SELECT COUNT(*) FROM jos_app_edit_category_log l WHERE l.designationid=c.id) AS log_count FROM jos_app_emp_category c WHERE c.designation_name LIKE ? ORDER BY c.id ASC'
            : 'SELECT id, designation_name, 0 AS log_count FROM jos_app_emp_category WHERE designation_name LIKE ? ORDER BY id ASC';
        $stmt = $con->prepare($sql);
        $stmt->bind_param('s', $like);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
        $stmt->close();
    } else {
        $sql = $hasCategoryLogTable
            ? 'SELECT c.id, c.designation_name, (SELECT COUNT(*) FROM jos_app_edit_category_log l WHERE l.designationid=c.id) AS log_count FROM jos_app_emp_category c ORDER BY c.id ASC'
            : 'SELECT id, designation_name, 0 AS log_count FROM jos_app_emp_category ORDER BY id ASC';
        $result = $con->query($sql);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $categories[] = $row;
            }
            $result->free();
        }
    }
}

$formId = (int)($editItem['id'] ?? 0);
$formCategoryName = $errors ? trim((string)($_POST['designation_name'] ?? '')) : (string)($editItem['designation_name'] ?? '');

console_header('Categories', $pageLink);
?>
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
    <div>
        <div class="flex items-center gap-2 text-[12px] font-semibold text-slate-500 mb-2">
            <a href="/dashboard.php" class="hover:text-brand-600 transition-colors">Dashboard</a>
            <i class="fa-solid fa-chevron-right text-[9px] text-slate-300"></i>
            <span>Masters</span>
            <i class="fa-solid fa-chevron-right text-[9px] text-slate-300"></i>
            <span class="text-brand-600">Categories</span>
        </div>
        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Category Master</h1>
        <p class="text-sm text-slate-500 mt-1">Manage employee category records from the payroll configuration master.</p>
    </div>
    <div class="bg-white border border-slate-100 rounded-xl shadow-sm px-4 py-3 flex items-center gap-3">
        <span class="w-10 h-10 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-solid fa-layer-group"></i></span>
        <div>
            <div class="text-[11px] font-bold text-slate-400 uppercase tracking-widest"><?= $isFormView ? 'Form View' : ($isHistoryView ? 'History View' : 'Total Categories') ?></div>
            <div class="text-lg font-bold text-slate-900 leading-tight"><?= $isFormView ? ($formId ? 'Edit' : 'Add') : ($isHistoryView ? 'Log' : count($categories)) ?></div>
        </div>
    </div>
</div>

<?php if ($flash): ?>
    <div class="mb-6 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-emerald-700 shadow-sm flex gap-3">
        <span class="mt-0.5 w-8 h-8 rounded-lg bg-emerald-100 text-emerald-600 flex items-center justify-center shrink-0"><i class="fa-solid fa-check text-sm"></i></span>
        <div><h2 class="text-base font-bold">Message</h2><p class="mt-1 text-sm font-medium"><?= h($flash) ?></p></div>
    </div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="mb-6 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-red-700 shadow-sm">
        <h2 class="text-base font-bold">Please fix the following</h2>
        <ul class="mt-2 text-sm font-medium list-disc list-inside"><?php foreach ($errors as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<?php if (!$isFormView && !$isHistoryView): ?>
    <section class="bg-white rounded-[1.25rem] shadow-sm border border-slate-100 overflow-hidden">
        <div class="px-6 py-5 border-b border-slate-100 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 bg-white">
            <div>
                <h2 class="font-semibold text-slate-800 flex items-center gap-2">
                    <span class="w-9 h-9 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-solid fa-layer-group text-sm"></i></span>
                    Category List
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 lg:ml-11">Source table: <span class="font-semibold">jos_app_emp_category</span></p>
            </div>
            <div class="flex flex-col sm:flex-row gap-2">
                <form method="get" class="flex flex-col sm:flex-row gap-2">
                    <div class="relative">
                        <i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                        <input type="search" name="q" value="<?= h($search) ?>" placeholder="Search category" class="w-full sm:w-64 rounded-lg border border-slate-200 bg-white py-2.5 pl-9 pr-3 text-sm font-medium outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100">
                    </div>
                    <button class="rounded-lg bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 px-4 py-2.5 text-sm font-semibold shadow-sm" type="submit">Search</button>
                    <?php if ($search !== ''): ?><a class="rounded-lg bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 px-4 py-2.5 text-sm font-semibold shadow-sm text-center" href="/masters/categories.php">Clear</a><?php endif; ?>
                </form>
                <?php if (!empty($acl['can_add'])): ?>
                    <a href="/masters/categories.php?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 hover:bg-brand-700 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition-all">
                        <i class="fa-solid fa-plus text-xs"></i> Add
                    </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full min-w-[720px] text-sm text-left text-slate-600">
                <thead class="bg-slate-50/80 text-[10px] font-extrabold text-slate-800 uppercase tracking-wider">
                    <tr>
                        <th class="border-b border-slate-100 px-6 py-4 w-28">Sr No</th>
                        <th class="border-b border-slate-100 px-6 py-4">Category Name</th>
                        <th class="border-b border-slate-100 px-6 py-4 text-right w-44">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (!$categories): ?>
                        <tr><td colspan="3" class="px-6 py-10 text-center text-slate-400 font-semibold">No categories found.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($categories as $index => $category): ?>
                        <tr class="hover:bg-slate-50/80 transition-colors">
                            <td class="px-6 py-5 font-semibold text-slate-500"><?= $index + 1 ?></td>
                            <td class="px-6 py-5"><span class="font-semibold text-slate-900"><?= h($category['designation_name']) ?></span></td>
                            <td class="px-6 py-5">
                                <div class="flex items-center justify-end gap-2">
                                    <?php if (!empty($acl['can_edit'])): ?>
                                        <a href="/masters/categories.php?edit=<?= (int)$category['id'] ?>" class="w-9 h-9 rounded-lg border border-slate-200 bg-white text-slate-500 hover:border-brand-200 hover:bg-brand-50 hover:text-brand-600 transition-colors flex items-center justify-center" aria-label="Edit <?= h($category['designation_name']) ?>"><i class="fa-regular fa-pen-to-square text-base"></i></a>
                                    <?php endif; ?>
                                    <?php if ((int)($category['log_count'] ?? 0) > 1): ?>
                                        <a href="/masters/categories.php?history=<?= (int)$category['id'] ?>" class="w-9 h-9 rounded-lg border border-slate-200 bg-white text-slate-500 hover:border-brand-200 hover:bg-brand-50 hover:text-brand-600 transition-colors flex items-center justify-center" aria-label="View history for <?= h($category['designation_name']) ?>"><i class="fa-regular fa-eye text-base"></i></a>
                                    <?php endif; ?>
                                    <?php if (!empty($acl['can_delete'])): ?>
                                        <form method="post" onsubmit="return confirm('Delete this category?');">
                                            <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= (int)$category['id'] ?>">
                                            <button type="submit" class="w-9 h-9 rounded-lg border border-slate-200 bg-white text-slate-500 hover:border-red-200 hover:bg-red-50 hover:text-red-600 transition-colors" aria-label="Delete <?= h($category['designation_name']) ?>"><i class="fa-regular fa-trash-can text-base"></i></button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>
<?php elseif ($isHistoryView): ?>
    <section class="bg-white rounded-[1.25rem] shadow-sm border border-slate-100 overflow-hidden">
        <div class="px-6 py-5 border-b border-slate-100 bg-white flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
                <h2 class="font-semibold text-slate-800 flex items-center gap-2">
                    <span class="w-9 h-9 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-regular fa-eye text-sm"></i></span>
                    Category History
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 sm:ml-11">Change log for <span class="font-semibold text-slate-500"><?= h($historyItem['designation_name'] ?? '') ?></span></p>
            </div>
            <a href="/masters/categories.php" class="inline-flex justify-center items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:bg-slate-50 hover:border-slate-300">
                <i class="fa-solid fa-arrow-left text-xs text-slate-400"></i> Back to List
            </a>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full min-w-[760px] text-sm text-left text-slate-600">
                <thead class="bg-slate-50/80 text-[10px] font-extrabold text-slate-800 uppercase tracking-wider">
                    <tr>
                        <th class="border-b border-slate-100 px-6 py-4 w-28">Sr No</th>
                        <th class="border-b border-slate-100 px-6 py-4">Category Name</th>
                        <th class="border-b border-slate-100 px-6 py-4">Date</th>
                        <th class="border-b border-slate-100 px-6 py-4">Time</th>
                        <th class="border-b border-slate-100 px-6 py-4">Modified By</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (!$historyRows): ?>
                        <tr><td colspan="5" class="px-6 py-10 text-center text-slate-400 font-semibold">No category history found.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($historyRows as $index => $row): ?>
                        <tr class="hover:bg-slate-50/80 transition-colors">
                            <td class="px-6 py-5 font-semibold text-slate-500"><?= $index + 1 ?></td>
                            <td class="px-6 py-5"><span class="font-semibold text-slate-900"><?= h($row['designation_name']) ?></span></td>
                            <td class="px-6 py-5 font-medium text-slate-600"><?= h((string)$row['date']) ?></td>
                            <td class="px-6 py-5 font-medium text-slate-600"><?= h((string)$row['time']) ?></td>
                            <td class="px-6 py-5 font-medium text-slate-600"><?= h((string)$row['modify_by']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>
<?php else: ?>
    <section class="bg-white rounded-[1.25rem] shadow-sm border border-slate-100 overflow-hidden">
        <div class="px-6 py-5 border-b border-slate-100 bg-white flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
                <h2 class="font-semibold text-slate-800 flex items-center gap-2">
                    <span class="w-9 h-9 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-solid fa-layer-group text-sm"></i></span>
                    <?= $formId ? 'Edit Category' : 'Add Category' ?>
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 sm:ml-11">Category name is required.</p>
            </div>
            <a href="/masters/categories.php" class="inline-flex justify-center items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:bg-slate-50 hover:border-slate-300">
                <i class="fa-solid fa-arrow-left text-xs text-slate-400"></i> Back to List
            </a>
        </div>

        <?php if (($formId && empty($acl['can_edit'])) || (!$formId && empty($acl['can_add']))): ?>
            <div class="p-6 text-sm font-semibold text-amber-700 bg-amber-50 border-t border-amber-100">You can view this page, but you do not have permission to <?= $formId ? 'edit' : 'add' ?> categories.</div>
        <?php else: ?>
            <form method="post" class="p-6 sm:p-8">
                <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" value="<?= $formId ?>">

                <div class="max-w-5xl">
                    <label for="designation_name" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Category Name <span class="text-amber-500">*</span></label>
                    <input id="designation_name" name="designation_name" type="text" value="<?= h($formCategoryName) ?>" required maxlength="255" placeholder="Category Name" class="block w-full rounded-xl border border-slate-200 bg-white py-3.5 px-4 text-sm font-medium text-slate-900 placeholder:text-slate-400 shadow-sm outline-none transition-all focus:border-brand-500 focus:ring-4 focus:ring-brand-100">
                </div>

                <div class="mt-8 flex flex-col-reverse sm:flex-row sm:items-center gap-3">
                    <button type="submit" class="inline-flex justify-center items-center gap-2 rounded-lg bg-brand-900 hover:bg-slate-800 px-6 py-3 text-sm font-semibold text-white shadow-sm transition-all active:scale-[0.98]"><i class="fa-solid fa-check text-xs"></i> Submit</button>
                    <a href="/masters/categories.php" class="inline-flex justify-center items-center gap-2 rounded-lg border border-slate-200 bg-white px-6 py-3 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:bg-slate-50 hover:border-slate-300"><i class="fa-solid fa-xmark text-xs text-slate-400"></i> Cancel</a>
                </div>
            </form>
        <?php endif; ?>
    </section>
<?php endif; ?>
<?php console_footer(); ?>
