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

$pageTitle = 'Edit User';

$uid = (int)($_GET['id'] ?? 0);
if (!$uid) { setFlash('danger','User not found.'); header('Location: users.php'); exit; }

$userRow = $pdo->prepare("SELECT * FROM users WHERE id=?");
$userRow->execute([$uid]);
$userRow = $userRow->fetch();
if (!$userRow) { setFlash('danger','User not found.'); header('Location: users.php'); exit; }

$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 = [];
$currentTabs = json_decode($userRow['tab_permissions'] ?? '[]', true) ?: [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: user_edit.php?id='.$uid); exit;
    }
    $name   = trim($_POST['name'] ?? '');
    $email  = trim($_POST['email'] ?? '');
    $role   = in_array($_POST['role']??'',['admin','staff']) ? $_POST['role'] : 'staff';
    $tabs   = $_POST['tabs'] ?? [];
    $status = isset($_POST['status']) ? 1 : 0;

    if (empty($name))  $errors[] = 'Name is required.';
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email required.';

    // Duplicate email (exclude self)
    $dup = $pdo->prepare("SELECT id FROM users WHERE email=? AND id!=?");
    $dup->execute([$email, $uid]);
    if ($dup->fetch()) $errors[] = 'Email already in use by another user.';

    if (empty($errors)) {
        // If this reactivates a previously-inactive user, make sure the license allows it
        if ($status == 1 && $userRow['status'] == 0) {
            if (getActiveUserCount() >= getLicenseCount()) {
                $errors[] = 'Cannot activate this user - your company has reached its license limit (' . getLicenseCount() . ' users). Contact support to increase your license.';
            }
        }
    }

    if (empty($errors)) {
        $tabJson = json_encode(array_values($tabs));
        $oldEmail = $userRow['email'];
        $pdo->prepare("UPDATE users SET name=?,email=?,role=?,status=?,tab_permissions=? WHERE id=?")
            ->execute([$name,$email,$role,$status,$tabJson,$uid]);
        require_once __DIR__ . '/../../includes/TenantIndex.php';
        tenantIndexUpdateEmail($oldEmail, $email);
        setFlash('success','User updated successfully.');
        header('Location: users.php'); exit;
    }

    $currentTabs = $tabs;
}

require_once __DIR__ . '/../../includes/header.php';
$name   = $_POST['name']  ?? $userRow['name'];
$email  = $_POST['email'] ?? $userRow['email'];
$role   = $_POST['role']  ?? $userRow['role'];
$status = array_key_exists('status',$_POST) ? (isset($_POST['status'])?1:0) : $userRow['status'];
?>
<div class="page-header">
    <h2>Edit User: <?= sanitize($userRow['name']) ?></h2>
    <div class="flex gap-8">
        <a href="user_change_password.php?id=<?= $uid ?>" class="btn btn-secondary"><?= icon('key') ?> Change Password</a>
        <a href="users.php" class="btn btn-secondary"><?= icon('arrow-left') ?> Back</a>
    </div>
</div>

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

<div class="card" style="max-width:700px;">
<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($name) ?>" required>
        </div>
        <div class="form-group">
            <label>Email Address *</label>
            <input type="email" name="email" value="<?= sanitize($email) ?>" required>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group">
            <label>Role *</label>
            <select name="role" id="roleSelect" onchange="toggleTabSection(this.value)">
                <option value="staff" <?= $role==='staff'?'selected':'' ?>>Staff</option>
                <option value="admin" <?= $role==='admin'?'selected':'' ?>>Admin</option>
            </select>
        </div>
        <div class="form-group">
            <label>Status</label>
            <label style="display:flex;align-items:center;gap:8px;margin-top:8px;">
                <input type="checkbox" name="status" <?= $status?'checked':'' ?>>
                Active (user can log in)
            </label>
        </div>
    </div>

    <div id="tabSection" style="<?= $role==='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, $currentTabs);
            ?>
            <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('device-floppy') ?> Save Changes</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'; ?>
