<?php
require 'config_pdo.php';
require '../vendor/autoload.php'; // Ensure dependencies are loaded

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use OTPHP\TOTP;

date_default_timezone_set('UTC'); // Set a consistent timezone

header("Content-Type: application/json");

// Function to log messages
function logMessage($message)
{
    file_put_contents("update_secret_log.txt", "[" . date("Y-m-d H:i:s") . "] " . $message . PHP_EOL, FILE_APPEND);
}

// Check for Authorization token
$headers = getallheaders();
if (!isset($headers["Authorization"])) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Token missing"]);
    logMessage("Authorization token missing");
    exit;
}

$token = trim(str_replace("Bearer", "", $headers["Authorization"]));
try {
    $decoded = JWT::decode($token, new Key(JWT_SECRET_KEY, "HS256"));
    $user_id = $decoded->sub;
    logMessage("Token verified for User ID: $user_id");
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Invalid token"]);
    logMessage("Invalid token: " . $e->getMessage());
    exit;
}

// Get app_name from request
$data = json_decode(file_get_contents("php://input"), true);
if (!isset($data["app_name"])) {
    echo json_encode(["status" => "error", "message" => "Missing app_name"]);
    logMessage("Missing app_name in request");
    exit;
}

$app_name = $data["app_name"];
logMessage("Received secret update request - App: $app_name");

// Fetch app from database
$sql = "SELECT secret FROM scanned_auths WHERE user_id = :user_id AND app_name = :app_name";
$stmt = $pdo->prepare($sql);
$stmt->execute(["user_id" => $user_id, "app_name" => $app_name]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    echo json_encode(["status" => "error", "message" => "App not found"]);
    logMessage("App '$app_name' not found for User ID: $user_id");
    exit;
}

// Generate new secret key
$newSecretKey = TOTP::generate()->getSecret();
logMessage("New Secret Key generated for App '$app_name': $newSecretKey");

// Update secret in database
$sql = "UPDATE scanned_auths SET secret = :new_secret WHERE user_id = :user_id AND app_name = :app_name";
$stmt = $pdo->prepare($sql);
$stmt->execute(["new_secret" => $newSecretKey, "user_id" => $user_id, "app_name" => $app_name]);

// Response
echo json_encode(["status" => "success", "message" => "Secret key updated successfully"]);
logMessage("Secret key updated successfully for App: $app_name");
?>
