<?php
/**
 * Authentication API
 * POST /api/auth.php?action=login
 */

require_once 'config.php';

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

if ($method === 'POST' && $action === 'login') {
    $input = getJsonInput();
    
    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        errorResponse('Username dan password harus diisi', 400);
    }
    
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM admins WHERE username = ?");
    $stmt->execute([$username]);
    $admin = $stmt->fetch();
    
    if (!$admin) {
        errorResponse('Username atau password salah', 401);
    }
    
    // Verify password
    if (!password_verify($password, $admin['password_hash'])) {
        errorResponse('Username atau password salah', 401);
    }
    
    // Create JWT token
    $token = createJWT([
        'sub' => $admin['username'],
        'role' => $admin['role'],
        'id' => $admin['id']
    ]);
    
    jsonResponse([
        'access_token' => $token,
        'token_type' => 'bearer'
    ]);
}

// Create first admin (one-time setup)
if ($method === 'POST' && $action === 'create-first-admin') {
    $db = getDB();
    
    // Check if admin exists
    $stmt = $db->query("SELECT COUNT(*) as count FROM admins");
    $result = $stmt->fetch();
    
    if ($result['count'] > 0) {
        errorResponse('Admin sudah ada', 400);
    }
    
    // Create admin
    $id = generateUUID();
    $passwordHash = password_hash('admin123', PASSWORD_BCRYPT);
    
    $stmt = $db->prepare("INSERT INTO admins (id, username, password_hash, role) VALUES (?, ?, ?, ?)");
    $stmt->execute([$id, 'admin', $passwordHash, 'admin']);
    
    jsonResponse([
        'message' => 'Admin berhasil dibuat',
        'username' => 'admin',
        'password' => 'admin123'
    ]);
}

// Verify token
if ($method === 'GET' && $action === 'verify') {
    $payload = requireAuth();
    jsonResponse(['valid' => true, 'user' => $payload['sub']]);
}

errorResponse('Invalid action', 400);
