<?php

function handleGetApiflashScreenshot($method, $urlToScreenshot)
{
    if ($method !== 'GET') {
        http_response_code(405);
        echo json_encode(['message' => 'Method not allowed']);
        return;
    }

    $apiflashAccessKey = 'f7042e9f917049e98d8b4447bc3c3feb';

    $apiflashApiUrl = "https://api.apiflash.com/v1/urltoimage?access_key={$apiflashAccessKey}&url={$urlToScreenshot}&format=png&quality=70&width=1920&height=1080&fresh=true";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiflashApiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);

    $image_data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($http_code === 200 && $image_data !== false) {


        $baseSavePath = __DIR__ . '/websites/';

        // in case it doesn't find the directory
        if (!is_dir($baseSavePath)) {
            if (!mkdir($baseSavePath, 0755, true)) {
                http_response_code(500);
                error_log("Failed to create screenshot directory: " . $baseSavePath);
                echo json_encode(['message' => 'Server error: Could not create screenshot directory.']);
                exit();
            }
        }


        $filename = md5($urlToScreenshot) . '.png';
        $fullSavePath = $baseSavePath . $filename;


        if (file_put_contents($fullSavePath, $image_data) !== false) {
            $publicImageUrl = "https://new.platformacrm.info/new-tool/backend/websites/{$filename}";

            http_response_code(200);
            echo json_encode([
                'message' => 'Screenshot generated and saved successfully.',
                'imageUrl' => $publicImageUrl
            ]);
            exit();
        } else {
            http_response_code(500);
            error_log("Failed to save screenshot file to: " . $fullSavePath);
            echo json_encode(['message' => 'Server error: Failed to save screenshot file.']);
            exit();
        }

    } else {
        http_response_code(500);
        error_log("Apiflash API Error (HTTP {$http_code}): " . $curl_error);
        echo json_encode(['message' => 'Failed to fetch screenshot from Apiflash API.', 'error' => $curl_error]);
        exit();
    }
}

?>