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

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

$pageLink = 'masters/employee-registration.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_employee_registration'] ?? null;
unset($_SESSION['flash_employee_registration']);

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

function er_options(mysqli $con, string $sql): array
{
    $rows = [];
    $result = $con->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) $rows[] = $row;
        $result->free();
    }
    return $rows;
}

function er_ids($value): array
{
    return array_values(array_unique(array_filter(array_map('intval', (array)$value), static function ($id) { return $id > 0; })));
}

function er_date(string $value, string $fallback = '1970-01-01'): string
{
    if ($value === '') return $fallback;
    $date = DateTime::createFromFormat('Y-m-d', $value);
    return $date && $date->format('Y-m-d') === $value ? $value : $fallback;
}

function er_valid_id(mysqli $con, string $table, int $id, string $extra = ''): bool
{
    if ($id <= 0) return false;
    $allowed = ['jos_app_department', 'jos_app_designation', 'jos_app_emp_category', 'jos_app_emp_skilllevel', 'jos_app_payrolllocation', 'jos_app_orglocation', 'jos_app_subbranch', 'jos_app_banktype', 'jos_app_empshift'];
    if (!in_array($table, $allowed, true)) return false;
    $stmt = er_stmt($con, 'SELECT id FROM `' . $table . '` WHERE id=? ' . $extra . ' LIMIT 1');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $exists = (bool)$stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $exists;
}

function er_insert_employee(mysqli $con, array $values): int
{
    $columns = [];
    $params = [];
    $result = $con->query('SHOW COLUMNS FROM jos_app_employee');
    if (!$result) throw new RuntimeException('Unable to inspect employee table.');
    while ($column = $result->fetch_assoc()) {
        $name = (string)$column['Field'];
        if (strpos((string)$column['Extra'], 'auto_increment') !== false) continue;
        $type = strtolower((string)$column['Type']);
        if (array_key_exists($name, $values)) {
            $value = $values[$name];
        } elseif ($column['Default'] !== null) {
            $value = $column['Default'];
        } elseif (strpos($type, 'date') !== false && strpos($type, 'datetime') === false) {
            $value = '1970-01-01';
        } elseif (strpos($type, 'datetime') !== false || strpos($type, 'timestamp') !== false) {
            $value = date('Y-m-d H:i:s');
        } elseif (preg_match('/int|decimal|float|double/', $type)) {
            $value = 0;
        } else {
            $value = '';
        }
        $columns[] = '`' . $name . '`';
        $params[] = (string)$value;
    }
    $result->free();
    $sql = 'INSERT INTO jos_app_employee (' . implode(',', $columns) . ') VALUES (' . implode(',', array_fill(0, count($params), '?')) . ')';
    $stmt = er_stmt($con, $sql);
    $types = str_repeat('s', count($params));
    $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) throw new RuntimeException('Unable to save employee.');
    $id = (int)$con->insert_id;
    $stmt->close();
    return $id;
}

function er_save_relations(mysqli $con, int $employeeId, array $shiftIds, array $terminalIds, int $designation, string $dob): void
{
    $shiftValue = implode(',', $shiftIds);
    $stmt = er_stmt($con, 'SELECT id FROM jos_app_employeeinfo WHERE employeeid=? LIMIT 1');
    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $info = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if ($info) {
        $stmt = er_stmt($con, 'UPDATE jos_app_employeeinfo SET designation=?, dob=?, shift_type=? WHERE employeeid=?');
        $stmt->bind_param('issi', $designation, $dob, $shiftValue, $employeeId);
    } else {
        $now = date('Y-m-d H:i:s');
        $empty = '';
        $zero = 0;
        $stmt = er_stmt($con, 'INSERT INTO jos_app_employeeinfo (employeeid,registerdate,son,phone,pincode,lat,lon,dob,designation,shift_type,job_type,addpayroll_location,qualification) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->bind_param('issssddsisisi', $employeeId, $now, $empty, $empty, $empty, $zero, $zero, $dob, $designation, $shiftValue, $zero, $empty, $zero);
    }
    if (!$stmt->execute()) throw new RuntimeException('Unable to save employee shift information.');
    $stmt->close();

    $stmt = er_stmt($con, 'DELETE FROM jos_app_employee_locationlog WHERE app_empid=?');
    $stmt->bind_param('i', $employeeId);
    $stmt->execute();
    $stmt->close();
    if ($terminalIds) {
        $status = 1;
        $stmt = er_stmt($con, 'INSERT INTO jos_app_employee_locationlog (app_empid,orglocation,status) VALUES (?,?,?)');
        foreach ($terminalIds as $locationId) {
            $stmt->bind_param('iii', $employeeId, $locationId, $status);
            if (!$stmt->execute()) throw new RuntimeException('Unable to save terminal locations.');
        }
        $stmt->close();
    }
}

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$isForm = $mode === 'add' || $editId > 0;
$search = trim((string)($_GET['q'] ?? ''));
$filterStatus = isset($_GET['status']) && $_GET['status'] !== '' ? (int)$_GET['status'] : -1;
$filterDepartment = max(0, (int)($_GET['department'] ?? 0));
$filterPayroll = max(0, (int)($_GET['payroll'] ?? 0));

$departments = er_options($con, 'SELECT id, department AS name FROM jos_app_department ORDER BY department');
$designations = er_options($con, 'SELECT id, designation AS name FROM jos_app_designation ORDER BY designation');
$categories = er_options($con, 'SELECT id, designation_name AS name FROM jos_app_emp_category ORDER BY designation_name');
$skillLevels = er_options($con, 'SELECT id, name FROM jos_app_emp_skilllevel ORDER BY name');
$payrollLocations = er_options($con, 'SELECT id, name FROM jos_app_payrolllocation WHERE status=1 ORDER BY name');
$branches = er_options($con, 'SELECT id, name FROM jos_app_orglocation ORDER BY name');
$subBranches = er_options($con, 'SELECT id, subbranch AS name FROM jos_app_subbranch ORDER BY subbranch');
$shifts = er_options($con, 'SELECT id, shift_type AS name, shortname FROM jos_app_empshift ORDER BY shift_type');
$bankTypes = er_options($con, 'SELECT id, name FROM jos_app_banktype ORDER BY name');

$employee = null;
$selectedShifts = [];
$selectedTerminals = [];
if ($editId > 0) {
    $stmt = er_stmt($con, 'SELECT * FROM jos_app_employee WHERE id=? LIMIT 1');
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $employee = $stmt->get_result()->fetch_assoc() ?: null;
    $stmt->close();
    if (!$employee) redirect('/masters/employee-registration.php');
    $stmt = er_stmt($con, 'SELECT shift_type FROM jos_app_employeeinfo WHERE employeeid=? LIMIT 1');
    $stmt->bind_param('i', $editId); $stmt->execute();
    $info = $stmt->get_result()->fetch_assoc(); $stmt->close();
    $selectedShifts = er_ids(explode(',', (string)($info['shift_type'] ?? '')));
    $stmt = er_stmt($con, 'SELECT orglocation FROM jos_app_employee_locationlog WHERE app_empid=? AND status=1');
    $stmt->bind_param('i', $editId); $stmt->execute(); $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) $selectedTerminals[] = (int)$row['orglocation'];
    $stmt->close();
}

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 employees.';
        if ($id === 0 && empty($acl['can_add'])) $errors[] = 'You do not have permission to add employees.';
        $name = trim((string)($_POST['name'] ?? ''));
        $empCode = trim((string)($_POST['emp_code'] ?? ''));
        $department = max(0, (int)($_POST['depat'] ?? 0));
        $designation = max(0, (int)($_POST['designation'] ?? 0));
        $payroll = max(0, (int)($_POST['payroll_location'] ?? 0));
        $branch = max(0, (int)($_POST['branch_location'] ?? 0));
        $dob = er_date((string)($_POST['dob'] ?? ''));
        $joining = er_date((string)($_POST['app_date'] ?? ''), date('Y-m-d'));
        $mobile = preg_replace('/\D+/', '', (string)($_POST['mobno'] ?? ''));
        $email = trim((string)($_POST['email'] ?? ''));
        $status = (int)($_POST['status'] ?? 1);
        $bankDetails = (int)($_POST['bank_details'] ?? 0);
        $shiftIds = er_ids($_POST['shifts'] ?? []);
        $terminalIds = er_ids($_POST['terminal_locations'] ?? []);

        if ($name === '') $errors[] = 'Employee name is required.';
        if (strlen($name) > 500) $errors[] = 'Employee name is too long.';
        if ($empCode === '') $errors[] = 'Employee code is required.';
        if (!er_valid_id($con, 'jos_app_department', $department)) $errors[] = 'Select a valid department.';
        if (!er_valid_id($con, 'jos_app_designation', $designation)) $errors[] = 'Select a valid designation.';
        if (!er_valid_id($con, 'jos_app_payrolllocation', $payroll, 'AND status=1')) $errors[] = 'Select a valid payroll location.';
        if (!er_valid_id($con, 'jos_app_orglocation', $branch)) $errors[] = 'Select a valid branch location.';
        if ($dob === '1970-01-01') $errors[] = 'Date of birth is required.';
        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Enter a valid email address.';
        if ($mobile !== '' && strlen($mobile) !== 10) $errors[] = 'Contact number must contain 10 digits.';
        if (!in_array($status, [0, 1, 2], true)) $errors[] = 'Select a valid employee status.';
        foreach ($shiftIds as $value) if (!er_valid_id($con, 'jos_app_empshift', $value)) $errors[] = 'Invalid shift selected.';
        foreach ($terminalIds as $value) if (!er_valid_id($con, 'jos_app_orglocation', $value)) $errors[] = 'Invalid terminal location selected.';
        $stmt = er_stmt($con, 'SELECT id FROM jos_app_employee WHERE emp_code=? AND id<>? LIMIT 1');
        $stmt->bind_param('si', $empCode, $id); $stmt->execute();
        if ($stmt->get_result()->fetch_assoc()) $errors[] = 'Employee code already exists.';
        $stmt->close();

        $values = [
            'orderby' => max(0, (int)($_POST['orderby'] ?? 0)), 'emp_code' => $empCode,
            'erp_empid' => trim((string)($_POST['erp_empid'] ?? '')), 'branch_code' => trim((string)($_POST['branch_code'] ?? '')),
            'name' => $name, 'empregno' => trim((string)($_POST['empregno'] ?? '')), 'address' => trim((string)($_POST['address'] ?? '')),
            'qualfication' => trim((string)($_POST['qualfication'] ?? '')), 'marital_status' => (int)($_POST['marital_status'] ?? 0),
            'gender' => (int)($_POST['gender'] ?? 0), 'depat' => $department, 'designation' => $designation,
            'category' => max(0, (int)($_POST['category'] ?? 0)), 'skilllevel' => max(0, (int)($_POST['skilllevel'] ?? 0)),
            'dob' => $dob, 'bloodgroup' => trim((string)($_POST['bloodgroup'] ?? '')), 'email' => $email, 'mobno' => $mobile,
            'status' => $status, 'entrydate' => date('Y-m-d H:i:s'), 'panno' => strtoupper(trim((string)($_POST['panno'] ?? ''))),
            'adhar_no' => preg_replace('/\D+/', '', (string)($_POST['adhar_no'] ?? '')), 'pfacc_no' => trim((string)($_POST['pfacc_no'] ?? '')),
            'basic_pay' => trim((string)($_POST['basic_pay'] ?? '0')), 'rate' => trim((string)($_POST['rate'] ?? '0')), 'app_date' => $joining,
            'bank_details' => $bankDetails, 'banktype' => max(0, (int)($_POST['banktype'] ?? 0)), 'bank_name' => trim((string)($_POST['bank_name'] ?? '')),
            'accholdername' => trim((string)($_POST['accholdername'] ?? '')), 'accmobile' => preg_replace('/\D+/', '', (string)($_POST['accmobile'] ?? '')),
            'acc_no' => trim((string)($_POST['acc_no'] ?? '')), 'branch_name' => trim((string)($_POST['branch_name'] ?? '')), 'ifsc_code' => strtoupper(trim((string)($_POST['ifsc_code'] ?? ''))),
            'subbranch' => max(0, (int)($_POST['subbranch'] ?? 0)), 'gen_salary' => (int)($_POST['gen_salary'] ?? 2),
            'pf_appli' => (int)($_POST['pf_appli'] ?? 2), 'pfjoin_date' => er_date((string)($_POST['pfjoin_date'] ?? '')),
            'user_reg' => (int)($_POST['user_reg'] ?? 0), 'payroll_location' => $payroll, 'branch_location' => $branch,
            'uan' => trim((string)($_POST['uan'] ?? '')), 'esi' => (int)($_POST['esi'] ?? 2), 'esi_no' => trim((string)($_POST['esi_no'] ?? '')),
            'ptax' => (int)($_POST['ptax'] ?? 2), 'esiclock' => (int)($_POST['esiclock'] ?? 1),
        ];
        if ($bankDetails !== 1) {
            foreach (['bank_name','accholdername','acc_no','branch_name','ifsc_code'] as $key) $values[$key] = '';
            $values['accmobile'] = 0;
        }

        if (!$errors) {
            $con->begin_transaction();
            try {
                if ($id > 0) {
                    $assignments = [];
                    $params = [];
                    foreach ($values as $column => $value) { $assignments[] = '`' . $column . '`=?'; $params[] = (string)$value; }
                    $params[] = (string)$id;
                    $stmt = er_stmt($con, 'UPDATE jos_app_employee SET ' . implode(',', $assignments) . ' WHERE id=?');
                    $types = str_repeat('s', count($params)); $stmt->bind_param($types, ...$params);
                    if (!$stmt->execute()) throw new RuntimeException('Unable to update employee.');
                    $stmt->close();
                } else {
                    $id = er_insert_employee($con, $values);
                }
                er_save_relations($con, $id, $shiftIds, $terminalIds, $designation, $dob);
                $con->commit();
                audit_log($editId > 0 ? 'employee.update' : 'employee.create', 'jos_app_employee', (string)$id, $name);
                $_SESSION['flash_employee_registration'] = $editId > 0 ? 'Employee updated successfully.' : 'Employee registered successfully.';
                redirect('/masters/employee-registration.php');
            } catch (Throwable $e) {
                $con->rollback();
                $errors[] = 'Unable to save employee. No changes were committed.';
            }
        }
        $isForm = true; $editId = $id; $employee = array_merge($employee ?: [], $values, ['id' => $id]);
        $selectedShifts = $shiftIds; $selectedTerminals = $terminalIds;
    } elseif ($action === 'status') {
        if (empty($acl['can_edit'])) $errors[] = 'You do not have permission to change employee status.';
        $id = max(0, (int)($_POST['id'] ?? 0));
        $status = (int)($_POST['status'] ?? -1);
        if ($id <= 0 || !in_array($status, [0, 1, 2], true)) $errors[] = 'Invalid status request.';
        if (!$errors) {
            $stmt = er_stmt($con, 'UPDATE jos_app_employee SET status=?, update_status=0 WHERE id=?');
            $stmt->bind_param('ii', $status, $id); $stmt->execute(); $stmt->close();
            audit_log('employee.status', 'jos_app_employee', (string)$id, (string)$status);
            $_SESSION['flash_employee_registration'] = 'Employee status updated successfully.';
            redirect('/masters/employee-registration.php');
        }
    }
}

$employees = [];
if (!$isForm) {
    $where = ['1=1']; $types = ''; $params = [];
    if ($search !== '') { $where[] = '(e.name LIKE ? OR e.emp_code LIKE ? OR e.mobno LIKE ?)'; $like = '%' . $search . '%'; $types .= 'sss'; array_push($params, $like, $like, $like); }
    if ($filterStatus >= 0 && $filterStatus <= 2) { $where[] = 'e.status=?'; $types .= 'i'; $params[] = $filterStatus; }
    if ($filterDepartment > 0) { $where[] = 'e.depat=?'; $types .= 'i'; $params[] = $filterDepartment; }
    if ($filterPayroll > 0) { $where[] = 'e.payroll_location=?'; $types .= 'i'; $params[] = $filterPayroll; }
    $sql = 'SELECT e.id,e.emp_code,e.name,e.mobno,e.email,e.status,e.app_date,e.photo,e.user_reg,e.bank_details,e.gen_salary,d.department,g.designation,p.name AS payroll_name,b.name AS branch_name,i.shift_type FROM jos_app_employee e LEFT JOIN jos_app_department d ON d.id=e.depat LEFT JOIN jos_app_designation g ON g.id=e.designation LEFT JOIN jos_app_payrolllocation p ON p.id=e.payroll_location LEFT JOIN jos_app_orglocation b ON b.id=e.branch_location LEFT JOIN jos_app_employeeinfo i ON i.employeeid=e.id WHERE ' . implode(' AND ', $where) . ' ORDER BY e.orderby=0,e.orderby,e.name LIMIT 200';
    $stmt = er_stmt($con, $sql);
    if ($types !== '') $stmt->bind_param($types, ...$params);
    $stmt->execute(); $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) $employees[] = $row;
    $stmt->close();
}

$value = static function (string $key, $default = '') use (&$employee, &$errors) {
    return $errors && isset($_POST[$key]) ? $_POST[$key] : ($employee[$key] ?? $default);
};
$input = 'mt-1 w-full rounded-xl 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';
$statusLabels = [0 => 'Inactive', 1 => 'Active', 2 => 'Left Company'];
$statusClasses = [0 => 'bg-slate-100 text-slate-600', 1 => 'bg-emerald-50 text-emerald-700', 2 => 'bg-amber-50 text-amber-700'];

console_header('Employee Registration', $pageLink);
?>
<div class="mb-6 flex flex-col gap-4 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>Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Employee Registration</span></div><h1 class="text-2xl font-bold text-slate-900">Employee Registration</h1><p class="mt-1 text-sm text-slate-500"><?= $isForm ? 'Maintain personal, employment, payroll and attendance settings.' : 'Search and manage employee records.' ?></p></div>
  <?php if (!$isForm && !empty($acl['can_add'])): ?><a href="/masters/employee-registration.php?mode=add" class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-5 py-3 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-user-plus"></i>Add Employee</a><?php endif; ?>
</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): ?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <form method="get" class="grid gap-3 border-b border-slate-100 p-5 md:grid-cols-2 xl:grid-cols-5">
    <div class="relative xl:col-span-2"><i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-xs text-slate-400"></i><input name="q" value="<?= h($search) ?>" placeholder="Name, employee code or mobile" class="w-full rounded-xl border border-slate-200 py-2.5 pl-9 pr-3 text-sm outline-none focus:border-brand-500"></div>
    <select name="status" class="rounded-xl border border-slate-200 px-3 py-2.5 text-sm"><option value="">All Statuses</option><?php foreach ($statusLabels as $key=>$label): ?><option value="<?= $key ?>" <?= $filterStatus===$key?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select>
    <select name="department" class="rounded-xl border border-slate-200 px-3 py-2.5 text-sm"><option value="0">All Departments</option><?php foreach ($departments as $row): ?><option value="<?= (int)$row['id'] ?>" <?= $filterDepartment===(int)$row['id']?'selected':'' ?>><?= h($row['name']) ?></option><?php endforeach; ?></select>
    <div class="flex gap-2"><select name="payroll" class="min-w-0 flex-1 rounded-xl border border-slate-200 px-3 py-2.5 text-sm"><option value="0">All Payroll Locations</option><?php foreach ($payrollLocations as $row): ?><option value="<?= (int)$row['id'] ?>" <?= $filterPayroll===(int)$row['id']?'selected':'' ?>><?= h($row['name']) ?></option><?php endforeach; ?></select><button class="rounded-xl bg-slate-900 px-4 text-white"><i class="fa-solid fa-filter"></i></button></div>
  </form>
  <div class="overflow-x-auto"><table class="w-full min-w-[1100px] text-left text-sm"><thead class="bg-slate-50 text-[10px] uppercase tracking-wider text-slate-400"><tr><th class="px-5 py-4">Employee</th><th class="px-5 py-4">Employment</th><th class="px-5 py-4">Contact</th><th class="px-5 py-4">Location</th><th class="px-5 py-4">Configuration</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 (!$employees): ?><tr><td colspan="7" class="px-6 py-14 text-center font-semibold text-slate-400">No employees found.</td></tr><?php endif; ?>
  <?php foreach ($employees as $row): $initials = strtoupper(substr(trim((string)$row['name']),0,2)); ?>
    <tr class="hover:bg-slate-50/70"><td class="px-5 py-4"><div class="flex items-center gap-3"><span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-xs font-bold text-brand-600"><?= h($initials) ?></span><div><div class="font-bold text-slate-800"><?= h($row['name']) ?></div><div class="text-xs text-slate-400">#<?= h($row['emp_code']) ?> · ID <?= (int)$row['id'] ?></div></div></div></td><td class="px-5 py-4"><div class="font-semibold text-slate-700"><?= h((string)($row['designation'] ?: '—')) ?></div><div class="text-xs text-slate-400"><?= h((string)($row['department'] ?: '—')) ?> · Joined <?= h($row['app_date']) ?></div></td><td class="px-5 py-4"><div class="font-medium text-slate-700"><?= h((string)($row['mobno'] ?: '—')) ?></div><div class="text-xs text-slate-400"><?= h((string)($row['email'] ?: '—')) ?></div></td><td class="px-5 py-4"><div class="font-semibold text-slate-700"><?= h((string)($row['payroll_name'] ?: '—')) ?></div><div class="text-xs text-slate-400"><?= h((string)($row['branch_name'] ?: '—')) ?></div></td><td class="px-5 py-4"><div class="flex flex-wrap gap-1"><span class="rounded-md bg-blue-50 px-2 py-1 text-[10px] font-bold text-blue-700"><?= $row['user_reg']?'Staff App':'Terminal' ?></span><span class="rounded-md bg-violet-50 px-2 py-1 text-[10px] font-bold text-violet-700"><?= $row['bank_details']?'Bank ✓':'No Bank' ?></span><span class="rounded-md bg-slate-100 px-2 py-1 text-[10px] font-bold text-slate-600"><?= h((string)($row['shift_type'] ?: 'No Shift')) ?></span></div></td><td class="px-5 py-4"><span class="rounded-full px-3 py-1 text-xs font-bold <?= h($statusClasses[(int)$row['status']] ?? $statusClasses[0]) ?>"><?= h($statusLabels[(int)$row['status']] ?? 'Unknown') ?></span></td><td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (!empty($acl['can_edit'])): ?><a href="?edit=<?= (int)$row['id'] ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-brand-50 hover:text-brand-600"><i class="fa-solid fa-pen"></i></a><form method="post"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="status"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><input type="hidden" name="status" value="<?= (int)$row['status']===1?0:1 ?>"><button title="<?= (int)$row['status']===1?'Deactivate':'Activate' ?>" class="rounded-lg border border-slate-200 px-3 py-2 text-slate-600 hover:bg-amber-50 hover:text-amber-600"><i class="fa-solid fa-power-off"></i></button></form><?php endif; ?></div></td></tr>
  <?php endforeach; ?></tbody></table></div>
</section>
<?php else: ?>
<form method="post" id="employee-form" class="space-y-5"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= (int)($employee['id'] ?? 0) ?>">
  <div class="sticky top-[72px] z-30 flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-slate-100 bg-white/95 px-5 py-3 shadow-sm backdrop-blur"><div class="font-bold text-slate-800"><?= !empty($employee['id'])?'Edit Employee #'.(int)$employee['id']:'Register New Employee' ?></div><div class="flex gap-2"><a href="/masters/employee-registration.php" class="rounded-xl border border-slate-200 px-5 py-2.5 text-sm font-bold text-slate-600">Cancel</a><button class="rounded-xl 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 Employee</button></div></div>
  <?php
  $section = static function (string $title, string $subtitle, string $icon): void { echo '<section class="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm"><div class="mb-5 flex items-center gap-3"><span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="' . h($icon) . '"></i></span><div><h2 class="font-bold text-slate-800">' . h($title) . '</h2><p class="text-xs text-slate-400">' . h($subtitle) . '</p></div></div><div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">'; };
  $endSection = static function (): void { echo '</div></section>'; };
  $select = static function (string $name, string $label, array $options, $selected, string $class, bool $required=false): void { echo '<label class="text-sm font-semibold text-slate-700">' . h($label) . '<select name="' . h($name) . '" class="' . h($class) . '"' . ($required?' required':'') . '><option value="">Select ' . h($label) . '</option>'; foreach($options as $row) echo '<option value="'.(int)$row['id'].'" '.((string)$selected===(string)$row['id']?'selected':'').'>'.h($row['name']).'</option>'; echo '</select></label>'; };
  $section('Identity & Contact','Core employee identity and personal information.','fa-solid fa-id-card'); ?>
    <label class="text-sm font-semibold text-slate-700 xl:col-span-2">Employee Name *<input name="name" required maxlength="500" value="<?= h((string)$value('name')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Employee Code *<input name="emp_code" required maxlength="255" value="<?= h((string)$value('emp_code')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Employee ID / Reg No<input name="empregno" maxlength="100" value="<?= h((string)$value('empregno')) ?>" class="<?= $input ?>"></label>
    <label class="text-sm font-semibold text-slate-700">ERP Employee ID<input name="erp_empid" value="<?= h((string)$value('erp_empid')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Contact Number<input name="mobno" inputmode="numeric" maxlength="10" value="<?= h((string)$value('mobno')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Email<input name="email" type="email" value="<?= h((string)$value('email')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Date of Birth *<input name="dob" required type="date" value="<?= h((string)$value('dob')) ?>" class="<?= $input ?>"></label>
    <label class="text-sm font-semibold text-slate-700">Gender<select name="gender" class="<?= $input ?>"><option value="0">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">Blood Group<select name="bloodgroup" class="<?= $input ?>"><option value="">Select Blood Group</option><?php foreach(['A+','A-','B+','B-','AB+','AB-','O+','O-'] as $bg): ?><option <?= (string)$value('bloodgroup')===$bg?'selected':'' ?>><?= $bg ?></option><?php endforeach; ?></select></label><label class="text-sm font-semibold text-slate-700">Marital Status<select name="marital_status" class="<?= $input ?>"><option value="0" <?= (int)$value('marital_status')===0?'selected':'' ?>>Unmarried</option><option value="1" <?= (int)$value('marital_status')===1?'selected':'' ?>>Married</option></select></label><label class="text-sm font-semibold text-slate-700">Qualification<input name="qualfication" value="<?= h((string)$value('qualfication')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700 md:col-span-2 xl:col-span-4">Address<textarea name="address" rows="2" class="<?= $input ?>"><?= h((string)$value('address')) ?></textarea></label>
  <?php $endSection(); $section('Employment','Department, designation, locations and attendance assignment.','fa-solid fa-briefcase');
  $select('depat','Department',$departments,$value('depat'),$input,true); $select('designation','Designation',$designations,$value('designation'),$input,true); $select('category','Category',$categories,$value('category'),$input); $select('skilllevel','Skill Level',$skillLevels,$value('skilllevel'),$input); $select('payroll_location','Payroll Location',$payrollLocations,$value('payroll_location'),$input,true); $select('branch_location','Branch Location',$branches,$value('branch_location'),$input,true); $select('subbranch','Sub Branch',$subBranches,$value('subbranch'),$input); ?>
    <label class="text-sm font-semibold text-slate-700">Branch Code<input name="branch_code" value="<?= h((string)$value('branch_code')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Date of Joining *<input name="app_date" required type="date" value="<?= h((string)$value('app_date',date('Y-m-d'))) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Order Number<input name="orderby" type="number" min="0" value="<?= h((string)$value('orderby',0)) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Status<select name="status" class="<?= $input ?>"><?php foreach($statusLabels as $key=>$label): ?><option value="<?= $key ?>" <?= (int)$value('status',1)===$key?'selected':'' ?>><?= h($label) ?></option><?php endforeach; ?></select></label><label class="text-sm font-semibold text-slate-700">Staff App Module<select name="user_reg" class="<?= $input ?>"><option value="0" <?= (int)$value('user_reg')===0?'selected':'' ?>>No</option><option value="1" <?= (int)$value('user_reg')===1?'selected':'' ?>>Yes</option></select></label>
    <label class="text-sm font-semibold text-slate-700 md:col-span-2">Assigned Shifts<select name="shifts[]" multiple size="5" class="<?= $input ?>"><?php foreach($shifts as $row): ?><option value="<?= (int)$row['id'] ?>" <?= in_array((int)$row['id'],$selectedShifts,true)?'selected':'' ?>><?= h($row['name']) ?><?= $row['shortname']?' ('.h($row['shortname']).')':'' ?></option><?php endforeach; ?></select><span class="mt-1 block text-xs font-medium text-slate-400">Use Ctrl/Cmd to select multiple shifts.</span></label><label class="text-sm font-semibold text-slate-700 md:col-span-2">Terminal Locations<select name="terminal_locations[]" multiple size="5" class="<?= $input ?>"><?php foreach($branches as $row): ?><option value="<?= (int)$row['id'] ?>" <?= in_array((int)$row['id'],$selectedTerminals,true)?'selected':'' ?>><?= h($row['name']) ?></option><?php endforeach; ?></select><span class="mt-1 block text-xs font-medium text-slate-400">Controls employee terminal availability.</span></label>
  <?php $endSection(); $section('Payroll & Statutory','Salary, PF, ESI and statutory identifiers.','fa-solid fa-coins'); ?>
    <label class="text-sm font-semibold text-slate-700">Actual Salary<input name="basic_pay" type="number" min="0" step="0.01" value="<?= h((string)$value('basic_pay',0)) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Rate Per Hour<input name="rate" type="number" min="0" step="0.01" value="<?= h((string)$value('rate',0)) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Generate Salary<select name="gen_salary" class="<?= $input ?>"><option value="1" <?= (int)$value('gen_salary')===1?'selected':'' ?>>Yes</option><option value="2" <?= (int)$value('gen_salary',2)===2?'selected':'' ?>>No</option></select></label><label class="text-sm font-semibold text-slate-700">PAN Number<input name="panno" maxlength="10" value="<?= h((string)$value('panno')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">Aadhaar Number<input name="adhar_no" inputmode="numeric" maxlength="12" value="<?= h((string)$value('adhar_no')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">UAN Number<input name="uan" value="<?= h((string)$value('uan')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">PF Applicable<select name="pf_appli" class="<?= $input ?>"><option value="1" <?= (int)$value('pf_appli')===1?'selected':'' ?>>Yes</option><option value="2" <?= (int)$value('pf_appli',2)===2?'selected':'' ?>>No</option></select></label><label class="text-sm font-semibold text-slate-700">PF Account Number<input name="pfacc_no" value="<?= h((string)$value('pfacc_no')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">PF Join Date<input name="pfjoin_date" type="date" value="<?= h((string)$value('pfjoin_date')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">ESI Applicable<select name="esi" class="<?= $input ?>"><option value="1" <?= (int)$value('esi')===1?'selected':'' ?>>Yes</option><option value="2" <?= (int)$value('esi',2)===2?'selected':'' ?>>No</option></select></label><label class="text-sm font-semibold text-slate-700">ESI Number<input name="esi_no" value="<?= h((string)$value('esi_no')) ?>" class="<?= $input ?>"></label><label class="text-sm font-semibold text-slate-700">P-Tax<select name="ptax" class="<?= $input ?>"><option value="1" <?= (int)$value('ptax')===1?'selected':'' ?>>Yes</option><option value="2" <?= (int)$value('ptax',2)===2?'selected':'' ?>>No</option></select></label>
  <?php $endSection(); $section('Bank Details','Optional salary bank-account information.','fa-solid fa-building-columns'); ?>
    <label class="text-sm font-semibold text-slate-700">Bank Details Available<select name="bank_details" id="bank-details-toggle" class="<?= $input ?>"><option value="0" <?= (int)$value('bank_details')===0?'selected':'' ?>>No</option><option value="1" <?= (int)$value('bank_details')===1?'selected':'' ?>>Yes</option></select></label><div class="bank-field"><?php $select('banktype','Bank Type',$bankTypes,$value('banktype'),$input); ?></div><label class="bank-field text-sm font-semibold text-slate-700">Bank Name<input name="bank_name" value="<?= h((string)$value('bank_name')) ?>" class="<?= $input ?>"></label><label class="bank-field text-sm font-semibold text-slate-700">Account Holder<input name="accholdername" value="<?= h((string)$value('accholdername')) ?>" class="<?= $input ?>"></label><label class="bank-field text-sm font-semibold text-slate-700">Account Mobile<input name="accmobile" value="<?= h((string)$value('accmobile')) ?>" class="<?= $input ?>"></label><label class="bank-field text-sm font-semibold text-slate-700">Account Number<input name="acc_no" value="<?= h((string)$value('acc_no')) ?>" class="<?= $input ?>"></label><label class="bank-field text-sm font-semibold text-slate-700">Bank Branch<input name="branch_name" value="<?= h((string)$value('branch_name')) ?>" class="<?= $input ?>"></label><label class="bank-field text-sm font-semibold text-slate-700">IFSC Code<input name="ifsc_code" value="<?= h((string)$value('ifsc_code')) ?>" class="<?= $input ?>"></label>
  <?php $endSection(); ?>
</form>
<script>(()=>{const toggle=document.getElementById('bank-details-toggle');const fields=[...document.querySelectorAll('.bank-field')];const sync=()=>fields.forEach(field=>field.classList.toggle('hidden',toggle.value!=='1'));if(toggle){toggle.addEventListener('change',sync);sync();}})();</script>
<?php endif; ?>
<?php console_footer(); ?>
