<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/db.php';

mocker_admin_require_login();

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

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$adminKind = (string) ($_SESSION['mocker_admin_kind'] ?? 'master');
$adminId = isset($_SESSION['mocker_admin_id']) ? (int) $_SESSION['mocker_admin_id'] : 0;

if ($method === 'GET') {
    if ($adminKind !== 'staff' || $adminId <= 0) {
        $twofa = $pdo->query('SELECT twofa_enabled, twofa_backup_codes_json FROM admin_master_2fa WHERE id = 1 LIMIT 1')->fetch(PDO::FETCH_ASSOC);
        $backupHashes = json_decode((string) (($twofa['twofa_backup_codes_json'] ?? '[]')), true);
        echo json_encode([
            'ok' => true,
            'profile' => [
                'kind' => $adminKind,
                'username' => (string) ($_SESSION['mocker_admin_username'] ?? 'master'),
                'displayName' => (string) ($_SESSION['mocker_admin_display'] ?? 'Master Admin'),
                'editable' => false,
                'passwordEditable' => false,
                'twofaEnabled' => (int) (($twofa['twofa_enabled'] ?? 0)) === 1,
                'twofaBackupCodesCount' => is_array($backupHashes) ? count($backupHashes) : 0,
                'message' => 'Master hesap bilgileri sabit yapıdadır.',
            ],
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $st = $pdo->prepare('SELECT id, username, display_name, twofa_enabled, twofa_backup_codes_json FROM admin_operators WHERE id = :id LIMIT 1');
    $st->execute([':id' => $adminId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $backupHashes = json_decode((string) ($row['twofa_backup_codes_json'] ?? '[]'), true);
    echo json_encode([
        'ok' => true,
        'profile' => [
            'kind' => 'staff',
            'username' => (string) $row['username'],
            'displayName' => (string) $row['display_name'],
            'editable' => true,
            'passwordEditable' => true,
            'twofaEnabled' => (int) ($row['twofa_enabled'] ?? 0) === 1,
            'twofaBackupCodesCount' => is_array($backupHashes) ? count($backupHashes) : 0,
            'message' => '',
        ],
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$action = (string) ($input['action'] ?? '');

if ($adminKind !== 'staff' || $adminId <= 0) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'update_profile') {
    $displayName = trim((string) ($input['displayName'] ?? ''));
    if ($displayName === '' || strlen($displayName) > 200) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'displayName'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $up = $pdo->prepare('UPDATE admin_operators SET display_name = :d, updated_at = :u WHERE id = :id');
    $up->execute([
        ':d' => $displayName,
        ':u' => gmdate('c'),
        ':id' => $adminId,
    ]);
    $_SESSION['mocker_admin_display'] = $displayName;
    echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'update_password') {
    $currentPassword = (string) ($input['currentPassword'] ?? '');
    $newPassword = (string) ($input['newPassword'] ?? '');
    if ($currentPassword === '' || $newPassword === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'password_required'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (strlen($newPassword) < 8) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'password_short'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $st = $pdo->prepare('SELECT password_hash FROM admin_operators WHERE id = :id LIMIT 1');
    $st->execute([':id' => $adminId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row || !password_verify($currentPassword, (string) $row['password_hash'])) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'password_invalid'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $up = $pdo->prepare('UPDATE admin_operators SET password_hash = :h, updated_at = :u WHERE id = :id');
    $up->execute([
        ':h' => password_hash($newPassword, PASSWORD_DEFAULT),
        ':u' => gmdate('c'),
        ':id' => $adminId,
    ]);
    echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'action'], JSON_UNESCAPED_UNICODE);
