<?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 admin_count(mysqli $mysqli): int {
    $res = $mysqli->query("SELECT COUNT(*) AS c FROM users WHERE role='admin'");
    if (!$res) return 0;
    $row = $res->fetch_assoc();
    return (int)($row['c'] ?? 0);
}

function username_exists(mysqli $mysqli, string $username, int $excludeId = 0): bool {
    if ($excludeId > 0) {
        $stmt = $mysqli->prepare('SELECT id FROM users WHERE username = ? AND id <> ? LIMIT 1');
        $stmt->bind_param('si', $username, $excludeId);
    } else {
        $stmt = $mysqli->prepare('SELECT id FROM users WHERE username = ? LIMIT 1');
        $stmt->bind_param('s', $username);
    }
    $stmt->execute();
    $stmt->store_result();
    $exists = $stmt->num_rows > 0;
    $stmt->close();
    return $exists;
}

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

$messages = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $role     = ($_POST['role'] ?? 'user') === 'admin' ? 'admin' : 'user';

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

        if ($username === '' || $password === '') {
            $messages[] = ['danger', 'Korisničko ime i lozinka su obavezni.'];
        } elseif (username_exists($mysqli, $username)) {
            $messages[] = ['danger', 'Korisničko ime već postoji.'];
        } 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();
            $messages[] = ['success', 'Korisnik dodan.'];
        }
    }

    if ($action === 'update_rights') {
        $uid = (int)($_POST['user_id'] ?? 0);
        $role = ($_POST['role'] ?? 'user') === 'admin' ? 'admin' : 'user';
        $can_projects   = bool_post('can_projects');
        $can_djelatnik  = bool_post('can_djelatnik');
        $can_items      = bool_post('can_items');
        $can_orders     = bool_post('can_orders');
        $can_suppliers  = bool_post('can_suppliers');
        $can_receipts   = bool_post('can_receipts');
        $can_stock      = bool_post('can_stock');

        if ($uid <= 0) {
            $messages[] = ['danger', 'Neispravan korisnik.'];
        } else {
            $stmtOld = $mysqli->prepare('SELECT username, role FROM users WHERE id = ? LIMIT 1');
            $stmtOld->bind_param('i', $uid);
            $stmtOld->execute();
            $old = $stmtOld->get_result()->fetch_assoc();
            $stmtOld->close();

            if (!$old) {
                $messages[] = ['danger', 'Korisnik nije pronađen.'];
            } elseif ($old['role'] === 'admin' && $role !== 'admin' && admin_count($mysqli) <= 1) {
                $messages[] = ['danger', 'Nije moguće maknuti admin ulogu zadnjem administratoru.'];
            } 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();
                $messages[] = ['success', 'Prava korisnika ažurirana.'];

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

    if ($action === 'change_password') {
        $uid = (int)($_POST['user_id'] ?? 0);
        $password = trim($_POST['new_password'] ?? '');

        if ($uid <= 0 || $password === '') {
            $messages[] = ['danger', 'Nova lozinka je obavezna.'];
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $mysqli->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
            $stmt->bind_param('si', $hash, $uid);
            $stmt->execute();
            $stmt->close();
            $messages[] = ['success', 'Lozinka je promijenjena.'];
        }
    }

    if ($action === 'delete_user') {
        $uid = (int)($_POST['user_id'] ?? 0);
        if ($uid <= 0) {
            $messages[] = ['danger', 'Neispravan korisnik.'];
        } elseif ($uid === (int)$me['id']) {
            $messages[] = ['danger', 'Nije moguće obrisati trenutno prijavljenog korisnika.'];
        } else {
            $stmtChk = $mysqli->prepare('SELECT username, role FROM users WHERE id = ? LIMIT 1');
            $stmtChk->bind_param('i', $uid);
            $stmtChk->execute();
            $row = $stmtChk->get_result()->fetch_assoc();
            $stmtChk->close();

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

$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"
);

$rightsMap = [
    'can_projects' => 'Projekti',
    'can_djelatnik' => 'Djelatnici',
    'can_items' => 'Artikli',
    'can_orders' => 'Nalozi',
    'can_suppliers' => 'Dobavljači',
    'can_receipts' => 'Primke',
    'can_stock' => 'Stanje',
];
?>
<style>
.permission-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 14px;}
.permission-chip{display:flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid rgba(255,255,255,.12);border-radius:12px;background:rgba(255,255,255,.03);}
.user-row-card{border:1px solid rgba(255,255,255,.12);border-radius:18px;padding:16px;background:linear-gradient(180deg,rgba(255,255,255,.02),rgba(255,255,255,.03));}
.user-row-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:12px;}
.user-name{font-weight:700;font-size:1rem;color:#fff;line-height:1.2;}
.user-sub{font-size:.82rem;color:rgba(255,255,255,.72);margin-top:4px;}
.user-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:8px;}
.user-action-stack{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end;}
.preset-buttons{display:flex;flex-wrap:wrap;gap:8px;}
.form-inline-soft{display:flex;flex-wrap:wrap;gap:8px;align-items:center;}
.role-box{min-width:150px;max-width:180px;}
.pass-box{min-width:220px;max-width:280px;}
@media (max-width: 991.98px){
  .permission-grid{grid-template-columns:1fr;}
  .user-row-head{flex-direction:column;align-items:flex-start;}
  .user-actions,.user-action-stack{justify-content:flex-start;}
  .role-box,.pass-box{min-width:100%;max-width:none;}
}
</style>

<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, brza dodjela pristupa i sigurno upravljanje računima</div>
    </div>
</div>

<?php foreach ($messages as [$type, $text]): ?>
    <div class="alert alert-<?php echo $type; ?> mb-3"><?php echo htmlspecialchars($text); ?></div>
<?php endforeach; ?>

<div class="row g-3">
    <div class="col-12 col-xl-4">
        <div class="card card-soft h-100">
            <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" id="createUserForm">
                    <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 align-items-center justify-content-between mb-2">
                        <label class="form-label small mb-0">Kartice kojima ima pristup</label>
                        <div class="preset-buttons">
                            <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="toggleRights('createUserForm', true)">Sve</button>
                            <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="toggleRights('createUserForm', false)">Ništa</button>
                            <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="applyPreset('createUserForm','warehouse')">Skladište</button>
                            <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="applyPreset('createUserForm','field')">Teren</button>
                        </div>
                    </div>

                    <div class="permission-grid mb-3">
                        <?php foreach ($rightsMap as $field => $label): ?>
                            <label class="permission-chip">
                                <input class="form-check-input m-0" type="checkbox" name="<?php echo $field; ?>" <?php echo in_array($field, ['can_projects','can_djelatnik','can_items','can_orders','can_suppliers','can_receipts','can_stock'], true) ? 'checked' : ''; ?>>
                                <span><?php echo htmlspecialchars($label); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>

                    <button class="btn btn-primary btn-soft w-100" type="submit">Spremi korisnika</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-8">
        <div class="card card-soft">
            <div class="card-header card-soft-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                <span class="fw-semibold">Postojeći korisnici</span>
                <span class="text-muted small">Admin uvijek ima pristup svim karticama</span>
            </div>
            <div class="card-body card-soft-body d-grid gap-3">
                <?php while ($urow = $usersRes->fetch_assoc()): ?>
                    <?php
                        $isMe = ((int)$urow['id'] === (int)$me['id']);
                        $isLastAdmin = ($urow['role'] === 'admin' && admin_count($mysqli) <= 1);
                    ?>
                    <div class="user-row-card">
                        <div class="user-row-head">
                            <div>
                                <div class="user-name"><?php echo htmlspecialchars($urow['username']); ?></div>
                                <div class="user-sub">
                                    <?php echo $urow['role'] === 'admin' ? 'Administrator' : 'Korisnik'; ?>
                                    <?php if ($isMe): ?> · Trenutno prijavljen<?php endif; ?>
                                </div>
                            </div>
                            <div class="user-actions">
                                <form method="post" class="m-0" onsubmit="return confirm('Obrisati korisnika <?php echo htmlspecialchars($urow['username'], ENT_QUOTES); ?>?');">
                                    <input type="hidden" name="action" value="delete_user">
                                    <input type="hidden" name="user_id" value="<?php echo (int)$urow['id']; ?>">
                                    <button class="btn btn-outline-danger btn-soft btn-sm" type="submit" <?php echo ($isMe || $isLastAdmin) ? 'disabled' : ''; ?>>Obriši korisnika</button>
                                </form>
                            </div>
                        </div>

                        <form method="post" class="d-grid gap-3" id="userForm_<?php echo (int)$urow['id']; ?>">
                            <input type="hidden" name="action" value="update_rights">
                            <input type="hidden" name="user_id" value="<?php echo (int)$urow['id']; ?>">

                            <div class="form-inline-soft">
                                <div class="role-box">
                                    <label class="form-label small">Uloga</label>
                                    <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="user-action-stack ms-auto">
                                    <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="toggleRights('userForm_<?php echo (int)$urow['id']; ?>', true)">Sve</button>
                                    <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="toggleRights('userForm_<?php echo (int)$urow['id']; ?>', false)">Ništa</button>
                                    <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="applyPreset('userForm_<?php echo (int)$urow['id']; ?>','warehouse')">Skladište</button>
                                    <button type="button" class="btn btn-outline-secondary btn-soft btn-sm" onclick="applyPreset('userForm_<?php echo (int)$urow['id']; ?>','field')">Teren</button>
                                    <button class="btn btn-primary btn-soft btn-sm" type="submit">Spremi</button>
                                </div>
                            </div>

                            <div class="permission-grid">
                                <?php foreach ($rightsMap as $field => $label): ?>
                                    <label class="permission-chip">
                                        <input class="form-check-input m-0" type="checkbox" name="<?php echo $field; ?>" <?php echo !empty($urow[$field]) ? 'checked' : ''; ?>>
                                        <span><?php echo htmlspecialchars($label); ?></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </form>

                        <form method="post" class="form-inline-soft mt-3" onsubmit="return confirm('Promijeniti lozinku korisniku <?php echo htmlspecialchars($urow['username'], ENT_QUOTES); ?>?');">
                            <input type="hidden" name="action" value="change_password">
                            <input type="hidden" name="user_id" value="<?php echo (int)$urow['id']; ?>">
                            <div class="pass-box">
                                <label class="form-label small">Nova lozinka</label>
                                <input type="password" name="new_password" class="form-control form-control-sm" placeholder="Upiši novu lozinku">
                            </div>
                            <div class="pt-4">
                                <button class="btn btn-outline-secondary btn-soft btn-sm" type="submit">Promijeni lozinku</button>
                            </div>
                        </form>
                    </div>
                <?php endwhile; ?>

                <div class="text-muted small">
                    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 checkboxFields(form){
  return Array.from(form.querySelectorAll('input[type="checkbox"][name^="can_"]'));
}
function toggleRights(formId, checked){
  const form = document.getElementById(formId);
  if(!form) return;
  checkboxFields(form).forEach(cb => cb.checked = !!checked);
}
function applyPreset(formId, preset){
  const form = document.getElementById(formId);
  if(!form) return;
  const map = {
    warehouse: ['can_items','can_suppliers','can_receipts','can_stock'],
    field: ['can_projects','can_djelatnik','can_orders']
  };
  checkboxFields(form).forEach(cb => cb.checked = false);
  (map[preset] || []).forEach(name => {
    const el = form.querySelector(`input[name="${name}"]`);
    if(el) el.checked = true;
  });
}
</script>

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