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

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

$pageLink = 'masters/employee-status.php';
$acl = require_acl('can_view', $pageLink);

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

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$isFormView = $mode === 'add' || $editId > 0;
$search = trim((string)($_GET['q'] ?? ''));
$editItem = null;

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));
        $statusName = trim((string)($_POST['status_name'] ?? ''));
        $durationMonths = trim((string)($_POST['duration_months'] ?? ''));
        $status = !empty($_POST['status']) ? 1 : 0;

        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit employee statuses.';
        }
        if ($id === 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add employee statuses.';
        }
        if ($statusName === '') {
            $errors[] = 'Status name is required.';
        } elseif (strlen($statusName) > 255) {
            $errors[] = 'Status name must be 255 characters or fewer.';
        }
        if ($durationMonths === '') {
            $errors[] = 'Duration month is required.';
        } elseif (!preg_match('/^\d+$/', $durationMonths)) {
            $errors[] = 'Duration month must be a whole number.';
        }

        if (!$errors) {
            $duration = (int)$durationMonths;
            if ($id > 0) {
                $stmt = $con->prepare('UPDATE jos_app_employment_status SET status_name=?, duration_months=?, status=? WHERE id=?');
                $stmt->bind_param('siii', $statusName, $duration, $status, $id);
                $stmt->execute();
                $stmt->close();
                audit_log('employee_status.update', 'jos_app_employment_status', (string)$id, $statusName);
                $_SESSION['flash_employee_status'] = 'Employee status updated successfully.';
            } else {
                $stmt = $con->prepare('INSERT INTO jos_app_employment_status (status_name, duration_months, status) VALUES (?, ?, ?)');
                $stmt->bind_param('sii', $statusName, $duration, $status);
                $stmt->execute();
                $newId = (int)$con->insert_id;
                $stmt->close();
                audit_log('employee_status.create', 'jos_app_employment_status', (string)$newId, $statusName);
                $_SESSION['flash_employee_status'] = 'Employee status saved successfully.';
            }
            redirect('/masters/employee-status.php');
        }
        $isFormView = true;
        $editId = $id;
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete employee statuses.';
        }

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

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

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

            audit_log('employee_status.delete', 'jos_app_employment_status', (string)$id, $name);
            $_SESSION['flash_employee_status'] = 'Employee status deleted successfully.';
            redirect('/masters/employee-status.php');
        }
    }
}

if ($editId > 0) {
    $stmt = $con->prepare('SELECT id, status_name, duration_months, status FROM jos_app_employment_status 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_employee_status'] = 'Employee status record was not found.';
        redirect('/masters/employee-status.php');
    }
}

$statuses = [];
if (!$isFormView) {
    if ($search !== '') {
        $like = '%' . $search . '%';
        $stmt = $con->prepare('SELECT id, status_name, duration_months, status FROM jos_app_employment_status WHERE status_name LIKE ? OR duration_months LIKE ? ORDER BY id ASC');
        $stmt->bind_param('ss', $like, $like);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $statuses[] = $row;
        }
        $stmt->close();
    } else {
        $result = $con->query('SELECT id, status_name, duration_months, status FROM jos_app_employment_status ORDER BY id ASC');
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $statuses[] = $row;
            }
            $result->free();
        }
    }
}

$formId = (int)($editItem['id'] ?? 0);
$formStatusName = $errors ? trim((string)($_POST['status_name'] ?? '')) : (string)($editItem['status_name'] ?? '');
$formDurationMonths = $errors ? trim((string)($_POST['duration_months'] ?? '')) : (string)($editItem['duration_months'] ?? '');
$formStatus = $errors ? (!empty($_POST['status']) ? 1 : 0) : (int)($editItem['status'] ?? 1);

console_header('Employee Status', $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">Employee Status</span>
        </div>
        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Employee Status Master</h1>
        <p class="text-sm text-slate-500 mt-1">Manage employment status 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-user-check"></i></span>
        <div>
            <div class="text-[11px] font-bold text-slate-400 uppercase tracking-widest"><?= $isFormView ? 'Form View' : 'Total Statuses' ?></div>
            <div class="text-lg font-bold text-slate-900 leading-tight"><?= $isFormView ? ($formId ? 'Edit' : 'Add') : count($statuses) ?></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): ?>
    <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-user-check text-sm"></i></span>
                    Employee Status List
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 lg:ml-11">Source table: <span class="font-semibold">jos_app_employment_status</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 status" 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/employee-status.php">Clear</a><?php endif; ?>
                </form>
                <?php if (!empty($acl['can_add'])): ?>
                    <a href="/masters/employee-status.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-[900px] 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">Status Name</th>
                        <th class="border-b border-slate-100 px-6 py-4 w-48">Duration Month</th>
                        <th class="border-b border-slate-100 px-6 py-4 w-44">Active Status</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 (!$statuses): ?>
                        <tr><td colspan="5" class="px-6 py-10 text-center text-slate-400 font-semibold">No employee statuses found.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($statuses as $index => $statusRow): ?>
                        <?php $isActive = (int)($statusRow['status'] ?? 0) === 1; ?>
                        <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($statusRow['status_name']) ?></span></td>
                            <td class="px-6 py-5 font-semibold text-slate-700"><?= h((string)$statusRow['duration_months']) ?></td>
                            <td class="px-6 py-5">
                                <span class="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] font-bold <?= $isActive ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-slate-100 text-slate-500 border border-slate-200' ?>">
                                    <span class="w-1.5 h-1.5 rounded-full <?= $isActive ? 'bg-emerald-500' : 'bg-slate-400' ?>"></span><?= $isActive ? 'Active' : 'Inactive' ?>
                                </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/employee-status.php?edit=<?= (int)$statusRow['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($statusRow['status_name']) ?>"><i class="fa-regular fa-pen-to-square text-base"></i></a>
                                    <?php endif; ?>
                                    <?php if (!empty($acl['can_delete'])): ?>
                                        <form method="post" onsubmit="return confirm('Delete this employee status permanently?');">
                                            <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= (int)$statusRow['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($statusRow['status_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 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-user-check text-sm"></i></span>
                    <?= $formId ? 'Edit Employee Status' : 'Add Employee Status' ?>
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 sm:ml-11">Status name, duration month, and active status are required.</p>
            </div>
            <a href="/masters/employee-status.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' ?> employee statuses.</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 grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_220px_220px] gap-5">
                    <div>
                        <label for="status_name" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Status Name <span class="text-amber-500">*</span></label>
                        <input id="status_name" name="status_name" type="text" value="<?= h($formStatusName) ?>" required maxlength="255" placeholder="Status 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>
                        <label for="duration_months" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Duration Month <span class="text-amber-500">*</span></label>
                        <input id="duration_months" name="duration_months" type="number" min="0" step="1" value="<?= h($formDurationMonths) ?>" required placeholder="Duration" 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>
                        <label for="status" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Active Status</label>
                        <select id="status" name="status" class="block w-full rounded-xl border border-slate-200 bg-white py-3.5 px-4 text-sm font-medium text-slate-900 shadow-sm outline-none transition-all focus:border-brand-500 focus:ring-4 focus:ring-brand-100">
                            <option value="1" <?= $formStatus ? 'selected' : '' ?>>Active</option>
                            <option value="0" <?= !$formStatus ? 'selected' : '' ?>>Inactive</option>
                        </select>
                    </div>
                </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/employee-status.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(); ?>
