<?php
declare(strict_types=1);

ini_set('display_errors', '0');

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

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

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

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

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

function document_type_execute(mysqli_stmt $stmt): void
{
    if (!$stmt->execute()) {
        $stmt->close();
        throw new RuntimeException('Unable to complete database operation.');
    }
}

function document_type_clean_name(string $value): string
{
    $value = trim($value);
    $normalized = preg_replace('/\s+/u', ' ', $value);
    return is_string($normalized) ? $normalized : $value;
}

if (mb_strlen($search) > 100) {
    $errors[] = 'Search must be 100 characters or fewer.';
    $search = '';
}

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));
        $name = document_type_clean_name((string)($_POST['documenttype'] ?? ''));

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

        if (!$errors && $id > 0) {
            try {
                $stmt = document_type_prepare($con, 'SELECT id FROM jos_payroll_documenttype WHERE id=? LIMIT 1');
                $stmt->bind_param('i', $id);
                document_type_execute($stmt);
                $existing = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                if (!$existing) {
                    $errors[] = 'Document Type record was not found.';
                }
            } catch (Throwable $e) {
                $errors[] = 'Unable to verify Document Type. Please try again.';
            }
        }

        if (!$errors) {
            try {
                $stmt = document_type_prepare($con, 'SELECT id FROM jos_payroll_documenttype WHERE documenttype=? AND id<>? LIMIT 1');
                $stmt->bind_param('si', $name, $id);
                document_type_execute($stmt);
                $duplicate = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                if ($duplicate) {
                    $errors[] = 'A document type with this name already exists.';
                }
            } catch (Throwable $e) {
                $errors[] = 'Unable to validate Document Type. Please try again.';
            }
        }

        if (!$errors) {
            try {
                if ($id > 0) {
                    $stmt = document_type_prepare($con, 'UPDATE jos_payroll_documenttype SET documenttype=? WHERE id=?');
                    $stmt->bind_param('si', $name, $id);
                    document_type_execute($stmt);
                    $stmt->close();
                    $_SESSION['flash_document_types'] = 'Document Type updated successfully.';
                } else {
                    $stmt = document_type_prepare($con, 'INSERT INTO jos_payroll_documenttype (documenttype) VALUES (?)');
                    $stmt->bind_param('s', $name);
                    document_type_execute($stmt);
                    $stmt->close();
                    $_SESSION['flash_document_types'] = 'Document Type saved successfully.';
                }
                redirect('/masters/document-types.php');
            } catch (Throwable $e) {
                $errors[] = 'Unable to save Document Type. Please try again.';
            }
        }

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

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

        if (!$errors) {
            try {
                $stmt = document_type_prepare($con, 'DELETE FROM jos_payroll_documenttype WHERE id=?');
                $stmt->bind_param('i', $id);
                document_type_execute($stmt);
                $deleted = $stmt->affected_rows;
                $stmt->close();

                $_SESSION['flash_document_types'] = $deleted > 0
                    ? 'Document Type deleted successfully.'
                    : 'Document Type record was not found.';
                redirect('/masters/document-types.php');
            } catch (Throwable $e) {
                $errors[] = 'Unable to delete Document Type. It may be in use by another record.';
            }
        }
    } else {
        $errors[] = 'Invalid request.';
    }
}

if ($editId > 0) {
    try {
        $stmt = document_type_prepare($con, 'SELECT id, documenttype FROM jos_payroll_documenttype WHERE id=? LIMIT 1');
        $stmt->bind_param('i', $editId);
        document_type_execute($stmt);
        $editItem = $stmt->get_result()->fetch_assoc() ?: null;
        $stmt->close();
    } catch (Throwable $e) {
        $errors[] = 'Unable to load Document Type. Please try again.';
    }

    if (!$editItem && !$errors) {
        $_SESSION['flash_document_types'] = 'Document Type record was not found.';
        redirect('/masters/document-types.php');
    }
}

$documentTypes = [];
if (!$isFormView) {
    try {
        if ($search !== '') {
            $like = '%' . $search . '%';
            $stmt = document_type_prepare($con, 'SELECT id, documenttype FROM jos_payroll_documenttype WHERE documenttype LIKE ? ORDER BY id ASC');
            $stmt->bind_param('s', $like);
        } else {
            $stmt = document_type_prepare($con, 'SELECT id, documenttype FROM jos_payroll_documenttype ORDER BY id ASC');
        }
        document_type_execute($stmt);
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $documentTypes[] = $row;
        }
        $stmt->close();
    } catch (Throwable $e) {
        $errors[] = 'Unable to load Document Types. Please try again.';
    }
}

$isEditing = $editId > 0;
$formId = $isEditing ? $editId : 0;
$formName = $errors && ($_POST['action'] ?? '') === 'save'
    ? document_type_clean_name((string)($_POST['documenttype'] ?? ''))
    : (string)($editItem['documenttype'] ?? '');

console_header('Document Types', $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">Document Types</span>
        </div>
        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Document Type Master</h1>
        <p class="text-sm text-slate-500 mt-1">Manage employee document names used by payroll records.</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-file-lines"></i></span>
        <div>
            <div class="text-[11px] font-bold text-slate-400 uppercase tracking-widest"><?= $isFormView ? 'Form View' : 'Total Document Types' ?></div>
            <div class="text-lg font-bold text-slate-900 leading-tight"><?= $isFormView ? ($isEditing ? 'Edit' : 'Add') : h((string)count($documentTypes)) ?></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-file-lines text-sm"></i></span>
                    Document Type List
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 lg:ml-11">Employee document names available for payroll records.</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) ?>" maxlength="100" placeholder="Search document type" 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/document-types.php">Clear</a><?php endif; ?>
                </form>
                <?php if (!empty($acl['can_add'])): ?>
                    <a href="/masters/document-types.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-bold text-slate-400 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">Document Type</th><th class="border-b border-slate-100 px-6 py-4 text-right w-48">Actions</th></tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (!$documentTypes): ?><tr><td colspan="3" class="px-6 py-10 text-center text-slate-400 font-semibold">No document types found.</td></tr><?php endif; ?>
                    <?php foreach ($documentTypes as $index => $documentType): ?>
                        <tr class="hover:bg-slate-50/80 transition-colors">
                            <td class="px-6 py-5 font-semibold text-slate-500"><?= h((string)($index + 1)) ?></td>
                            <td class="px-6 py-5"><span class="font-semibold text-slate-800"><?= h($documentType['documenttype']) ?></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/document-types.php?edit=<?= h((string)(int)$documentType['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($documentType['documenttype']) ?>"><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 Document Type permanently?');">
                                            <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= h((string)(int)$documentType['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($documentType['documenttype']) ?>"><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-file-lines text-sm"></i></span><?= $isEditing ? 'Edit Document Type' : 'Add Document Type' ?></h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 sm:ml-11">Document Name is required.</p>
            </div>
            <a href="/masters/document-types.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 (($isEditing && empty($acl['can_edit'])) || (!$isEditing && 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 <?= $isEditing ? 'edit' : 'add' ?> document types.</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="<?= h((string)$formId) ?>">
                <div class="max-w-5xl">
                    <label for="documenttype" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Document Name <span class="text-amber-500">*</span></label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none"><i class="fa-solid fa-file-lines text-slate-400 text-sm"></i></div>
                        <input id="documenttype" name="documenttype" type="text" value="<?= h($formName) ?>" required maxlength="255" placeholder="Document Name" class="block w-full rounded-xl border border-slate-200 bg-white py-3.5 pl-11 pr-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>
                <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/document-types.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(); ?>
