<?php
error_reporting(0);
$db = new SQLite3('./.adb.db');
$res = $db->query('SELECT * FROM ads'); 
$json_response = array(); 

// Get the protocol (http or https) dynamically
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

// Get the domain of the site
$domain = $_SERVER['HTTP_HOST'];

// Get the current script's directory, considering subdirectories
$scriptPath = dirname($_SERVER['PHP_SELF']);

while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
    $row_array['AdName'] = $row['title']; 
    
    // Form the complete URL, appending '/uploads/' before the stored path, ensuring it's relative to the root
    // Adjust the path according to your needs, especially if 'uploads' is not directly under the root
    // Use rtrim to ensure there are no trailing slashes that could break the URL form
    $fullPath = rtrim($protocol . $domain, '/') . '/magic/' . ltrim($row['url'], '/');

    // Assign the full path to 'AdUrl'
    $row_array['AdUrl'] = $fullPath;

    array_push($json_response, $row_array);  
}

header('Content-type: application/json; charset=UTF-8');
echo json_encode($json_response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>
