<?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']);

$user = new User($conn);
$allTerminals = $user->getAllTerminals();
$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;

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

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

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <div class="container mt-5">
        <h1 class="mb-4">Add New 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" required>
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" id="password" name="password" required>
            </div>
            <div class="form-group">
                <label for="role">Role</label>
                <select class="form-control" id="role" name="role" required>
                    <option value="admin">Admin</option>
                    <option value="warehouse">Warehouse</option>
                    <option value="branch">Branch</option>
                    <option value="sales">Sales</option>
                </select>
            </div>
            <div class="form-group">
                <label for="email">Email</label>
                <input type="email" class="form-control" id="email" name="email" required>
            </div>
            <div class="form-group">
                <label for="branch">Branch</label>
                <select class="form-control" id="branch" name="branch" required>
                    <?php
                    $branchObj = new Branch($conn);
                    $branches = $branchObj->getAllBranches();
                    $postedBranch = $_POST['branch'] ?? '';
                    while ($branch = $branches->fetch(PDO::FETCH_ASSOC)) {
                        $selected = ((string)$postedBranch === (string)$branch['branch_id']) ? 'selected' : '';
                        echo '<option value="' . htmlspecialchars($branch['branch_id']) . '" ' . $selected . '>' .
                             htmlspecialchars($branch['branch_name']) . '</option>';
                    }
                    ?>
                </select>
            </div>
            <div class="form-group">
                <label for="terminal_id">Terminal</label>
                <select class="form-control" id="terminal_id" name="terminal_id" required>
                    <option value="">Select branch first</option>
                    <?php
                    $postedTerminal = $_POST['terminal_id'] ?? '';
                    foreach ($allTerminals as $terminal) {
                        $selected = ((string)$postedTerminal === (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">Add User</button>
            <a href="users_list.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
    <script>
        (function () {
            var branchSelect = document.getElementById('branch');
            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 = '';
                }

                options[0].textContent = visibleCount ? 'Select terminal' : 'No terminals for this branch';
            }

            branchSelect.addEventListener('change', filterTerminals);
            filterTerminals();
        })();
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
