<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/employee_management.php';

require_permission($conn, 'employees');

$positionEditId = filter_input(INPUT_GET, 'position_id', FILTER_VALIDATE_INT);
if ($positionEditId) {
    redirect(employee_management_page_url('positions.php', array('position_id' => $positionEditId)));
}

$oldInput = pull_old_input();
$employeeEditId = filter_input(INPUT_GET, 'employee_id', FILTER_VALIDATE_INT) ?: (int) old_value($oldInput, 'employee_id', '0');
$filterPositionId = filter_input(INPUT_GET, 'filter_position_id', FILTER_VALIDATE_INT) ?: (int) old_value($oldInput, 'filter_position_id', '0');
$showEmployeeFormFlag = filter_input(INPUT_GET, 'show_form', FILTER_VALIDATE_INT);

$branchNames = order_branch_options($conn);

$positions = array();
$positionsResult = $conn->query("
    SELECT position_id, position_name, role_key, branch_scope, permissions, is_active
    FROM positions
    ORDER BY is_active DESC, position_name ASC
");

if ($positionsResult instanceof mysqli_result) {
    while ($row = $positionsResult->fetch_assoc()) {
        $positions[] = $row;
    }
}

$selectedFilterPositionId = 0;
foreach ($positions as $position) {
    if ((int) ($position['position_id'] ?? 0) === (int) $filterPositionId) {
        $selectedFilterPositionId = (int) $filterPositionId;
        break;
    }
}

$editingEmployee = null;
$editingEmployeeBranches = array();
if ($employeeEditId) {
    $stmt = db_prepare($conn, "
        SELECT employee_id, name, phone, username, position_id, branch_scope, default_start_page, is_active
        FROM employees
        WHERE employee_id = ?
        LIMIT 1
    ");
    $stmt->bind_param('i', $employeeEditId);
    $stmt->execute();
    $editingEmployee = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($editingEmployee) {
        $branchStmt = db_prepare($conn, "
            SELECT branch_name
            FROM employee_branch_access
            WHERE employee_id = ?
        ");
        $branchStmt->bind_param('i', $employeeEditId);
        $branchStmt->execute();
        $employeeBranchResult = $branchStmt->get_result();
        while ($row = $employeeBranchResult->fetch_assoc()) {
            $editingEmployeeBranches[] = (string) $row['branch_name'];
        }
        $branchStmt->close();
    }
}

$employees = array();
$employeeTypes = '';
$employeeParams = array();
$employeeWhere = array();
if ($selectedFilterPositionId > 0) {
    $employeeWhere[] = 'e.position_id = ?';
    $employeeTypes .= 'i';
    $employeeParams[] = $selectedFilterPositionId;
}
$employeeWhereSql = empty($employeeWhere) ? '' : 'WHERE ' . implode(' AND ', $employeeWhere);
$employeeSql = "
    SELECT
        e.employee_id,
        e.name,
        e.phone,
        e.username,
        e.branch_scope,
        e.default_start_page,
        e.is_active,
        e.last_login_at,
        p.position_name,
        p.role_key,
        GROUP_CONCAT(eba.branch_name ORDER BY eba.branch_name SEPARATOR ', ') AS branch_names
    FROM employees e
    LEFT JOIN positions p ON p.position_id = e.position_id
    LEFT JOIN employee_branch_access eba ON eba.employee_id = e.employee_id
    {$employeeWhereSql}
    GROUP BY
        e.employee_id,
        e.name,
        e.phone,
        e.username,
        e.branch_scope,
        e.default_start_page,
        e.is_active,
        e.last_login_at,
        p.position_name,
        p.role_key
    ORDER BY e.is_active DESC, e.name ASC
";

if ($employeeTypes === '') {
    $employeesResult = $conn->query($employeeSql);
    if ($employeesResult instanceof mysqli_result) {
        while ($row = $employeesResult->fetch_assoc()) {
            $employees[] = $row;
        }
    }
} else {
    $employeesStmt = db_prepare($conn, $employeeSql);
    $employeesStmt->bind_param($employeeTypes, ...$employeeParams);
    $employeesStmt->execute();
    $employeesResult = $employeesStmt->get_result();
    while ($row = $employeesResult->fetch_assoc()) {
        $employees[] = $row;
    }
    $employeesStmt->close();
}

$employeeName = old_value($oldInput, 'name', (string) ($editingEmployee['name'] ?? ''));
$employeePhone = old_value($oldInput, 'phone', (string) ($editingEmployee['phone'] ?? ''));
$employeeUsername = old_value($oldInput, 'username', (string) ($editingEmployee['username'] ?? ''));
$employeePositionId = old_value($oldInput, 'position_id', (string) ($editingEmployee['position_id'] ?? ''));
$employeeScope = old_value($oldInput, 'branch_scope', (string) ($editingEmployee['branch_scope'] ?? 'assigned'));
$employeeDefaultStartPage = old_value($oldInput, 'default_start_page', (string) ($editingEmployee['default_start_page'] ?? ''));
$employeeActive = old_value($oldInput, 'is_active', (string) ($editingEmployee['is_active'] ?? '1')) !== '0';
$selectedEmployeeBranches = old_array($oldInput, 'branch_names') ?: $editingEmployeeBranches;
$showEmployeeForm = $editingEmployee !== null || !empty($oldInput) || (int) $showEmployeeFormFlag === 1;
$employeeFormPath = employee_management_page_url('employees.php', array_filter(array(
    'show_form' => 1,
    'employee_id' => $editingEmployee ? (int) ($editingEmployee['employee_id'] ?? 0) : null,
    'filter_position_id' => $selectedFilterPositionId > 0 ? $selectedFilterPositionId : null,
)));
$pageTitle = ui_text('พนักงาน', 'Employees');
$pageDescription = ui_text(
    'จัดการบัญชีพนักงาน สาขาที่รับผิดชอบ และสิทธิ์เข้าสู่ระบบ แยกจากการตั้งค่าตำแหน่งงาน',
    'Manage staff accounts, assigned branches and login access separately from job position settings.'
);
$manageSystemLabel = ui_text('จัดการระบบ', 'Manage System');
$managePositionsLabel = ui_text('จัดการตำแหน่ง', 'Manage positions');
$employeeFiltersLabel = ui_text('ตัวกรองพนักงาน', 'Employee filters');
$employeeFiltersHelperLabel = ui_text('เริ่มจากดูรายการพนักงาน แล้วค่อยกรองตามตำแหน่งหรือเปิดฟอร์มเมื่อต้องการ', 'Open with employee list first, then filter by position or open the employee form when needed.');
$hideFormLabel = ui_text('ซ่อนฟอร์ม', 'Hide form');
$addEmployeeLabel = ui_text('เพิ่มพนักงาน', 'Add employee');
$formToggleLabel = $showEmployeeForm ? $hideFormLabel : $addEmployeeLabel;
$positionLabel = ui_text('ตำแหน่ง', 'Position');
$allPositionsLabel = ui_text('ทุกตำแหน่ง', 'All positions');
$filterLabel = ui_text('กรอง', 'Filter');
$resetLabel = ui_text('รีเซ็ต', 'Reset');
$employeeAccountsLabel = ui_text('บัญชีพนักงาน', 'Employee accounts');
$employeeRecordsLabel = ui_text('รายการพนักงาน', 'employee record(s)');
$employeeFilterEmptyLabel = ui_text('ไม่พบพนักงานตามตัวกรองนี้', 'No employee found for this filter.');
$nameLabel = ui_text('ชื่อ', 'Name');
$usernameLabel = ui_text('ชื่อผู้ใช้', 'Username');
$startPageLabel = ui_text('หน้าเริ่มต้น', 'Start page');
$branchScopeLabel = ui_text('ขอบเขตสาขา', 'Branch scope');
$branchesLabel = ui_text('สาขา', 'Branches');
$statusLabel = ui_text('สถานะ', 'Status');
$actionLabel = ui_text('การทำรายการ', 'Action');
$allOrNoneAssignedLabel = ui_text('ทุกสาขา / ยังไม่ได้กำหนด', 'All / none assigned');
$editLabel = ui_text('แก้ไข', 'Edit');
$editEmployeeLabel = ui_text('แก้ไขพนักงาน', 'Edit employee');
$employeeFormTitle = $editingEmployee ? $editEmployeeLabel : $addEmployeeLabel;
$employeeFormHelperLabel = ui_text('ขอบเขตสาขาที่กำหนดจะจำกัดการจอง คิวงาน และรายงานให้เห็นเฉพาะสาขาที่เลือก', 'Assigned branch scope limits bookings, queue and reports to selected branches.');
$newEmployeeLabel = ui_text('เพิ่มพนักงานใหม่', 'New employee');
$employeeNameLabel = ui_text('ชื่อพนักงาน', 'Employee name');
$phoneLabel = ui_text('เบอร์โทร', 'Phone');
$passwordLabel = ui_text('รหัสผ่าน', 'Password');
$selectPositionLabel = ui_text('เลือกตำแหน่ง', 'Select position');
$defaultStartPageLabel = ui_text('หน้าเริ่มต้น', 'Default start page');
$activeAccountLabel = ui_text('บัญชีเปิดใช้งาน', 'Active account');
$saveEmployeeLabel = $editingEmployee ? ui_text('บันทึกพนักงาน', 'Save employee') : $addEmployeeLabel;

render_page_start($pageTitle, 'employees', array('translation_buffer' => false));
?>

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="manage_system.php"><?= e($manageSystemLabel) ?></a>
        <a class="button button-secondary" href="positions.php"><?= e($managePositionsLabel) ?></a>
    </div>
</section>

<?= render_employee_management_tabs('employees') ?>

<section class="form-card">
    <div class="section-head">
        <div>
            <h2 class="section-title"><?= e($employeeFiltersLabel) ?></h2>
            <p class="helper"><?= e($employeeFiltersHelperLabel) ?></p>
        </div>
        <button
            class="button button-accent"
            type="button"
            data-edit-toggle
            aria-expanded="<?= $showEmployeeForm ? 'true' : 'false' ?>"
            aria-controls="employee-form-panel"
            data-closed-label="<?= e($addEmployeeLabel) ?>"
            data-open-label="<?= e($hideFormLabel) ?>"
        ><?= e($formToggleLabel) ?></button>
    </div>

    <form method="GET">
        <div class="form-grid">
            <div class="field">
                <label for="filter_position_id"><?= e($positionLabel) ?></label>
                <select id="filter_position_id" name="filter_position_id">
                    <option value=""><?= e($allPositionsLabel) ?></option>
                    <?php foreach ($positions as $position): ?>
                        <option value="<?= (int) $position['position_id'] ?>" <?= $selectedFilterPositionId === (int) ($position['position_id'] ?? 0) ? 'selected' : '' ?>>
                            <?= e((string) $position['position_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="actions service-management-filter-actions">
            <button class="button button-secondary" type="submit"><?= e($filterLabel) ?></button>
            <a class="button button-ghost" href="employees.php"><?= e($resetLabel) ?></a>
        </div>
    </form>
</section>

<section class="table-card" style="margin-top: 18px;">
    <div class="section-head" style="padding: 18px 18px 0;">
        <div>
            <h2 class="section-title"><?= e($employeeAccountsLabel) ?></h2>
            <p class="helper"><?= count($employees) ?> <?= e($employeeRecordsLabel) ?></p>
        </div>
    </div>

    <table style="min-width: 780px;">
        <thead>
        <tr>
            <th><?= e($nameLabel) ?></th>
            <th><?= e($usernameLabel) ?></th>
            <th><?= e($positionLabel) ?></th>
            <th><?= e($startPageLabel) ?></th>
            <th><?= e($branchScopeLabel) ?></th>
            <th><?= e($branchesLabel) ?></th>
            <th><?= e($statusLabel) ?></th>
            <th><?= e($actionLabel) ?></th>
        </tr>
        </thead>
        <tbody>
        <?php if (empty($employees)): ?>
            <tr>
                <td colspan="8">
                    <div class="empty-state" style="margin: 0;"><?= e($employeeFilterEmptyLabel) ?></div>
                </td>
            </tr>
        <?php endif; ?>
        <?php foreach ($employees as $employee): ?>
            <tr>
                <td>
                    <div class="stack">
                        <strong><?= e((string) $employee['name']) ?></strong>
                        <span class="muted"><?= e((string) ($employee['phone'] ?? '')) ?></span>
                    </div>
                </td>
                <td><?= e((string) ($employee['username'] ?? '-')) ?></td>
                <td><?= e((string) ($employee['position_name'] ?? '-')) ?></td>
                <td><?= e(translate_text(auth_default_start_page_label((string) ($employee['default_start_page'] ?? '')))) ?></td>
                <td><?= e(employee_branch_scope_label((string) $employee['branch_scope'])) ?></td>
                <td><?= e((string) ($employee['branch_names'] ?: $allOrNoneAssignedLabel)) ?></td>
                <td><span class="<?= (int) $employee['is_active'] === 1 ? 'badge badge-paid' : 'badge badge-unpaid' ?>"><?= e(employee_status_label((int) $employee['is_active'] === 1)) ?></span></td>
                <td><a class="button button-secondary" href="<?= e(employee_management_page_url('employees.php', array_filter(array(
                    'employee_id' => (int) $employee['employee_id'],
                    'filter_position_id' => $selectedFilterPositionId > 0 ? $selectedFilterPositionId : null,
                )))) ?>#employee-form-panel"><?= e($editLabel) ?></a></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</section>

<section class="form-card" id="employee-form-panel" style="margin-top: 18px;" <?= $showEmployeeForm ? '' : 'hidden' ?>>
    <div class="section-head">
        <div>
            <h2 class="section-title"><?= e($employeeFormTitle) ?></h2>
            <p class="helper"><?= e($employeeFormHelperLabel) ?></p>
        </div>
        <?php if ($editingEmployee): ?>
            <a class="button button-ghost" href="<?= e(employee_management_page_url('employees.php', array_filter(array(
                'show_form' => 1,
                'filter_position_id' => $selectedFilterPositionId > 0 ? $selectedFilterPositionId : null,
            )))) ?>"><?= e($newEmployeeLabel) ?></a>
        <?php endif; ?>
    </div>

    <form method="POST" action="../process/save_employee.php">
        <?php if ($editingEmployee): ?>
            <input type="hidden" name="employee_id" value="<?= (int) $editingEmployee['employee_id'] ?>">
        <?php endif; ?>
        <input type="hidden" name="filter_position_id" value="<?= $selectedFilterPositionId > 0 ? $selectedFilterPositionId : '' ?>">

        <div class="form-grid">
            <div class="field">
                <label for="name"><?= e($employeeNameLabel) ?></label>
                <input id="name" name="name" type="text" value="<?= e($employeeName) ?>" required>
            </div>

            <div class="field">
                <label for="phone"><?= e($phoneLabel) ?></label>
                <input id="phone" name="phone" type="text" value="<?= e($employeePhone) ?>">
            </div>

            <div class="field">
                <label for="username"><?= e($usernameLabel) ?></label>
                <input id="username" name="username" type="text" value="<?= e($employeeUsername) ?>" required>
            </div>

            <div class="field">
                <label for="password"><?= e($passwordLabel) ?></label>
                <input id="password" name="password" type="password" <?= $editingEmployee ? '' : 'required' ?>>
            </div>

            <div class="field">
                <label for="position_id"><?= e($positionLabel) ?></label>
                <select id="position_id" name="position_id" required>
                    <option value=""><?= e($selectPositionLabel) ?></option>
                    <?php foreach ($positions as $position): ?>
                        <option value="<?= (int) $position['position_id'] ?>" <?= (string) $employeePositionId === (string) $position['position_id'] ? 'selected' : '' ?>>
                            <?= e((string) $position['position_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="field">
                <label for="branch_scope"><?= e($branchScopeLabel) ?></label>
                <select id="branch_scope" name="branch_scope">
                    <?php foreach (employee_branch_scope_options() as $scopeValue => $scopeOptionLabel): ?>
                        <option value="<?= e($scopeValue) ?>" <?= $employeeScope === $scopeValue ? 'selected' : '' ?>><?= e($scopeOptionLabel) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="field">
                <label for="default_start_page"><?= e($defaultStartPageLabel) ?></label>
                <select id="default_start_page" name="default_start_page">
                    <?php foreach (auth_default_start_page_options() as $startPageKey => $startPageLabel): ?>
                        <option value="<?= e($startPageKey) ?>" <?= $employeeDefaultStartPage === $startPageKey ? 'selected' : '' ?>>
                            <?= e(translate_text($startPageLabel)) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="field">
            <label><?= e($branchesLabel) ?></label>
            <div class="checkbox-grid">
                <?php foreach ($branchNames as $branchName): ?>
                    <label class="service-option compact-option">
                        <input type="checkbox" name="branch_names[]" value="<?= e($branchName) ?>" <?= in_array($branchName, $selectedEmployeeBranches, true) ? 'checked' : '' ?>>
                        <span><?= e($branchName) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <label class="service-option compact-option">
            <input type="checkbox" name="is_active" value="1" <?= $employeeActive ? 'checked' : '' ?>>
            <span><?= e($activeAccountLabel) ?></span>
        </label>

        <button class="button button-accent" type="submit"><?= e($saveEmployeeLabel) ?></button>
    </form>
</section>

<?php render_page_end(); ?>
