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

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

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

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

// Debug log file
$logFile = 'update_debug_log.txt';

// Function to log messages
function logMessage($message)
{
    global $logFile;
    file_put_contents($logFile, "[" . 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 old and new app names from request
$data = json_decode(file_get_contents("php://input"), true);
if (!isset($data["old_app_name"]) || !isset($data["new_app_name"])) {
    echo json_encode(["status" => "error", "message" => "Missing old_app_name or new_app_name"]);
    logMessage("Missing old_app_name or new_app_name in request");
    exit;
}

$old_app_name = $data["old_app_name"];
$new_app_name = $data["new_app_name"];
logMessage("Received update request - Old: $old_app_name, New: $new_app_name");

// Check if old app exists
$sql = "SELECT id FROM scanned_auths WHERE user_id = :user_id AND app_name = :old_app_name";
$stmt = $pdo->prepare($sql);
$stmt->execute(["user_id" => $user_id, "old_app_name" => $old_app_name]);

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

// Check if new app name already exists
$sql = "SELECT id FROM scanned_auths WHERE user_id = :user_id AND app_name = :new_app_name";
$stmt = $pdo->prepare($sql);
$stmt->execute(["user_id" => $user_id, "new_app_name" => $new_app_name]);

if ($stmt->fetch()) {
    echo json_encode(["status" => "error", "message" => "New app name already in use"]);
    logMessage("New app name '$new_app_name' already exists for User ID: $user_id");
    exit;
}

// Update app name
$sql = "UPDATE scanned_auths SET app_name = :new_app_name WHERE user_id = :user_id AND app_name = :old_app_name";
$stmt = $pdo->prepare($sql);
if ($stmt->execute(["user_id" => $user_id, "old_app_name" => $old_app_name, "new_app_name" => $new_app_name])) {
    echo json_encode(["status" => "success", "message" => "App name updated successfully"]);
    logMessage("App name updated successfully: '$old_app_name' -> '$new_app_name'");
} else {
    echo json_encode(["status" => "error", "message" => "Failed to update app name"]);
    logMessage("Failed to update app name for User ID: $user_id");
}

?>
