<?php
// api/users.php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth_stub.php';

session_start();

function json_error($message, $code = 400) {
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

function json_ok($data = []) {
    echo json_encode(array_merge(['status' => 'ok'], $data), JSON_UNESCAPED_UNICODE);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

try {
    // USERS RO'YXATI
    if ($action === 'list') {
        $stmt = $pdo->query("
          SELECT id, name, login, role_id, is_active, created_at, updated_at
            FROM users
           ORDER BY id DESC
        ");
        $users = $stmt->fetchAll();
        json_ok(['users' => $users]);
    }

    // CREATE / UPDATE
    if ($action === 'save') {
        if ($method !== 'POST') {
            json_error('POST bo‘lishi kerak', 405);
        }

        $id        = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $name      = trim($_POST['name'] ?? '');
        $login     = trim($_POST['login'] ?? '');
        $password  = trim($_POST['password'] ?? '');
        $role_id   = (int)($_POST['role_id'] ?? 2);
        $is_active = isset($_POST['is_active']) && $_POST['is_active'] == '1' ? 1 : 0;

        if ($name === '' || $login === '') {
            json_error('F.I.Sh va Login majburiy.');
        }
        if ($id === 0 && $password === '') {
            json_error('Yangi foydalanuvchi uchun parol majburiy.');
        }

        // login unikal bo‘lsin
        $checkStmt = $pdo->prepare("SELECT id FROM users WHERE login = :login AND id <> :id");
        $checkStmt->execute([
            ':login' => $login,
            ':id'    => $id,
        ]);
        if ($checkStmt->fetch()) {
            json_error('Bu login allaqachon band. Boshqa login tanlang.');
        }

        // Rol ID ni himoya qilamiz
        if (!in_array($role_id, [1, 2, 3,4], true)) {
            $role_id = 2;
        }

        if ($id > 0) {
            // UPDATE – agar password bo‘sh bo‘lsa, o‘zgarmaydi
            if ($password !== '') {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("
                    UPDATE users
                       SET name          = :name,
                           login         = :login,
                           password_hash = :pass,
                           role_id       = :role_id,
                           is_active     = :active,
                           updated_at    = NOW()
                     WHERE id = :id
                ");
                $stmt->execute([
                    ':name'    => $name,
                    ':login'   => $login,
                    ':pass'    => $hash,
                    ':role_id' => $role_id,
                    ':active'  => $is_active,
                    ':id'      => $id,
                ]);
            } else {
                $stmt = $pdo->prepare("
                    UPDATE users
                       SET name       = :name,
                           login      = :login,
                           role_id    = :role_id,
                           is_active  = :active,
                           updated_at = NOW()
                     WHERE id = :id
                ");
                $stmt->execute([
                    ':name'    => $name,
                    ':login'   => $login,
                    ':role_id' => $role_id,
                    ':active'  => $is_active,
                    ':id'      => $id,
                ]);
            }

            json_ok(['message' => 'Foydalanuvchi tahrirlandi', 'id' => $id]);

        } else {
            // INSERT
            $hash = password_hash($password, PASSWORD_DEFAULT);

            $createdBy = current_user_id();
            if (!$createdBy) {
                // bootstrap uchun: agar auth_stub user bermasa ham, 1-admin sifatida yozib turamiz
                $createdBy = 1;
            }

            $stmt = $pdo->prepare("
                INSERT INTO users
                  (name, login, password_hash, role_id, created_at, created_by, is_active)
                VALUES
                  (:name, :login, :pass, :role_id, NOW(), :created_by, :active)
            ");
            $stmt->execute([
                ':name'       => $name,
                ':login'      => $login,
                ':pass'       => $hash,
                ':role_id'    => $role_id,
                ':created_by' => $createdBy,
                ':active'     => $is_active,
            ]);
            $newId = (int)$pdo->lastInsertId();
            json_ok(['message' => 'Yangi foydalanuvchi qo‘shildi', 'id' => $newId]);
        }
    }

    // ACTIVE/INACTIVE TOGGLE
    if ($action === 'toggle') {
        if ($method !== 'POST') {
            json_error('POST bo‘lishi kerak', 405);
        }
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            json_error('Noto‘g‘ri ID');
        }

        $rowStmt = $pdo->prepare("SELECT is_active FROM users WHERE id = ?");
        $rowStmt->execute([$id]);
        $row = $rowStmt->fetch();
        if (!$row) {
            json_error('Foydalanuvchi topilmadi', 404);
        }

        $newState = $row['is_active'] ? 0 : 1;
        $upd = $pdo->prepare("
            UPDATE users
               SET is_active  = ?,
                   updated_at = NOW()
             WHERE id = ?
        ");
        $upd->execute([$newState, $id]);

        json_ok([
            'message'   => 'Holat yangilandi',
            'id'        => $id,
            'is_active' => $newState
        ]);
    }

    // DELETE
    if ($action === 'delete') {
        if ($method !== 'POST') {
            json_error('POST bo‘lishi kerak', 405);
        }

        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            json_error('Noto‘g‘ri ID');
        }

        // O'zini o'chirmaslik (hozircha ehtiyot chorasi)
        if (current_user_id() && (int)current_user_id() === $id) {
            json_error('O‘zingizni o‘chirib qo‘yish mumkin emas.');
        }

        $rowStmt = $pdo->prepare("SELECT id, name, login FROM users WHERE id = ?");
        $rowStmt->execute([$id]);
        $row = $rowStmt->fetch();
        if (!$row) {
            json_error('Foydalanuvchi topilmadi', 404);
        }

        try {
            $del = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $del->execute([$id]);
        } catch (PDOException $e) {
            if ($e->getCode() === '23000') {
                json_error(
                    'Bu foydalanuvchi boshqa jadvalda ishlatilgan (masalan, loglarda). O‘chirib bo‘lmaydi.',
                    409
                );
            }
            throw $e;
        }

        json_ok([
            'message' => 'Foydalanuvchi o‘chirildi',
            'id'      => $id,
            'name'    => $row['name'],
            'login'   => $row['login']
        ]);
    }

    json_error('Noto‘g‘ri action', 400);

} catch (Throwable $e) {
    json_error('Server xatosi: ' . $e->getMessage(), 500);
}
