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

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

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

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

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? 0));
$historyId = max(0, (int)($_GET['history'] ?? 0));
$hasLogTable = false;
$logTableCheck = $con->query("SHOW TABLES LIKE 'jos_app_subbranch_editlog'");
if ($logTableCheck && $logTableCheck->num_rows > 0) {
    $hasLogTable = 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));
        $subBranch = trim((string)($_POST['subbranch'] ?? ''));

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

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

                if ($hasLogTable) {
                    $userId = (int)(current_user()['id'] ?? 0);
                    $stmt = $con->prepare('INSERT INTO jos_app_subbranch_editlog (subid, date, subbranch, modify_by) VALUES (?, NOW(), ?, ?)');
                    if ($stmt) {
                        $stmt->bind_param('isi', $subBranchId, $subBranch, $userId);
                        $stmt->execute();
                        $stmt->close();
                    }
                }

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

        $isFormView = true;
        $editId = $id;
    }
}

if ($editId > 0) {
    $stmt = $con->prepare('SELECT id, subbranch FROM jos_app_subbranch 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_sub_branches'] = 'Sub branch record was not found.';
        redirect('/masters/sub-branches.php');
    }
}

if ($historyId > 0) {
    $stmt = $con->prepare('SELECT id, subbranch FROM jos_app_subbranch 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_sub_branches'] = 'Sub branch record was not found.';
        redirect('/masters/sub-branches.php');
    }

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

$subBranches = [];
if (!$isFormView && !$isHistoryView) {
    if ($search !== '') {
        $like = '%' . $search . '%';
        $sql = $hasLogTable
            ? 'SELECT s.id, s.subbranch, (SELECT COUNT(*) FROM jos_app_subbranch_editlog l WHERE l.subid=s.id) AS log_count FROM jos_app_subbranch s WHERE s.subbranch LIKE ? ORDER BY s.id ASC'
            : 'SELECT id, subbranch, 0 AS log_count FROM jos_app_subbranch WHERE subbranch 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()) {
            $subBranches[] = $row;
        }
        $stmt->close();
    } else {
        $sql = $hasLogTable
            ? 'SELECT s.id, s.subbranch, (SELECT COUNT(*) FROM jos_app_subbranch_editlog l WHERE l.subid=s.id) AS log_count FROM jos_app_subbranch s ORDER BY s.id ASC'
            : 'SELECT id, subbranch, 0 AS log_count FROM jos_app_subbranch ORDER BY id ASC';
        $result = $con->query($sql);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $subBranches[] = $row;
            }
            $result->free();
        }
    }
}

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

console_header('Sub Branches', $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">Sub Branches</span>
        </div>
        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Sub Branch Master</h1>
        <p class="text-sm text-slate-500 mt-1">Manage sub branch 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-code-branch"></i></span>
        <div>
            <div class="text-[11px] font-bold text-slate-400 uppercase tracking-widest"><?= $isFormView ? 'Form View' : ($isHistoryView ? 'History View' : 'Total Sub Branches') ?></div>
            <div class="text-lg font-bold text-slate-900 leading-tight"><?= $isFormView ? ($formId ? 'Edit' : 'Add') : ($isHistoryView ? 'Log' : count($subBranches)) ?></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-code-branch text-sm"></i></span>
                    Sub Branch List
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 lg:ml-11">Source table: <span class="font-semibold">jos_app_subbranch</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 sub branch" 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/sub-branches.php">Clear</a><?php endif; ?>
                </form>
                <?php if (!empty($acl['can_add'])): ?>
                    <a href="/masters/sub-branches.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">Sub Branch</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 (!$subBranches): ?>
                        <tr><td colspan="3" class="px-6 py-10 text-center text-slate-400 font-semibold">No sub branches found.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($subBranches as $index => $subBranch): ?>
                        <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($subBranch['subbranch']) ?></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/sub-branches.php?edit=<?= (int)$subBranch['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($subBranch['subbranch']) ?>"><i class="fa-regular fa-pen-to-square text-base"></i></a>
                                    <?php endif; ?>
                                    <?php if ((int)($subBranch['log_count'] ?? 0) >= 1): ?>
                                        <a href="/masters/sub-branches.php?history=<?= (int)$subBranch['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($subBranch['subbranch']) ?>"><i class="fa-regular fa-eye text-base"></i></a>
                                    <?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>
                    Sub Branch 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['subbranch'] ?? '') ?></span></p>
            </div>
            <a href="/masters/sub-branches.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-[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">Sub Branch</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">Modified By</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (!$historyRows): ?>
                        <tr><td colspan="4" class="px-6 py-10 text-center text-slate-400 font-semibold">No sub branch 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['subbranch']) ?></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['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-code-branch text-sm"></i></span>
                    <?= $formId ? 'Edit Sub Branch' : 'Add Sub Branch' ?>
                </h2>
                <p class="text-[12px] font-medium text-slate-400 mt-1 sm:ml-11">Sub branch is required.</p>
            </div>
            <a href="/masters/sub-branches.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' ?> sub branches.</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="subbranch" class="block text-[12px] font-bold text-slate-700 mb-2 uppercase tracking-wider">Sub Branch <span class="text-amber-500">*</span></label>
                    <input id="subbranch" name="subbranch" type="text" value="<?= h($formSubBranch) ?>" required maxlength="255" placeholder="Sub Branch" 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/sub-branches.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(); ?>
