<?php
// image-proxy.php
// Proxies images from BDRIS using ProxyHelper to ensure cookies are sent
require_once 'includes/ProxyHelper.php';

$urlParam = $_GET['url'] ?? '';
$id = $_GET['id'] ?? '';

if (!$id && !$urlParam) {
    header("HTTP/1.1 400 Bad Request");
    exit;
}

$cacheDir = __DIR__ . '/cache/images';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0777, true);
}
$cacheKey = $id ? preg_replace('/[^a-zA-Z0-9_-]/', '', $id) : md5($urlParam);
$cacheFile = $cacheDir . '/' . $cacheKey;

if (file_exists($cacheFile) && filesize($cacheFile) > 0) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $contentType = finfo_file($finfo, $cacheFile);
    finfo_close($finfo);
    
    if (!$contentType || $contentType === 'application/x-empty') {
        $contentType = 'image/jpeg';
    }
    header("Content-Type: $contentType");
    header("Cache-Control: public, max-age=86400");
    readfile($cacheFile);
    exit;
}

$proxy = new ProxyHelper();

if ($urlParam) {
    $remoteUrl = $urlParam;
    if (strpos($remoteUrl, '//') === 0) {
        $remoteUrl = 'https:' . $remoteUrl;
    } elseif (strpos($remoteUrl, '/') === 0) {
        $remoteUrl = 'https://bdris.gov.bd' . $remoteUrl;
    }

    $response = $proxy->fetch($remoteUrl, 'GET', [], false, 'https://bdris.gov.bd/');
    if (($response['status'] ?? 0) === 200) {
        $body = $response['body'] ?? '';
        if ($body !== '' &&
            stripos($body, '<title>Login</title>') === false &&
            stripos($body, 'login-page') === false &&
            stripos($body, 'Page not found') === false &&
            stripos($body, '<html') === false) {
            $contentType = 'image/jpeg';
            if (substr($body, 0, 4) === '%PDF') {
                $contentType = 'application/pdf';
            } elseif (substr($body, 0, 3) === "\xFF\xD8\xFF") {
                $contentType = 'image/jpeg';
            } elseif (substr($body, 0, 4) === "\x89PNG") {
                $contentType = 'image/png';
            }
            @file_put_contents($cacheFile, $body);
            header("Content-Type: $contentType");
            header("Cache-Control: public, max-age=86400");
            echo $body;
            exit;
        }
    }
}

if ($id) {
    $urls = [
        // Primary: application attachment endpoint (used in print-application.php)
        'https://bdris.gov.bd/api/br/application/attachment/' . urlencode($id),
        // Fallbacks
        'https://bdris.gov.bd/api/br/attachment/content/' . urlencode($id),
        'https://bdris.gov.bd/br/attachment/content/' . urlencode($id),
        'https://bdris.gov.bd/api/attachment/content/' . urlencode($id),
        'https://bdris.gov.bd/api/dr/attachment/content/' . urlencode($id),
        'https://bdris.gov.bd/dr/attachment/content/' . urlencode($id),
        'https://bdris.gov.bd/api/br/attachment/preview/' . urlencode($id),
        'https://bdris.gov.bd/br/attachment/preview/' . urlencode($id),
        'https://bdris.gov.bd/api/attachment/preview/' . urlencode($id),
        'https://bdris.gov.bd/api/dr/attachment/preview/' . urlencode($id),
        'https://bdris.gov.bd/dr/attachment/preview/' . urlencode($id),
        'https://bdris.gov.bd/attachment/preview/' . urlencode($id)
    ];

    $attachReferer = 'https://bdris.gov.bd/admin/br/applications/search';
    // Load active office token for referer
    $officeFile = $proxy->getActiveOfficeFile();
    if (file_exists($officeFile)) {
        $oTok = trim(file_get_contents($officeFile));
        if ($oTok !== '') $attachReferer = 'https://bdris.gov.bd/admin/br/applications/search?data=' . urlencode($oTok);
    }
    $attachHeaders = ['client: bris', 'Accept: image/*, application/pdf, */*', 'X-Requested-With: XMLHttpRequest'];

    foreach ($urls as $url) {
        $response = $proxy->fetch($url, 'GET', [], false, $attachReferer, $attachHeaders);
        
        if (($response['status'] ?? 0) === 200) {
            $body = $response['body'] ?? '';

            if ($body === '') {
                continue;
            }

            if (stripos($body, '<title>Login</title>') !== false ||
                stripos($body, 'login-page') !== false ||
                stripos($body, 'Page not found') !== false ||
                stripos($body, '<html') !== false) {
                continue;
            }

            $contentType = 'image/jpeg';
            
            if (substr($body, 0, 4) === '%PDF') {
                $contentType = 'application/pdf';
            } elseif (substr($body, 0, 3) === "\xFF\xD8\xFF") {
                $contentType = 'image/jpeg';
            } elseif (substr($body, 0, 4) === "\x89PNG") {
                $contentType = 'image/png';
            }
            
            @file_put_contents($cacheFile, $body);
            header("Content-Type: $contentType");
            header("Cache-Control: public, max-age=86400");
            echo $body;
            exit;
        }
    }

    $docPageUrl = 'https://bdris.gov.bd/admin/doc/' . urlencode($id);
    $docResp = $proxy->fetch($docPageUrl, 'GET', [], false, 'https://bdris.gov.bd/admin/');
    if (($docResp['status'] ?? 0) === 200) {
        $docBody = $docResp['body'] ?? '';
        if ($docBody !== '' &&
            stripos($docBody, '<title>Login</title>') === false &&
            stripos($docBody, 'login-page') === false &&
            stripos($docBody, 'Page not found') === false) {
            
            if (stripos($docBody, '<img') !== false) {
                if (preg_match('~<img[^>]+src="([^"]+)"~i', $docBody, $m)) {
                    $imgUrl = $m[1];
                    if (strpos($imgUrl, '//') === 0) {
                        $imgUrl = 'https:' . $imgUrl;
                    } elseif (strpos($imgUrl, '/') === 0) {
                        $imgUrl = 'https://bdris.gov.bd' . $imgUrl;
                    }
                    $imgResp = $proxy->fetch($imgUrl, 'GET', [], false, 'https://bdris.gov.bd/');
                    if (($imgResp['status'] ?? 0) === 200) {
                        $imgBody = $imgResp['body'] ?? '';
                        if ($imgBody !== '') {
                            $contentType = 'image/jpeg';
                            if (substr($imgBody, 0, 4) === '%PDF') {
                                $contentType = 'application/pdf';
                            } elseif (substr($imgBody, 0, 3) === "\xFF\xD8\xFF") {
                                $contentType = 'image/jpeg';
                            } elseif (substr($imgBody, 0, 4) === "\x89PNG") {
                                $contentType = 'image/png';
                            }
                            @file_put_contents($cacheFile, $imgBody);
                            header("Content-Type: $contentType");
                            header("Cache-Control: public, max-age=86400");
                            echo $imgBody;
                            exit;
                        }
                    }
                }
            } else {
                $contentType = 'image/jpeg';
                if (substr($docBody, 0, 4) === '%PDF') {
                    $contentType = 'application/pdf';
                } elseif (substr($docBody, 0, 3) === "\xFF\xD8\xFF") {
                    $contentType = 'image/jpeg';
                } elseif (substr($docBody, 0, 4) === "\x89PNG") {
                    $contentType = 'image/png';
                }
                @file_put_contents($cacheFile, $docBody);
                header("Content-Type: $contentType");
                header("Cache-Control: public, max-age=86400");
                echo $docBody;
                exit;
            }
        }
    }
}

header("HTTP/1.1 404 Not Found");
echo "Image not found";
