<?php
require_once 'header.php';

$me = get_current_user_data();
if (!$me || $me['role'] !== 'admin') {
    echo '<div class="alert alert-danger m-3">Samo administrator može upravljati korisnicima.</div>';
    require_once 'footer.php';
    exit;
}

function post_checked(string $key): int {
    return isset($_POST[$key]) ? 1 : 0;
}

function count_admins(mysqli $mysqli): int {
    $res = $mysqli->query("SELECT COUNT(*) AS cnt FROM users WHERE role = 'admin'");
    if (!$res) return 0;
    $row = $res->fetch_assoc();
    return (int)($row['cnt'] ?? 0);
}

$message = '';
$messageType = 'success';

// Dodavanje novog korisnika
if (isset($_POST['action']) && $_POST['action'] === 'create') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $role     = $_POST['role'] ?? 'user';

    $can_projects   = post_checked('can_projects');
    $can_items      = post_checked('can_items');
    $can_orders     = post_checked('can_orders');
    $can_suppliers  = post_checked('can_suppliers');
    $can_receipts   = post_checked('can_receipts');
    $can_stock      = post_checked('can_stock');
    $can_djelatnik  = post_checked('can_djelatnik');

    if ($username === '' || $password === '') {
        $message = 'Korisničko ime i lozinka su obavezni.';
        $messageType = 'danger';
    } else {
        $check = $mysqli->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
        $check->bind_param('s', $username);
        $check->execute();
        $exists = $check->get_result()->fetch_assoc();
        $check->close();

        if ($exists) {
            $message = 'Korisničko ime već postoji.';
            $messageType = 'danger';
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $mysqli->prepare("
                INSERT INTO users
                    (username, password_hash, role,
                     can_projects, can_items, can_orders,
                     can_suppliers, can_receipts, can_stock, can_djelatnik)
                VALUES (?,?,?,?,?,?,?,?,?,?)
            ");
            $stmt->bind_param(
                'sssiiiiiii',
                $username, $hash, $role,
                $can_projects, $can_items, $can_orders,
                $can_suppliers, $can_receipts, $can_stock, $can_djelatnik
            );
            $stmt->execute();
            $stmt->close();

            $message = 'Korisnik dodan.';
            $messageType = 'success';
        }
    }
}

// Ažuriranje prava postojećih korisnika
if (isset($_POST['action']) && $_POST['action'] === 'update_rights') {
    $uid = (int)($_POST['user_id'] ?? 0);
    if ($uid > 0) {
        $role           = $_POST['role'] ?? 'user';
        $can_projects   = post_checked('can_projects');
        $can_items      = post_checked('can_items');
        $can_orders     = post_checked('can_orders');
        $can_suppliers  = post_checked('can_suppliers');
        $can_receipts   = post_checked('can_receipts');
        $can_stock      = post_checked('can_stock');
        $can_djelatnik  = post_checked('can_djelatnik');

        $currentStmt = $mysqli->prepare("SELECT id, username, role FROM users WHERE id = ? LIMIT 1");
        $currentStmt->bind_param('i', $uid);
        $currentStmt->execute();
        $currentUser = $currentStmt->get_result()->fetch_assoc();
        $currentStmt->close();

        if (!$currentUser) {
            $message = 'Korisnik nije pronađen.';
            $messageType = 'danger';
        } elseif ($currentUser['role'] === 'admin' && $role !== 'admin' && count_admins($mysqli) <= 1) {
            $message = 'Nije moguće maknuti admin prava zadnjem administratoru.';
            $messageType = 'danger';
        } else {
            $stmt = $mysqli->prepare("
                UPDATE users
                SET role = ?,
                    can_projects = ?, can_items = ?, can_orders = ?,
                    can_suppliers = ?, can_receipts = ?, can_stock = ?, can_djelatnik = ?
                WHERE id = ?
            ");
            $stmt->bind_param(
                'siiiiiiii',
                $role,
                $can_projects, $can_items, $can_orders,
                $can_suppliers, $can_receipts, $can_stock, $can_djelatnik,
                $uid
            );
            $stmt->execute();
            $stmt->close();

            $message = 'Prava korisnika ažurirana.';
            $messageType = 'success';

            if ($uid === (int)$me['id']) {
                unset($_SESSION['user']);
            }
        }
    }
}

// Brisanje korisnika
if (isset($_POST['action']) && $_POST['action'] === 'delete_user') {
    $uid = (int)($_POST['user_id'] ?? 0);

    if ($uid <= 0) {
        $message = 'Neispravan korisnik.';
        $messageType = 'danger';
    } elseif ($uid === (int)$me['id']) {
        $message = 'Ne možeš obrisati trenutno prijavljenog korisnika.';
        $messageType = 'danger';
    } else {
        $stmtCheck = $mysqli->prepare("SELECT id, username, role FROM users WHERE id = ? LIMIT 1");
        $stmtCheck->bind_param('i', $uid);
        $stmtCheck->execute();
        $userToDelete = $stmtCheck->get_result()->fetch_assoc();
        $stmtCheck->close();

        if (!$userToDelete) {
            $message = 'Korisnik nije pronađen.';
            $messageType = 'danger';
        } elseif ($userToDelete['role'] === 'admin' && count_admins($mysqli) <= 1) {
            $message = 'Nije moguće obrisati zadnjeg administratora.';
            $messageType = 'danger';
        } else {
            $stmtDel = $mysqli->prepare("DELETE FROM users WHERE id = ? LIMIT 1");
            $stmtDel->bind_param('i', $uid);
            $stmtDel->execute();
            $stmtDel->close();

            $message = 'Korisnik je obrisan.';
            $messageType = 'success';
        }
    }
}

$usersRes = $mysqli->query("
    SELECT id, username, role,
           can_projects, can_items, can_orders,
           can_suppliers, can_receipts, can_stock, can_djelatnik
    FROM users
    ORDER BY username
");
?>
<div class="row g-3 mb-3 align-items-center">
    <div class="col">
        <div class="section-title">Korisnici i prava</div>
        <div class="text-muted small">Dodavanje korisnika, dodjela pristupa i sigurno brisanje korisnika</div>
    </div>
</div>

<?php if ($message !== ''): ?>
    <div class="alert alert-<?php echo $messageType; ?> mb-3"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>

<div class="row g-3">
    <div class="col-12 col-lg-4">
        <div class="card card-soft">
            <div class="card-header card-soft-header">
                <span class="fw-semibold">Novi korisnik</span>
            </div>
            <div class="card-body card-soft-body">
                <form method="post" autocomplete="off">
                    <input type="hidden" name="action" value="create">
                    <div class="mb-2">
                        <label class="form-label">Korisničko ime</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Lozinka</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Uloga</label>
                        <select name="role" class="form-select form-select-sm">
                            <option value="user">User</option>
                            <option value="admin">Admin</option>
                        </select>
                    </div>

                    <div class="d-flex flex-wrap gap-2 mb-2">
                        <button class="btn btn-sm btn-outline-secondary btn-soft" type="button" onclick="toggleAllRights(this.form, true)">Označi sve</button>
                        <button class="btn btn-sm btn-outline-secondary btn-soft" type="button" onclick="toggleAllRights(this.form, false)">Makni sve</button>
                        <button class="btn btn-sm btn-outline-secondary btn-soft" type="button" onclick="applyRolePreset(this.form, 'warehouse')">Skladište</button>
                        <button class="btn btn-sm btn-outline-secondary btn-soft" type="button" onclick="applyRolePreset(this.form, 'field')">Teren</button>
                    </div>

                    <div class="mb-2">
                        <label class="form-label small mb-1">Kartice kojima ima pristup</label>
                        <div class="d-grid gap-1 small">
                            <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_projects" id="cproj_n" checked> <span class="form-check-label">Projekti</span></label>
                            <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_djelatnik" id="cdjelat_n" checked> <span class="form-check-label">Djelatnici</span></label>
                            <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_items" id="citems_n" checked> <span class="form-check-label">Artikli</span></label>
                            <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_orders" id="corders_n" checked> <span class="form-check-label">Nalozi utroška</span></label>
                            <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_suppliers" id="csupp_n" checked> <span class="form-check-label">Dobavljači</span></label>
                            <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_receipts" id="crec_n" checked> <span class="form-check-label">Primke</span></label>
                            <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_stock" id="cstock_n" checked> <span class="form-check-label">Stanje skladišta</span></label>
                        </div>
                    </div>
                    <button class="btn btn-primary btn-soft w-100" type="submit">Spremi korisnika</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-12 col-lg-8">
        <div class="card card-soft">
            <div class="card-header card-soft-header">
                <span class="fw-semibold">Postojeći korisnici</span>
            </div>
            <div class="card-body card-soft-body">
                <div class="table-responsive">
                    <table class="table table-sm align-middle">
                        <thead class="small text-muted">
                        <tr>
                            <th>Korisnik</th>
                            <th>Uloga</th>
                            <th>Kartice</th>
                            <th class="text-end">Akcije</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php while ($urow = $usersRes->fetch_assoc()): ?>
                            <tr>
                                <td class="fw-semibold">
                                    <?php echo htmlspecialchars($urow['username']); ?>
                                    <?php if ((int)$urow['id'] === (int)$me['id']): ?>
                                        <div class="small text-muted">Trenutno prijavljen</div>
                                    <?php endif; ?>
                                </td>
                                <td colspan="3">
                                    <form method="post" class="row g-2 align-items-center" autocomplete="off">
                                        <input type="hidden" name="action" value="update_rights">
                                        <input type="hidden" name="user_id" value="<?php echo (int)$urow['id']; ?>">

                                        <div class="col-12 col-md-2">
                                            <select name="role" class="form-select form-select-sm">
                                                <option value="user" <?php echo $urow['role']==='user'?'selected':''; ?>>User</option>
                                                <option value="admin" <?php echo $urow['role']==='admin'?'selected':''; ?>>Admin</option>
                                            </select>
                                        </div>

                                        <div class="col-12 col-md-7">
                                            <div class="d-flex flex-wrap gap-2 small">
                                                <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_projects" <?php echo $urow['can_projects'] ? 'checked' : ''; ?>> <span class="form-check-label">Projekti</span></label>
                                                <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_djelatnik" <?php echo $urow['can_djelatnik'] ? 'checked' : ''; ?>> <span class="form-check-label">Djelatnici</span></label>
                                                <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_items" <?php echo $urow['can_items'] ? 'checked' : ''; ?>> <span class="form-check-label">Artikli</span></label>
                                                <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_orders" <?php echo $urow['can_orders'] ? 'checked' : ''; ?>> <span class="form-check-label">Nalozi</span></label>
                                                <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_suppliers" <?php echo $urow['can_suppliers'] ? 'checked' : ''; ?>> <span class="form-check-label">Dobavljači</span></label>
                                                <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_receipts" <?php echo $urow['can_receipts'] ? 'checked' : ''; ?>> <span class="form-check-label">Primke</span></label>
                                                <label class="form-check"><input class="form-check-input rights-toggle" type="checkbox" name="can_stock" <?php echo $urow['can_stock'] ? 'checked' : ''; ?>> <span class="form-check-label">Stanje</span></label>
                                            </div>
                                        </div>

                                        <div class="col-12 col-md-3 text-end">
                                            <div class="d-flex flex-wrap gap-2 justify-content-md-end">
                                                <button class="btn btn-sm btn-outline-primary btn-soft" type="submit">
                                                    Spremi
                                                </button>
                                                <button class="btn btn-sm btn-outline-secondary btn-soft" type="button" onclick="toggleAllRights(this.form, true)">Sve</button>
                                                <button class="btn btn-sm btn-outline-secondary btn-soft" type="button" onclick="toggleAllRights(this.form, false)">Ništa</button>
                                            </div>
                                        </div>
                                    </form>

                                    <form method="post" class="mt-2 text-end"
                                          onsubmit="return confirm('Obrisati korisnika <?php echo htmlspecialchars(addslashes($urow['username'])); ?>?');">
                                        <input type="hidden" name="action" value="delete_user">
                                        <input type="hidden" name="user_id" value="<?php echo (int)$urow['id']; ?>">
                                        <button class="btn btn-sm btn-outline-danger btn-soft"
                                                type="submit"
                                                <?php echo ((int)$urow['id'] === (int)$me['id']) ? 'disabled' : ''; ?>>
                                            Obriši korisnika
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <div class="text-muted small mt-2">
                    Napomena: <strong>Admin</strong> uvijek ima pristup svim karticama, bez obzira na kvačice. Nije moguće obrisati trenutno prijavljenog korisnika ni zadnjeg administratora.
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleAllRights(form, checked) {
    form.querySelectorAll('.rights-toggle').forEach(cb => {
        cb.checked = checked;
    });
}

function applyRolePreset(form, preset) {
    const map = {
        can_projects: false,
        can_djelatnik: false,
        can_items: false,
        can_orders: false,
        can_suppliers: false,
        can_receipts: false,
        can_stock: false
    };

    if (preset === 'warehouse') {
        map.can_items = true;
        map.can_suppliers = true;
        map.can_receipts = true;
        map.can_stock = true;
    } else if (preset === 'field') {
        map.can_projects = true;
        map.can_orders = true;
        map.can_djelatnik = true;
    }

    Object.keys(map).forEach(name => {
        const el = form.querySelector('[name="' + name + '"]');
        if (el) el.checked = map[name];
    });
}
</script>

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