<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/User.php';
require_once __DIR__ . '/../../classes/Branch.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


if (!isset($_GET['id'])) {
    header('Location: users_list.php');
    exit();
}
$user_id = $_GET['id'];


$user = new User($conn);
$userDetails = $user->getUserById($user_id);
if (!$userDetails) {
    header('Location: users_list.php');
    exit();
}

$allTerminals = $user->getAllTerminals();
$roleOptions = User::getRoleOptions();
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $role = $_POST['role'];
    $email = $_POST['email'];
    $branch = $_POST['branch'];
    $terminal = $_POST['terminal_id'] ?? null;
    // Terminal is never required when editing an existing user — branch staff can be
    // saved without a terminal assigned; validateTerminalAssignment() still checks that
    // a *provided* terminal belongs to the selected branch.
    $requiresTerminal = false;

    try {
        if ($user->updateUser($user_id, $username, $password, $role, $email, $branch, $terminal, $requiresTerminal)) {
            header('Location: users_list.php');
            exit();
        }

        $error = 'Failed to update user.';
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <div class="container mt-5">
        <h1 class="mb-4">Edit User</h1>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <form method="POST">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($userDetails['username'] ?? ''); ?>" required>
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" id="password" name="password">
            </div>
            <div class="form-group">
                <label for="role">Role</label>
                <select class="form-control" id="role" name="role" required>
                    <?php foreach ($roleOptions as $value => $label): ?>
                        <option value="<?php echo htmlspecialchars($value); ?>" <?php echo (($userDetails['role'] ?? '') === $value) ? 'selected' : ''; ?>><?php echo htmlspecialchars($label); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="email">Email</label>
                <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($userDetails['email'] ?? ''); ?>" required>
            </div>
            <div class="form-group">
                <label for="branch">Branch</label>
                <select class="form-control" id="branch" name="branch">
                    <?php
                    $branchObj = new Branch($conn);
                    $branches = $branchObj->getAllBranches();
                    $selectedBranch = $_POST['branch'] ?? $userDetails['branch_id'];
                    $noBranchSelected = ($selectedBranch === null || $selectedBranch === '');
                    echo '<option value="" ' . ($noBranchSelected ? 'selected' : '') . '>System-wide / No branch</option>';
                    while ($branch = $branches->fetch(PDO::FETCH_ASSOC)) {
                        $selected = ((string)$selectedBranch === (string)$branch['branch_id']) ? 'selected' : '';
                        echo '<option value="' . htmlspecialchars($branch['branch_id']) . '" ' . $selected . '>' .
                             htmlspecialchars($branch['branch_name']) . '</option>';
                    }
                    ?>
                </select>
                <small class="form-text text-muted" id="branchAdminHint" style="display:none;">
                    Optional for Admin/Super Admin — assigning a branch + terminal only lets this account complete MRA EIS registration/testing flows for that branch. It does not restrict their normal system-wide access.
                </small>
            </div>
            <div class="form-group">
                <label for="terminal_id">Terminal</label>
                <select class="form-control" id="terminal_id" name="terminal_id">
                    <option value="">Select branch first</option>
                    <?php
                    $selectedTerminal = $_POST['terminal_id'] ?? $userDetails['terminal_id'];
                    foreach ($allTerminals as $terminal) {
                        $selected = ((string)$selectedTerminal === (string)$terminal['id']) ? 'selected' : '';
                        echo '<option value="' . htmlspecialchars($terminal['id']) . '" data-branch="' . htmlspecialchars($terminal['branch_id']) . '" ' . $selected . '>' .
                             htmlspecialchars($terminal['terminal_label'] . ' (' . $terminal['status'] . ')') .
                             '</option>';
                    }
                    ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Update User</button>
            <a href="users_list.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
    <script>
        (function () {
            var branchSelect = document.getElementById('branch');
            var roleSelect = document.getElementById('role');
            var terminalSelect = document.getElementById('terminal_id');
            var options = Array.prototype.slice.call(terminalSelect.options);

            function filterTerminals() {
                var branchId = branchSelect.value;
                var visibleCount = 0;

                options.forEach(function (option) {
                    if (!option.value) {
                        option.textContent = 'Select terminal';
                        option.hidden = false;
                        return;
                    }

                    var show = option.getAttribute('data-branch') === branchId;
                    option.hidden = !show;
                    option.disabled = !show;
                    if (show) {
                        visibleCount++;
                    }
                });

                if (terminalSelect.selectedOptions.length && terminalSelect.selectedOptions[0].disabled) {
                    terminalSelect.value = '';
                }

                // Controller stays strictly system-wide (no branch/terminal at all).
                // Admin/super_admin may optionally have a branch + terminal assigned
                // for MRA EIS registration/testing purposes, so their fields stay
                // editable and aren't cleared before submit.
                var noBranchRole = roleSelect && roleSelect.value === 'controller';
                var optionalBranchRole = roleSelect && (roleSelect.value === 'admin' || roleSelect.value === 'super_admin');
                if (branchSelect) { branchSelect.required = !(noBranchRole || optionalBranchRole); }
                // Terminal is always optional when editing a user.
                terminalSelect.required = false;
                options[0].textContent = noBranchRole ? 'No terminal required' : (visibleCount ? 'Select terminal (optional)' : 'No terminals for this branch');

                var hint = document.getElementById('branchAdminHint');
                if (hint) { hint.style.display = optionalBranchRole ? 'block' : 'none'; }
            }

            branchSelect.addEventListener('change', filterTerminals);
            if (roleSelect) { roleSelect.addEventListener('change', filterTerminals); }
            var form = terminalSelect.closest('form');
            if (form) {
                form.addEventListener('submit', function () {
                    var noBranchRole = roleSelect && roleSelect.value === 'controller';
                    if (noBranchRole) { terminalSelect.value = ''; }
                });
            }
            filterTerminals();
        })();
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>

