<?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");

// Debug log file
$logFile = 'delete_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 app_name and OTP from request
$data = json_decode(file_get_contents("php://input"), true);
if (!isset($data["app_name"]) || !isset($data["otp"])) {
    echo json_encode(["status" => "error", "message" => "Missing app_name or OTP"]);
    logMessage("Missing app_name or OTP in request");
    exit;
}

$app_name = $data["app_name"];
$otp = $data["otp"];
logMessage("Received delete request - App: $app_name, OTP: $otp");

// Fetch user's apps count
global $pdo;
$sql = "SELECT COUNT(*) as app_count FROM scanned_auths WHERE user_id = :user_id";
$stmt = $pdo->prepare($sql);
$stmt->execute(["user_id" => $user_id]);
$appCount = $stmt->fetch(PDO::FETCH_ASSOC)["app_count"];

if ($appCount <= 1) {
    echo json_encode(["status" => "error", "message" => "Cannot delete the only app linked to your account"]);
    logMessage("User ID: $user_id attempted to delete the only app");
    exit;
}

// Fetch secret key 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;
}

$secretKey = $row["secret"];
logMessage("Secret Key from DB: " . $secretKey);

// Verify OTP
$totp = TOTP::createFromSecret($secretKey);
if (!$totp->verify($otp, null, 2)) {
    echo json_encode(["status" => "error", "message" => "Invalid OTP"]);
    logMessage("Invalid OTP entered for App: $app_name");
    exit;
}

// Delete app entry
$sql = "DELETE 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]);

echo json_encode(["status" => "success", "message" => "App deleted successfully"]);
logMessage("App '$app_name' deleted successfully for User ID: $user_id");
?>
