<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/console_shell.php';
require_login();
require_once __DIR__ . '/job-type-common.php';

$pageLink = 'organization/job-types.php';
$acl = require_acl('can_view', $pageLink);
$canAdd = !empty($acl['can_add']);
$canEdit = !empty($acl['can_edit']);
$canDelete = !empty($acl['can_delete']);

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

$ready = jt_is_ready($con);
$mode = (string)($_GET['mode'] ?? '');
$editId = (int)($_GET['edit'] ?? 0);
$showAdd = $mode === 'add';
$showEdit = $editId > 0;
$locations = $ready ? jt_locations($con) : [];
$record = null;
$jobType = '';
$locationId = 0;

if ($showAdd && !$canAdd) {
    $errors[] = 'You do not have permission to add Job Type.';
    $showAdd = false;
}

if ($showEdit) {
    if (!$canEdit) {
        $errors[] = 'You do not have permission to edit Job Type.';
        $showEdit = false;
    } elseif ($ready) {
        $record = jt_fetch($con, $editId);
        if (!$record) {
            jt_flash('Job Type record was not found.');
            header('Location: /organization/job-types.php');
            exit;
        }
        $jobType = jt_text($record, 'job_type');
        $locationId = jt_fetch_location_id($con, $editId);
    }
}

if ($ready && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } else {
        $action = (string)($_POST['action'] ?? '');
        $id = (int)($_POST['id'] ?? 0);

        if ($action === 'save') {
            $isEdit = $id > 0;
            if ($isEdit && !$canEdit) {
                $errors[] = 'You do not have permission to edit Job Type.';
            } elseif (!$isEdit && !$canAdd) {
                $errors[] = 'You do not have permission to add Job Type.';
            } else {
                $jobType = trim((string)($_POST['job_type'] ?? ''));
                $locationId = (int)($_POST['location_id'] ?? 0);
                if ($jobType === '') {
                    $errors[] = 'Job Type is required.';
                }
                if ($locationId <= 0 || !jt_location_exists($con, $locationId)) {
                    $errors[] = 'Location is required.';
                }
                if ($jobType !== '' && jt_duplicate($con, $jobType, $id)) {
                    $errors[] = 'Job Type already exists.';
                }
                if ($isEdit && !jt_fetch($con, $id)) {
                    $errors[] = 'Job Type record was not found.';
                }

                if (!$errors) {
                    try {
                        $con->begin_transaction();
                        if ($isEdit) {
                            jt_history($con, $id);
                        }
                        jt_save($con, $id, $jobType, $locationId);
                        $con->commit();
                        jt_flash($isEdit ? 'Job Type updated successfully.' : 'Job Type added successfully.');
                        header('Location: /organization/job-types.php');
                        exit;
                    } catch (Throwable $e) {
                        $con->rollback();
                        error_log('Job Type save failed: ' . $e->getMessage());
                        $errors[] = 'Unable to save Job Type.';
                    }
                }
            }
        } elseif ($action === 'toggle') {
            $row = jt_fetch($con, $id);
            if (!$row) {
                $errors[] = 'Job Type record was not found.';
            } elseif (!$canDelete) {
                $errors[] = 'You do not have permission to change status.';
            } else {
                try {
                    jt_history($con, $id);
                    $newStatus = jt_int($row, 'update_status') === 0 ? 1 : 0;
                    $stmt = jt_stmt($con, 'UPDATE jos_app_jobtype SET update_status=? WHERE id=?');
                    $stmt->bind_param('ii', $newStatus, $id);
                    $stmt->execute();
                    $stmt->close();
                    jt_flash($newStatus === 0 ? 'Job Type activated successfully.' : 'Job Type deactivated successfully.');
                    header('Location: /organization/job-types.php');
                    exit;
                } catch (Throwable $e) {
                    error_log('Job Type status failed: ' . $e->getMessage());
                    $errors[] = 'Unable to update Job Type status.';
                }
            }
        } elseif ($action === 'delete') {
            $row = jt_fetch($con, $id);
            if (!$row) {
                $errors[] = 'Job Type record was not found.';
            } elseif (!$canDelete) {
                $errors[] = 'You do not have permission to delete.';
            } elseif (jt_dependency_count($con, $id) > 0) {
                $errors[] = 'Job Type is used by employees and cannot be deleted.';
            } else {
                try {
                    $con->begin_transaction();
                    if (jt_table_exists($con, 'jos_app_jobtype_edit_log')) {
                        $stmt = jt_stmt($con, 'DELETE FROM jos_app_jobtype_edit_log WHERE jobid=?');
                        $stmt->bind_param('i', $id);
                        $stmt->execute();
                        $stmt->close();
                    }
                    $stmt = jt_stmt($con, 'DELETE FROM jos_app_jobtype_locationlog WHERE jobid=?');
                    $stmt->bind_param('i', $id);
                    $stmt->execute();
                    $stmt->close();
                    $stmt = jt_stmt($con, 'DELETE FROM jos_app_jobtype WHERE id=?');
                    $stmt->bind_param('i', $id);
                    $stmt->execute();
                    $stmt->close();
                    $con->commit();
                    jt_flash('Job Type deleted successfully.');
                    header('Location: /organization/job-types.php');
                    exit;
                } catch (Throwable $e) {
                    $con->rollback();
                    error_log('Job Type delete failed: ' . $e->getMessage());
                    $errors[] = 'Unable to delete Job Type.';
                }
            }
        }
    }
}

if ($ready && $_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'save') {
    $showAdd = (int)($_POST['id'] ?? 0) <= 0;
    $showEdit = (int)($_POST['id'] ?? 0) > 0;
    $editId = (int)($_POST['id'] ?? 0);
}

$query = trim((string)($_GET['q'] ?? ''));
$statusFilter = (string)($_GET['status'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 15;
$offset = ($page - 1) * $perPage;
$rows = [];
$totalRows = 0;

if ($ready && !$showAdd && !$showEdit) {
    $where = [];
    $types = '';
    $params = [];
    if ($query !== '') {
        $where[] = 'job_type LIKE ?';
        $types .= 's';
        $params[] = '%' . $query . '%';
    }
    if ($statusFilter !== '' && in_array($statusFilter, ['0', '1'], true)) {
        $where[] = 'update_status=?';
        $types .= 'i';
        $params[] = (int)$statusFilter;
    }
    $whereSql = $where ? (' WHERE ' . implode(' AND ', $where)) : '';

    $stmt = jt_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_jobtype' . $whereSql);
    if ($types !== '') {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $totalRows = (int)($stmt->get_result()->fetch_assoc()['total'] ?? 0);
    $stmt->close();

    $sql = 'SELECT id, job_type, update_status FROM jos_app_jobtype' . $whereSql . ' ORDER BY id DESC LIMIT ? OFFSET ?';
    $stmt = jt_stmt($con, $sql);
    $listTypes = $types . 'ii';
    $listParams = array_merge($params, [$perPage, $offset]);
    $stmt->bind_param($listTypes, ...$listParams);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $stmt->close();
}

console_header($showEdit ? 'Edit Job Type' : 'Add Job Type', $pageLink);
jt_breadcrumb('Add Job Type');
jt_alerts($flash, $errors);
if (!$ready): ?>
    <div class="rounded-2xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-bold text-red-700">Required old Job Type tables are missing.</div>
<?php elseif ($showAdd || $showEdit): ?>
<form method="post" class="space-y-6">
    <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
    <input type="hidden" name="action" value="save">
    <input type="hidden" name="id" value="<?= h((string)($showEdit ? $editId : 0)) ?>">
    <section class="bg-white border border-slate-100 rounded-2xl shadow-sm overflow-hidden">
        <div class="px-6 py-5 flex items-center justify-between border-b border-slate-100">
            <div class="flex items-center gap-4">
                <div class="h-12 w-12 rounded-xl bg-brand-50 text-brand-600 flex items-center justify-center"><i class="fa-solid fa-briefcase"></i></div>
                <div>
                    <h2 class="text-lg font-bold text-slate-900"><?= $showEdit ? 'Edit Job Type' : 'New Job Type' ?></h2>
                    <p class="mt-1 text-sm font-medium text-slate-400">Fields marked with * are required.</p>
                </div>
            </div>
            <a href="/organization/job-types.php" class="rounded-lg border border-slate-200 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="p-6 grid gap-6 md:grid-cols-2">
            <label class="block">
                <span class="mb-2 block text-sm font-bold text-slate-700">Job Type *</span>
                <input type="text" name="job_type" value="<?= h($jobType) ?>" placeholder="Job Type" class="h-12 w-full rounded-xl border border-slate-200 px-4 text-sm font-semibold outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100">
            </label>
            <label class="block">
                <span class="mb-2 block text-sm font-bold text-slate-700">Location *</span>
                <select name="location_id" class="h-12 w-full rounded-xl border border-slate-200 px-4 text-sm font-semibold outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100">
                    <option value="">Select Location</option>
                    <?php foreach ($locations as $location): ?>
                        <option value="<?= h((string)$location['id']) ?>" <?= (int)$location['id'] === $locationId ? 'selected' : '' ?>><?= h((string)$location['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
        </div>
    </section>
    <div class="flex justify-center gap-3">
        <button type="submit" class="inline-flex h-12 items-center justify-center gap-2 rounded-xl bg-brand-600 px-10 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-floppy-disk"></i>Submit</button>
        <a href="/organization/job-types.php" class="inline-flex h-12 items-center justify-center rounded-xl border border-slate-200 px-8 text-sm font-bold text-slate-600 hover:bg-slate-50">Cancel</a>
    </div>
</form>
<?php else: ?>
<section class="bg-white border border-slate-100 rounded-2xl shadow-sm overflow-hidden">
    <div class="px-6 py-5 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h2 class="text-lg font-bold text-slate-900">Job Type List</h2>
            <p class="mt-1 text-sm font-medium text-slate-400">Job types are ordered by latest record.</p>
        </div>
        <?php if ($canAdd): ?>
            <a href="/organization/job-types.php?mode=add" class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-5 py-3 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus"></i>Add</a>
        <?php endif; ?>
    </div>
    <form method="get" class="border-t border-slate-100 px-6 py-5 flex flex-col gap-3 md:flex-row md:items-center">
        <input type="text" name="q" value="<?= h($query) ?>" placeholder="Search job type" class="h-11 w-full md:w-72 rounded-xl border border-slate-200 px-4 text-sm font-medium outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100">
        <select name="status" class="h-11 w-full md:w-64 rounded-xl border border-slate-200 px-4 text-sm font-medium outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100">
            <option value="">All Status</option>
            <option value="0" <?= $statusFilter === '0' ? 'selected' : '' ?>>Active</option>
            <option value="1" <?= $statusFilter === '1' ? 'selected' : '' ?>>Inactive</option>
        </select>
        <button type="submit" class="h-11 rounded-xl bg-slate-950 px-5 text-sm font-bold text-white hover:bg-slate-800"><i class="fa-solid fa-filter mr-2"></i>Filter</button>
        <a href="/organization/job-types.php" class="inline-flex h-11 items-center justify-center rounded-xl border border-slate-200 px-5 text-sm font-bold text-slate-600 hover:bg-slate-50">Clear</a>
    </form>
    <div class="overflow-x-auto">
        <table class="min-w-full text-left">
            <thead class="bg-slate-50">
                <tr class="text-[11px] font-bold uppercase tracking-wide text-slate-500">
                    <th class="px-6 py-4">Sr No</th>
                    <th class="px-6 py-4">Job Type</th>
                    <th class="px-6 py-4">Status</th>
                    <th class="px-6 py-4 text-right">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100 text-sm text-slate-700">
            <?php if (!$rows): ?>
                <tr><td colspan="4" class="px-6 py-16 text-center font-bold text-slate-400">No job types found.</td></tr>
            <?php else: foreach ($rows as $index => $row):
                $id = (int)$row['id'];
                $status = jt_int($row, 'update_status');
                $active = $status === 0;
            ?>
                <tr>
                    <td class="px-6 py-5 font-semibold text-slate-500"><?= h((string)($offset + $index + 1)) ?></td>
                    <td class="px-6 py-5 font-bold text-slate-800"><?= h(jt_text($row, 'job_type')) ?></td>
                    <td class="px-6 py-5"><span class="rounded-full px-3 py-1 text-xs font-bold <?= $active ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500' ?>"><?= h(jt_status_label($status)) ?></span></td>
                    <td class="px-6 py-5">
                        <div class="flex justify-end gap-2">
                            <?php if ($canEdit): ?>
                                <a href="/organization/job-types.php?edit=<?= h((string)$id) ?>" class="inline-flex h-10 w-10 items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:bg-slate-50" title="Edit"><i class="fa-solid fa-pen-to-square"></i></a>
                            <?php endif; ?>
                            <?php if ($canDelete): ?>
                                <form method="post" onsubmit="return confirm('Are you sure?');">
                                    <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                                    <input type="hidden" name="action" value="toggle">
                                    <input type="hidden" name="id" value="<?= h((string)$id) ?>">
                                    <button type="submit" class="inline-flex h-10 items-center justify-center rounded-lg px-4 text-xs font-bold text-white <?= $active ? 'bg-emerald-600 hover:bg-emerald-700' : 'bg-slate-600 hover:bg-slate-700' ?>"><?= $active ? 'Deactivate' : 'Activate' ?></button>
                                </form>
                                <form method="post" onsubmit="return confirm('Delete this Job Type?');">
                                    <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= h((string)$id) ?>">
                                    <button type="submit" class="inline-flex h-10 w-10 items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:bg-red-50 hover:text-red-600" title="Delete"><i class="fa-solid fa-trash-can"></i></button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($totalRows > $perPage):
        $lastPage = (int)ceil($totalRows / $perPage);
    ?>
    <div class="border-t border-slate-100 px-6 py-4 flex items-center justify-between text-sm font-semibold text-slate-500">
        <span>Page <?= h((string)$page) ?> of <?= h((string)$lastPage) ?></span>
        <div class="flex gap-2">
            <?php if ($page > 1): ?><a class="rounded-lg border border-slate-200 px-3 py-2" href="?q=<?= h(urlencode($query)) ?>&status=<?= h(urlencode($statusFilter)) ?>&page=<?= h((string)($page - 1)) ?>">Previous</a><?php endif; ?>
            <?php if ($page < $lastPage): ?><a class="rounded-lg border border-slate-200 px-3 py-2" href="?q=<?= h(urlencode($query)) ?>&status=<?= h(urlencode($statusFilter)) ?>&page=<?= h((string)($page + 1)) ?>">Next</a><?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</section>
<?php endif;
console_footer();
