<?php
require_once __DIR__ . '/../config.php';

// JSON javoblar keshlanmasin
header('Cache-Control: no-store');

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

// --- Logout varianti 1: DELETE
if ($method === 'DELETE') {
  unset($_SESSION['user_obj'], $_SESSION['user']);
  json_out(['ok' => true]);
}

// --- Logout varianti 2: GET?action=logout (DELETE bo'lmasa ham ishlasin)
if ($method === 'GET' && $action === 'logout') {
  unset($_SESSION['user_obj'], $_SESSION['user']);
  // API sifatida JSON qaytaramiz; agar sahifa bo‘lsa redirect ham qilishingiz mumkin
  json_out(['ok' => true]);
}

// --- Kim login bo‘lganini tekshirish
if ($method === 'GET') {
  json_out(['user' => current_user()]);
}

// --- Login
if ($method === 'POST') {
  // JSON yoki form-data qabul qilamiz
  $contentType = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
  if (stripos($contentType, 'application/json') !== false) {
    $data = json_decode(file_get_contents('php://input'), true);
  } else {
    // form-urlencoded / multipart fallback
    $data = $_POST;
  }

  // himoya: noto'g'ri JSON bo'lsa ham to'xtamaymiz
  if (!is_array($data)) {
    json_out(['error' => 'Bad request: invalid payload'], 400);
  }

  $username = trim($data['username'] ?? '');
  $password = $data['password'] ?? '';

  if ($username === '' || $password === '') {
    json_out(['error' => 'Login va parol kiritilishi shart'], 400);
  }

  // Foydalanuvchini bazadan topish
  $stmt = contracts_db()->prepare("SELECT * FROM users WHERE username=? LIMIT 1");
  if (!$stmt) {
    json_out(['error' => 'DB error', 'detail' => contracts_db()->error], 500);
  }
  $stmt->bind_param("s", $username);
  $stmt->execute();
  $u = $stmt->get_result()->fetch_assoc();
  $stmt->close();

  // Parolni tekshirish
  if ($u && $password == $u['password_hash']) {
    // Session fixation oldini olish
    if (session_status() === PHP_SESSION_ACTIVE) {
      session_regenerate_id(true);
    }

    $_SESSION['user_obj'] = [
      'id'          => (int)$u['id'],
      'username'    => $u['username'],
      'role'        => $u['role'],          // 'admin' | 'operator'
      'operator_id' => $u['operator_id'] !== null ? (int)$u['operator_id'] : null
    ];

    json_out(['ok' => true, 'user' => $_SESSION['user_obj']]);
  }

  // Noto'g'ri login/parol
  json_out(['error' => 'Login yoki parol xato'], 401);
}

// Bu yerga kelgan bo'lsa, method qo'llanilmagan
json_out(['error' => 'Method not allowed'], 405);
