<?php
require_once '../../includes/auth.php';
require_once '../../db.php';

$editId   = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$isEdit   = $editId > 0;
$user     = null;
$assigned = [];

if ($isEdit) {
    $user = $conn->query("SELECT * FROM users WHERE id = $editId")->fetch_assoc();
    if (!$user) die('User not found');
    $r = $conn->query("SELECT company_id FROM user_companies WHERE user_id = $editId");
    while ($row = $r->fetch_row()) $assigned[] = (int)$row[0];
}

// Load all companies
$companies = [];
$cr = $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name");
while ($c = $cr->fetch_assoc()) $companies[] = $c;

// Load all roles for role_id dropdown
$allRoles = $conn->query("
    SELECT id, name FROM roles ORDER BY is_system DESC, name
")->fetch_all(MYSQLI_ASSOC);

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = trim($_POST['name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $status   = (int)($_POST['status'] ?? 1);
    // Only admins may change role; staff always keeps the existing role
    $loggedInRolePost = $_SESSION['user_role'] ?? '';
    if ($loggedInRolePost === 'admin') {
        $role   = $_POST['role'] ?? 'staff';
        $roleId = $_POST['role_id'] ? (int)$_POST['role_id'] : null;
    } else {
        $role   = $isEdit ? ($user['role'] ?? 'staff') : 'staff';
        $roleId = $isEdit ? ($user['role_id'] ?? null) : null;
    }
    $co_ids   = array_map('intval', $_POST['company_ids'] ?? []);

    if (!$name)     $errors[] = 'Full name is required.';
    if (!$username) $errors[] = 'Username is required.';
    if (!$isEdit && !$password) $errors[] = 'Password is required for new user.';

    // Unique username check
    if ($username) {
        $ucheck = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
        $ucheck->bind_param("si", $username, $editId);
        $ucheck->execute();
        $ucheck->store_result();
        if ($ucheck->num_rows > 0) $errors[] = 'Username already taken.';
    }

    if (empty($errors)) {
        if ($isEdit) {
            if ($password) {
                $hashed = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("UPDATE users SET name=?, username=?, password=?, role=?, role_id=?, status=? WHERE id=?");
                $stmt->bind_param("ssssiii", $name, $username, $hashed, $role, $roleId, $status, $editId);
            } else {
                $stmt = $conn->prepare("UPDATE users SET name=?, username=?, role=?, role_id=?, status=? WHERE id=?");
                $stmt->bind_param("sssiii", $name, $username, $role, $roleId, $status, $editId);
            }
            $stmt->execute();
            $uid = $editId;
        } else {
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO users (name, username, password, role, role_id, status) VALUES (?,?,?,?,?,?)");
            $stmt->bind_param("ssssii", $name, $username, $hashed, $role, $roleId, $status);
            $stmt->execute();
            $uid = $stmt->insert_id;
        }

        // Sync company assignments
        $conn->query("DELETE FROM user_companies WHERE user_id = $uid");

        if ($role === 'admin') {
            // Admin gets all companies
            foreach ($companies as $co) {
                $coid = (int)$co['id'];
                $conn->query("INSERT INTO user_companies (user_id, company_id) VALUES ($uid, $coid)");
            }
        } else {
            // Staff gets checked companies
            foreach ($co_ids as $coid) {
                if ($coid > 0) {
                    $conn->query("INSERT INTO user_companies (user_id, company_id) VALUES ($uid, $coid)");
                }
            }
        }

        header("Location: index.php?success=1");
        exit;
    }
}

require_once '../../includes/header.php';
require_once '../../includes/sidebar.php';

$pageTitle       = $isEdit ? 'Edit User' : 'Add User';
$loggedInRole    = $_SESSION['user_role'] ?? '';
$loggedInUserId  = (int)($_SESSION['user_id'] ?? 0);
$isOwnProfile    = ($isEdit && $editId === $loggedInUserId && $loggedInRole !== 'admin');
$canChangeRole   = ($loggedInRole === 'admin');
$formRole    = $_POST['role']     ?? ($user['role']   ?? 'staff');
$formRoleId  = isset($_POST['role_id']) ? (int)$_POST['role_id'] : (int)($user['role_id'] ?? 0);
$formStatus  = $_POST['status']   ?? ($user['status'] ?? 1);
$formName    = $_POST['name']     ?? ($user['name']   ?? '');
$formUser    = $_POST['username'] ?? ($user['username'] ?? '');
$formCoids   = $_POST['company_ids'] ?? ($assigned);
?>

<div class="page-header">
    <h2><i class="fas fa-user-<?= $isEdit ? 'edit' : 'plus' ?>" style="color:var(--primary);margin-right:8px;"></i><?= $pageTitle ?></h2>
    <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<?php if ($errors): ?>
<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:12px 16px;margin-bottom:16px;color:#991b1b;">
    <strong><i class="fas fa-exclamation-circle"></i> Please fix the following:</strong>
    <ul style="margin:6px 0 0 16px;">
        <?php foreach ($errors as $e): ?>
        <li><?= htmlspecialchars($e) ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<form method="post" style="max-width:720px;">
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title"><i class="fas fa-user" style="color:var(--primary);margin-right:8px;"></i>User Details</span></div>
    <div class="panel-body">
        <div class="form-row">
            <div class="form-group">
                <label>Full Name <span style="color:var(--danger)">*</span></label>
                <input type="text" name="name" required value="<?= htmlspecialchars($formName) ?>" placeholder="Full name">
            </div>
            <div class="form-group">
                <label>Username <span style="color:var(--danger)">*</span></label>
                <input type="text" name="username" required value="<?= htmlspecialchars($formUser) ?>" placeholder="Login username" autocomplete="off">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>Password <?= $isEdit ? '<span style="font-weight:400;color:var(--text-muted);font-size:12px;">(leave blank to keep current)</span>' : '<span style="color:var(--danger)">*</span>' ?></label>
                <input type="password" name="password" <?= $isEdit ? '' : 'required' ?> placeholder="<?= $isEdit ? 'New password (optional)' : 'Set password' ?>" autocomplete="new-password">
            </div>
        </div>
        <?php if ($canChangeRole): ?>
        <div class="form-row">
            <div class="form-group">
                <label>System Role <span style="color:var(--danger)">*</span></label>
                <select name="role" id="roleSelect" onchange="toggleCompanyAccess()" required>
                    <option value="staff" <?= $formRole === 'staff' ? 'selected' : '' ?>>Staff</option>
                    <option value="master_staff" <?= $formRole === 'master_staff' ? 'selected' : '' ?>>Master Staff</option>
                    <option value="admin" <?= $formRole === 'admin' ? 'selected' : '' ?>>Admin</option>
                </select>
            </div>
            <div class="form-group">
                <label>Permission Role</label>
                <select name="role_id">
                    <option value="">— No role —</option>
                    <?php foreach ($allRoles as $r): ?>
                    <option value="<?= $r['id'] ?>" <?= $formRoleId === (int)$r['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($r['name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <small style="color:var(--text-muted);">Defines module access permissions for this user.</small>
            </div>
            <div class="form-group">
                <label>Status</label>
                <select name="status">
                    <option value="1" <?= $formStatus ? 'selected' : '' ?>>Active</option>
                    <option value="0" <?= !$formStatus ? 'selected' : '' ?>>Inactive</option>
                </select>
            </div>
        </div>
        <?php else: ?>
        <input type="hidden" name="role" value="<?= htmlspecialchars($formRole) ?>">
        <input type="hidden" name="role_id" value="<?= $formRoleId ?>">
        <input type="hidden" name="status" value="<?= (int)$formStatus ?>">
        <?php endif; ?>
    </div>
</div>

<?php if (!$isOwnProfile): ?>
<div class="panel" id="companyPanel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title"><i class="fas fa-building" style="color:var(--primary);margin-right:8px;"></i>Company Access</span></div>
    <div class="panel-body">
        <div id="adminNote" style="display:none;padding:10px 14px;background:#eff6ff;border-radius:6px;color:#1e40af;font-size:13px;">
            <i class="fas fa-info-circle" style="margin-right:6px;"></i>
            Admin has access to <strong>all companies</strong> automatically.
        </div>
        <div id="companyCheckboxes">
            <?php if (empty($companies)): ?>
                <p style="color:var(--text-muted);font-size:13px;">No companies found. <a href="<?= BASE_URL ?>/settings/companies/index.php">Add a company first.</a></p>
            <?php else: ?>
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px;">
                <?php foreach ($companies as $co): ?>
                <label style="display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--bg-light);border-radius:6px;cursor:pointer;border:1px solid transparent;transition:border-color 0.15s;"
                       onmouseover="this.style.borderColor='var(--primary)'" onmouseout="this.style.borderColor='transparent'">
                    <input type="checkbox" name="company_ids[]" value="<?= $co['id'] ?>"
                           <?= in_array((int)$co['id'], $formCoids) ? 'checked' : '' ?>>
                    <span><?= htmlspecialchars($co['company_name']) ?></span>
                </label>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<div style="display:flex;gap:10px;">
    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> <?= $isEdit ? 'Update User' : 'Save User' ?></button>
    <a href="index.php" class="btn btn-secondary">Cancel</a>
</div>
</form>

<script>
function toggleCompanyAccess() {
    var adminNote = document.getElementById('adminNote');
    var checkboxes = document.getElementById('companyCheckboxes');
    if (!adminNote || !checkboxes) return;
    const role = document.getElementById('roleSelect').value;
    const isAdmin = role === 'admin';
    adminNote.style.display   = isAdmin ? 'block' : 'none';
    checkboxes.style.display  = isAdmin ? 'none'  : 'block';
}
toggleCompanyAccess();
</script>

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