<?php
// AJAX handler for generating/revoking API keys
if (session_status() === PHP_SESSION_NONE) session_start();
require_once dirname(__DIR__, 2) . '/include/config.php';

header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized']); exit();
}

$user_id = (int)$_SESSION['user_id'];
$action  = trim($_POST['action'] ?? '');

if ($action === 'generate') {
    // Generate a new API key
    $key = bin2hex(random_bytes(32)); // 64-char hex key

    try {
        $pdo->prepare("UPDATE users SET api_key = :key, api_enabled = 1 WHERE id = :uid")
            ->execute([':key' => $key, ':uid' => $user_id]);

        echo json_encode(['status' => '1', 'msg' => 'API key generated successfully.', 'api_key' => $key]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Error generating key: ' . $e->getMessage()]);
    }
    exit();
}

if ($action === 'revoke') {
    try {
        $pdo->prepare("UPDATE users SET api_key = NULL, api_enabled = 0 WHERE id = :uid")
            ->execute([':uid' => $user_id]);

        echo json_encode(['status' => '1', 'msg' => 'API key revoked successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Error revoking key.']);
    }
    exit();
}

if ($action === 'regenerate') {
    $key = bin2hex(random_bytes(32));

    try {
        $pdo->prepare("UPDATE users SET api_key = :key, api_enabled = 1 WHERE id = :uid")
            ->execute([':key' => $key, ':uid' => $user_id]);

        echo json_encode(['status' => '1', 'msg' => 'API key regenerated. Old key is now invalid.', 'api_key' => $key]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Error regenerating key.']);
    }
    exit();
}

echo json_encode(['status' => '0', 'msg' => 'Invalid action.']);
