<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();
requireAdmin();

$pageTitle = 'Create User';

// All available tabs with friendly labels
$allTabs = [
    'dashboard'         => 'Dashboard',
    'purchase_vendors'  => 'Purchase Vendors',
    'sale_vendors'      => 'Sale Customers',
    'items'             => 'Item Master',
    'purchases'         => 'Purchase Entry',
    'purchase_payment'  => 'Purchase Payments',
    'stock_view'        => 'Stock Overview',
    'quotations'        => 'Quotations',
    'delivery_notes'    => 'Delivery Notes',
    'invoices'          => 'Tax Invoices',
    'sale_billing'      => 'Sale Billing',
    'manual_billing'    => 'Manual Billing',
    'payments'          => 'Payments',
    'purchase_report'   => 'Purchase Reports',
    'sales_report'      => 'Sales Reports',
    'cashflow_report'   => 'Cash Flow',
    'accounts'          => 'Accounts & Finance',
    'settings'          => 'Settings',
];

$errors = [];

// License check: block creating more users than this company is licensed for
$licenseCount = getLicenseCount();
$activeUserCount = getActiveUserCount();
$licenseReached = $activeUserCount >= $licenseCount;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($licenseReached) {
        setFlash('danger', "License limit reached ($activeUserCount / $licenseCount users). Contact support to increase your license before adding more users.");
        header('Location: user_create.php'); exit;
    }
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.'); header('Location: user_create.php'); exit;
    }

    $name     = trim($_POST['name'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';
    $role     = in_array($_POST['role'] ?? '', ['admin','staff']) ? $_POST['role'] : 'staff';
    $tabs     = $_POST['tabs'] ?? [];

    if (empty($name))    $errors[] = 'Name is required.';
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email required.';
    if (strlen($password) < 6) $errors[] = 'Password must be at least 6 characters.';
    if ($password !== $confirm)  $errors[] = 'Passwords do not match.';

    // Check duplicate email
    $existing = $pdo->prepare("SELECT id FROM users WHERE email=?");
    $existing->execute([$email]);
    if ($existing->fetch()) $errors[] = 'Email already in use.';

    if (empty($errors)) {
        $hash        = password_hash($password, PASSWORD_DEFAULT);
        $tabJson     = json_encode(array_values($tabs));
        $stmt = $pdo->prepare("INSERT INTO users (name, email, password, role, tab_permissions) VALUES (?,?,?,?,?)");
        $stmt->execute([$name, $email, $hash, $role, $tabJson]);
        require_once __DIR__ . '/../../includes/TenantIndex.php';
        tenantIndexAdd($email);
        setFlash('success', "User '$name' created successfully. They can log in and change their password.");
        header('Location: users.php'); exit;
    }
}

require_once __DIR__ . '/../../includes/header.php';
?>
<div class="page-header">
    <h2>Create New User</h2>
    <a href="users.php" class="btn btn-secondary"><?= icon('arrow-left') ?> Back</a>
</div>

<?php if ($errors): ?>
<div class="alert alert-danger"><?= icon('alert-circle') ?> <?= implode('<br>', array_map('sanitize', $errors)) ?></div>
<?php endif; ?>

<div class="alert <?= $licenseReached ? 'alert-danger' : 'alert-info' ?>">
    <?= icon('users') ?> License usage: <strong><?= $activeUserCount ?> / <?= $licenseCount ?></strong> users.
    <?php if ($licenseReached): ?>
        You've reached your license limit — contact support to add more seats before creating another user.
    <?php endif; ?>
</div>

<div class="card" style="max-width:700px;<?= $licenseReached ? 'opacity:0.5;pointer-events:none;' : '' ?>">
<form method="POST">
    <input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">

    <div class="form-row">
        <div class="form-group">
            <label>Full Name *</label>
            <input type="text" name="name" value="<?= sanitize($_POST['name'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Email Address *</label>
            <input type="email" name="email" value="<?= sanitize($_POST['email'] ?? '') ?>" required>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group">
            <label>Password * <span class="text-muted text-sm">(user can change after login)</span></label>
            <input type="password" name="password" required minlength="6">
        </div>
        <div class="form-group">
            <label>Confirm Password *</label>
            <input type="password" name="confirm_password" required>
        </div>
    </div>

    <div class="form-group">
        <label>Role *</label>
        <select name="role" id="roleSelect" onchange="toggleTabSection(this.value)">
            <option value="staff" <?= ($_POST['role']??'staff')==='staff'?'selected':'' ?>>Staff</option>
            <option value="admin" <?= ($_POST['role']??'')==='admin'?'selected':'' ?>>Admin</option>
        </select>
        <div class="text-sm text-muted" style="margin-top:4px;">Admin has access to all tabs. For Staff, choose tabs below.</div>
    </div>

    <div id="tabSection" style="<?= ($_POST['role']??'staff')==='admin'?'display:none':'' ?>">
        <label style="font-weight:600;margin-bottom:8px;display:block;"><?= icon('layout-grid') ?> Tab Access Permissions</label>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:8px;padding:16px;background:var(--bg-secondary);border-radius:8px;border:1px solid var(--border);">
            <?php foreach ($allTabs as $key => $label): 
                $checked = in_array($key, $_POST['tabs'] ?? []);
            ?>
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-weight:400;">
                <input type="checkbox" name="tabs[]" value="<?= $key ?>" <?= $checked?'checked':'' ?>>
                <?= sanitize($label) ?>
            </label>
            <?php endforeach; ?>
        </div>
        <div style="margin-top:8px;">
            <button type="button" class="btn btn-sm btn-secondary" onclick="checkAll(true)">Select All</button>
            <button type="button" class="btn btn-sm btn-secondary" onclick="checkAll(false)">Deselect All</button>
        </div>
    </div>

    <div style="margin-top:24px;">
        <button type="submit" class="btn btn-primary"><?= icon('user-check') ?> Create User</button>
        <a href="users.php" class="btn btn-secondary">Cancel</a>
    </div>
</form>
</div>

<script>
function toggleTabSection(role) {
    document.getElementById('tabSection').style.display = role === 'admin' ? 'none' : '';
}
function checkAll(check) {
    document.querySelectorAll('#tabSection input[type=checkbox]').forEach(cb => cb.checked = check);
}
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
