<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';
if (!$CAN_VIEW) { http_response_code(403); echo "<h1>Access Denied</h1>"; exit; }

/* User-provided file finder adapted to admin area */

/*
|--------------------------------------------------------------------------
| Private Search Downloader - Single PHP File
|--------------------------------------------------------------------------
| Features
| - Private login
| - Brave API primary search
| - Modes: web, image, video, audio
| - Fallbacks:
|     * Internet Archive
|     * Wikimedia Commons (image mode)
|     * Freesound (audio mode)
| - Select results, then download chosen files
| - Extension allowlist
| - Domain allowlist (optional)
| - Basic logging
|--------------------------------------------------------------------------
| REQUIREMENTS
| - PHP with cURL enabled
| - Write permission to download_dir
|--------------------------------------------------------------------------
*/

$config = [
    'username' => 'admin',
    'password' => 'change_this_password_now',

    // API keys
    'brave_api_key'     => 'PUT_BRAVE_API_KEY_HERE',
    'freesound_api_key' => 'PUT_FREESOUND_API_KEY_HERE',

    // Feature toggles
    'enable_internet_archive'   => true,
    'enable_wikimedia_commons'  => true,
    'enable_freesound'          => true,

    // Storage
    'download_dir' => __DIR__ . '/downloads',
    'log_file'     => __DIR__ . '/downloads/download-log.txt',

    // Network
    'request_timeout' => 25,
    'user_agent'      => 'PrivateSearchDownloader/1.0',
    'max_results'     => 20,
    'max_download_size_mb' => 500,

    // Empty array means allow any public host
    'allowed_domains' => [
        // 'archive.org',
        // 'upload.wikimedia.org',
        // 'freesound.org',
    ],

    // Allowed file extensions
    'allowed_extensions' => [
        // images
        'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg',

        // audio
        'mp3', 'wav', 'ogg', 'aac', 'flac', 'm4a',

        // video
        'mp4', 'm4v', 'webm', 'mov', 'avi', 'mkv', 'wmv', 'flv',

        // docs / archives
        'pdf', 'zip', 'rar', '7z', 'txt', 'csv', 'json'
    ],
];

if (!is_dir($config['download_dir'])) {
    @mkdir($config['download_dir'], 0755, true);
}

if (!empty($_SESSION['file_finder_logged_in'])) {
    $_SESSION['private_search_logged_in'] = true;
}

function esc($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function isLoggedIn() {
    return true;
}

function doLogout() {
    if (isset($_GET['logout'])) {
        session_destroy();
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    }
}

function handleLogin($config) {
    $error = null;

    if (isset($_POST['login_action'])) {
        $user = trim($_POST['username'] ?? '');
        $pass = trim($_POST['password'] ?? '');

        if ($user === $config['username'] && $pass === $config['password']) {
            $_SESSION['private_search_logged_in'] = true;
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $error = 'Invalid username or password.';
        }
    }

    return $error;
}

function normalizeUrl($url) {
    $url = trim((string)$url);
    if ($url === '') return false;
    if (!filter_var($url, FILTER_VALIDATE_URL)) return false;

    $parts = parse_url($url);
    if (!$parts || empty($parts['scheme']) || empty($parts['host'])) return false;

    $scheme = strtolower($parts['scheme']);
    if (!in_array($scheme, ['http', 'https'], true)) return false;

    return $url;
}

function hostAllowed($url, array $allowedDomains) {
    if (empty($allowedDomains)) {
        return true;
    }

    $host = strtolower((string)parse_url($url, PHP_URL_HOST));
    if ($host === '') return false;

    foreach ($allowedDomains as $domain) {
        $domain = strtolower(trim($domain));
        if ($domain === '') continue;
        if ($host === $domain || str_ends_with($host, '.' . $domain)) {
            return true;
        }
    }

    return false;
}

function getExtensionFromUrl($url) {
    $path = (string)parse_url($url, PHP_URL_PATH);
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    return $ext ?: '';
}

function extensionAllowed($url, array $allowedExtensions) {
    $ext = getExtensionFromUrl($url);
    if ($ext === '') return false;
    return in_array($ext, $allowedExtensions, true);
}

function safeFilenameFromUrl($url) {
    $path = (string)parse_url($url, PHP_URL_PATH);
    $filename = basename($path);

    if ($filename === '' || $filename === '/' || $filename === '.') {
        $filename = 'file_' . date('Ymd_His');
    }

    $filename = preg_replace('/[^A-Za-z0-9._-]/', '_', $filename);

    if (strlen($filename) > 180) {
        $ext  = pathinfo($filename, PATHINFO_EXTENSION);
        $name = pathinfo($filename, PATHINFO_FILENAME);
        $name = substr($name, 0, 160);
        $filename = $ext ? ($name . '.' . $ext) : $name;
    }

    return $filename;
}

function logLine($file, $line) {
    @file_put_contents($file, '[' . date('Y-m-d H:i:s') . '] ' . $line . PHP_EOL, FILE_APPEND);
}

function httpRequest($url, $userAgent, $timeout, $extraHeaders = [], $method = 'GET') {
    $ch = curl_init($url);

    $headers = array_merge([
        'User-Agent: ' . $userAgent,
        'Accept: */*'
    ], $extraHeaders);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_HEADER => true,
        CURLOPT_CUSTOMREQUEST => $method,
    ]);

    if (strtoupper($method) === 'HEAD') {
        curl_setopt($ch, CURLOPT_NOBODY, true);
    }

    $raw = curl_exec($ch);
    $err = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    if ($raw === false) {
        return ['ok' => false, 'error' => $err];
    }

    $headerSize = $info['header_size'] ?? 0;
    $headerText = substr($raw, 0, $headerSize);
    $body = substr($raw, $headerSize);

    return [
        'ok' => true,
        'status' => $info['http_code'] ?? 0,
        'content_type' => $info['content_type'] ?? '',
        'final_url' => $info['url'] ?? $url,
        'headers_raw' => $headerText,
        'body' => $body,
        'download_size' => strlen($body),
    ];
}

function parseHeaderValue($headersRaw, $headerName) {
    $lines = preg_split("/\r\n|\n|\r/", (string)$headersRaw);
    foreach ($lines as $line) {
        if (stripos($line, $headerName . ':') === 0) {
            return trim(substr($line, strlen($headerName) + 1));
        }
    }
    return '';
}

function dedupeResults(array $results) {
    $seen = [];
    $out = [];

    foreach ($results as $row) {
        $url = trim((string)($row['url'] ?? ''));
        if ($url === '') continue;
        if (isset($seen[$url])) continue;
        $seen[$url] = true;
        $out[] = $row;
    }

    return $out;
}

function braveHeaders($config) {
    return [
        'X-Subscription-Token: ' . $config['brave_api_key'],
        'Accept: application/json'
    ];
}

function searchBraveWeb($query, $config) {
    if (empty($config['brave_api_key']) || str_contains($config['brave_api_key'], 'PUT_')) {
        return ['ok' => false, 'error' => 'Brave API key not configured.', 'results' => []];
    }

    $url = 'https://api.search.brave.com/res/v1/web/search?q=' . rawurlencode($query)
         . '&count=' . (int)$config['max_results'];

    $response = httpRequest($url, $config['user_agent'], $config['request_timeout'], braveHeaders($config));

    if (!$response['ok']) {
        return ['ok' => false, 'error' => 'Brave web request failed: ' . $response['error'], 'results' => []];
    }

    if (($response['status'] ?? 0) >= 400) {
        return ['ok' => false, 'error' => 'Brave web HTTP ' . $response['status'], 'results' => []];
    }

    $json = json_decode($response['body'], true);
    $rows = $json['web']['results'] ?? [];
    $items = [];

    foreach ($rows as $row) {
        $items[] = [
            'title'       => $row['title'] ?? '',
            'url'         => $row['url'] ?? '',
            'source'      => parse_url($row['url'] ?? '', PHP_URL_HOST) ?: '',
            'description' => $row['description'] ?? '',
            'mode'        => 'web',
        ];
    }

    return ['ok' => true, 'results' => $items];
}

function searchBraveImages($query, $config) {
    if (empty($config['brave_api_key']) || str_contains($config['brave_api_key'], 'PUT_')) {
        return ['ok' => false, 'error' => 'Brave API key not configured.', 'results' => []];
    }

    $url = 'https://api.search.brave.com/res/v1/images/search?q=' . rawurlencode($query)
         . '&count=' . (int)$config['max_results'];

    $response = httpRequest($url, $config['user_agent'], $config['request_timeout'], braveHeaders($config));

    if (!$response['ok']) {
        return ['ok' => false, 'error' => 'Brave image request failed: ' . $response['error'], 'results' => []];
    }

    if (($response['status'] ?? 0) >= 400) {
        return ['ok' => false, 'error' => 'Brave images HTTP ' . $response['status'], 'results' => []];
    }

    $json = json_decode($response['body'], true);
    $rows = $json['results'] ?? [];
    $items = [];

    foreach ($rows as $row) {
        $imgUrl  = $row['properties']['url'] ?? ($row['url'] ?? '');
        $pageUrl = $row['source_url'] ?? ($row['page_fetched'] ?? $imgUrl);

        $items[] = [
            'title'       => $row['title'] ?? 'Image result',
            'url'         => $imgUrl,
            'source'      => parse_url($pageUrl, PHP_URL_HOST) ?: '',
            'description' => $pageUrl,
            'mode'        => 'image',
        ];
    }

    return ['ok' => true, 'results' => $items];
}

function searchBraveVideos($query, $config) {
    if (empty($config['brave_api_key']) || str_contains($config['brave_api_key'], 'PUT_')) {
        return ['ok' => false, 'error' => 'Brave API key not configured.', 'results' => []];
    }

    $url = 'https://api.search.brave.com/res/v1/videos/search?q=' . rawurlencode($query)
         . '&count=' . (int)$config['max_results'];

    $response = httpRequest($url, $config['user_agent'], $config['request_timeout'], braveHeaders($config));

    if (!$response['ok']) {
        return ['ok' => false, 'error' => 'Brave video request failed: ' . $response['error'], 'results' => []];
    }

    if (($response['status'] ?? 0) >= 400) {
        return ['ok' => false, 'error' => 'Brave video HTTP ' . $response['status'], 'results' => []];
    }

    $json = json_decode($response['body'], true);
    $rows = $json['results'] ?? [];
    $items = [];

    foreach ($rows as $row) {
        $items[] = [
            'title'       => $row['title'] ?? '',
            'url'         => $row['url'] ?? '',
            'source'      => parse_url($row['url'] ?? '', PHP_URL_HOST) ?: '',
            'description' => $row['description'] ?? '',
            'mode'        => 'video',
        ];
    }

    return ['ok' => true, 'results' => $items];
}

function searchInternetArchive($query, $mediaType, $config) {
    $q = '(' . $query . ')';

    if ($mediaType === 'audio') {
        $q .= ' AND mediatype:(audio)';
    } elseif ($mediaType === 'video') {
        $q .= ' AND mediatype:(movies)';
    } elseif ($mediaType === 'image') {
        $q .= ' AND mediatype:(image)';
    }

    $url = 'https://archive.org/advancedsearch.php?q=' . rawurlencode($q)
         . '&fl[]=identifier&fl[]=title&fl[]=mediatype'
         . '&rows=' . (int)$config['max_results']
         . '&page=1&output=json';

    $response = httpRequest($url, $config['user_agent'], $config['request_timeout']);

    if (!$response['ok']) {
        return ['ok' => false, 'error' => 'Internet Archive search failed: ' . $response['error'], 'results' => []];
    }

    if (($response['status'] ?? 0) >= 400) {
        return ['ok' => false, 'error' => 'Internet Archive HTTP ' . $response['status'], 'results' => []];
    }

    $json = json_decode($response['body'], true);
    $docs = $json['response']['docs'] ?? [];
    $items = [];

    foreach ($docs as $doc) {
        $identifier = $doc['identifier'] ?? '';
        if ($identifier === '') continue;

        $metaUrl = 'https://archive.org/metadata/' . rawurlencode($identifier);
        $metaResponse = httpRequest($metaUrl, $config['user_agent'], $config['request_timeout']);
        if (!$metaResponse['ok'] || ($metaResponse['status'] ?? 0) >= 400) {
            continue;
        }

        $metaJson = json_decode($metaResponse['body'], true);
        $files = $metaJson['files'] ?? [];
        $title = $doc['title'] ?? $identifier;

        foreach ($files as $file) {
            $name = $file['name'] ?? '';
            if ($name === '') continue;

            $directUrl = 'https://archive.org/download/' . rawurlencode($identifier) . '/' . str_replace('%2F', '/', rawurlencode($name));

            $items[] = [
                'title'       => $title . ' - ' . $name,
                'url'         => $directUrl,
                'source'      => 'archive.org',
                'description' => 'Internet Archive',
                'mode'        => $mediaType,
            ];
        }
    }

    return ['ok' => true, 'results' => $items];
}

function searchWikimediaCommons($query, $config) {
    $url = 'https://commons.wikimedia.org/w/api.php?action=query&generator=search'
         . '&gsrsearch=' . rawurlencode($query)
         . '&gsrnamespace=6'
         . '&gsrlimit=' . (int)$config['max_results']
         . '&prop=imageinfo'
         . '&iiprop=url'
         . '&format=json';

    $response = httpRequest($url, $config['user_agent'], $config['request_timeout']);

    if (!$response['ok']) {
        return ['ok' => false, 'error' => 'Wikimedia Commons request failed: ' . $response['error'], 'results' => []];
    }

    if (($response['status'] ?? 0) >= 400) {
        return ['ok' => false, 'error' => 'Wikimedia Commons HTTP ' . $response['status'], 'results' => []];
    }

    $json = json_decode($response['body'], true);
    $pages = $json['query']['pages'] ?? [];
    $items = [];

    foreach ($pages as $page) {
        $title = $page['title'] ?? 'Commons image';
        $imgUrl = $page['imageinfo'][0]['url'] ?? '';
        if ($imgUrl === '') continue;

        $items[] = [
            'title'       => $title,
            'url'         => $imgUrl,
            'source'      => 'upload.wikimedia.org',
            'description' => 'Wikimedia Commons',
            'mode'        => 'image',
        ];
    }

    return ['ok' => true, 'results' => $items];
}

function searchFreesound($query, $config) {
    if (empty($config['freesound_api_key']) || str_contains($config['freesound_api_key'], 'PUT_')) {
        return ['ok' => false, 'error' => 'Freesound API key not configured.', 'results' => []];
    }

    $url = 'https://freesound.org/apiv2/search/text/?query=' . rawurlencode($query)
         . '&page_size=' . (int)$config['max_results'];

    $response = httpRequest(
        $url,
        $config['user_agent'],
        $config['request_timeout'],
        [
            'Authorization: Token ' . $config['freesound_api_key'],
            'Accept: application/json'
        ]
    );

    if (!$response['ok']) {
        return ['ok' => false, 'error' => 'Freesound request failed: ' . $response['error'], 'results' => []];
    }

    if (($response['status'] ?? 0) >= 400) {
        return ['ok' => false, 'error' => 'Freesound HTTP ' . $response['status'], 'results' => []];
    }

    $json = json_decode($response['body'], true);
    $rows = $json['results'] ?? [];
    $items = [];

    foreach ($rows as $row) {
        $preview = $row['previews']['preview-hq-mp3']
            ?? $row['previews']['preview-lq-mp3']
            ?? '';

        if ($preview === '') continue;

        $items[] = [
            'title'       => $row['name'] ?? 'Sound',
            'url'         => $preview,
            'source'      => 'freesound.org',
            'description' => implode(', ', $row['tags'] ?? []),
            'mode'        => 'audio',
        ];
    }

    return ['ok' => true, 'results' => $items];
}

function searchByMode($query, $mode, $config) {
    $results = [];

    if ($mode === 'web') {
        return searchBraveWeb($query, $config);
    }

    if ($mode === 'image') {
        $brave = searchBraveImages($query, $config);
        if (!empty($brave['ok'])) {
            $results = array_merge($results, $brave['results']);
        }

        if (!empty($config['enable_wikimedia_commons'])) {
            $commons = searchWikimediaCommons($query, $config);
            if (!empty($commons['ok'])) {
                $results = array_merge($results, $commons['results']);
            }
        }

        return ['ok' => true, 'results' => dedupeResults($results)];
    }

    if ($mode === 'video') {
        $brave = searchBraveVideos($query, $config);
        if (!empty($brave['ok'])) {
            $results = array_merge($results, $brave['results']);
        }

        if (!empty($config['enable_internet_archive'])) {
            $ia = searchInternetArchive($query, 'video', $config);
            if (!empty($ia['ok'])) {
                $results = array_merge($results, $ia['results']);
            }
        }

        return ['ok' => true, 'results' => dedupeResults($results)];
    }

    if ($mode === 'audio') {
        $brave = searchBraveWeb($query . ' mp3 OR wav OR flac OR m4a OR ogg', $config);
        if (!empty($brave['ok'])) {
            $results = array_merge($results, $brave['results']);
        }

        if (!empty($config['enable_internet_archive'])) {
            $ia = searchInternetArchive($query, 'audio', $config);
            if (!empty($ia['ok'])) {
                $results = array_merge($results, $ia['results']);
            }
        }

        if (!empty($config['enable_freesound'])) {
            $fs = searchFreesound($query, $config);
            if (!empty($fs['ok'])) {
                $results = array_merge($results, $fs['results']);
            }
        }

        return ['ok' => true, 'results' => dedupeResults($results)];
    }

    return ['ok' => false, 'error' => 'Unknown mode.', 'results' => []];
}

function inspectUrlForDownload($url, $config) {
    $url = normalizeUrl($url);
    if (!$url) {
        return ['ok' => false, 'message' => 'Invalid URL'];
    }

    if (!hostAllowed($url, $config['allowed_domains'])) {
        return ['ok' => false, 'message' => 'Domain blocked'];
    }

    if (!extensionAllowed($url, $config['allowed_extensions'])) {
        return ['ok' => false, 'message' => 'Extension blocked'];
    }

    $head = httpRequest($url, $config['user_agent'], $config['request_timeout'], [], 'HEAD');
    if (!$head['ok']) {
        return ['ok' => false, 'message' => 'HEAD failed: ' . $head['error']];
    }

    $finalUrl = normalizeUrl($head['final_url'] ?? $url);
    if (!$finalUrl) {
        return ['ok' => false, 'message' => 'Redirect invalid'];
    }

    if (!hostAllowed($finalUrl, $config['allowed_domains'])) {
        return ['ok' => false, 'message' => 'Redirected to blocked domain'];
    }

    if (!extensionAllowed($finalUrl, $config['allowed_extensions'])) {
        return ['ok' => false, 'message' => 'Redirected to blocked extension'];
    }

    $contentLength = parseHeaderValue($head['headers_raw'] ?? '', 'Content-Length');
    $sizeBytes = is_numeric($contentLength) ? (int)$contentLength : 0;
    $maxBytes = (int)$config['max_download_size_mb'] * 1024 * 1024;

    if ($sizeBytes > 0 && $sizeBytes > $maxBytes) {
        return ['ok' => false, 'message' => 'Too large'];
    }

    return [
        'ok' => true,
        'message' => 'Ready',
        'final_url' => $finalUrl,
        'content_type' => $head['content_type'] ?? '',
        'size_bytes' => $sizeBytes,
    ];
}

function downloadFile($url, $config) {
    $check = inspectUrlForDownload($url, $config);
    if (!$check['ok']) {
        return ['success' => false, 'message' => $check['message']];
    }

    $finalUrl = $check['final_url'];
    $response = httpRequest($finalUrl, $config['user_agent'], $config['request_timeout']);

    if (!$response['ok']) {
        return ['success' => false, 'message' => 'Download failed: ' . $response['error']];
    }

    if (($response['status'] ?? 0) >= 400) {
        return ['success' => false, 'message' => 'HTTP ' . $response['status']];
    }

    $sizeBytes = (int)($response['download_size'] ?? 0);
    $maxBytes = (int)$config['max_download_size_mb'] * 1024 * 1024;
    if ($sizeBytes > $maxBytes) {
        return ['success' => false, 'message' => 'Downloaded file exceeded max size'];
    }

    $filename = safeFilenameFromUrl($finalUrl);
    $savePath = rtrim($config['download_dir'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;

    if (file_exists($savePath)) {
        $filename = time() . '_' . $filename;
        $savePath = rtrim($config['download_dir'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;
    }

    $written = @file_put_contents($savePath, $response['body']);
    if ($written === false) {
        return ['success' => false, 'message' => 'Failed to save file'];
    }

    logLine($config['log_file'], 'Downloaded: ' . $finalUrl . ' -> ' . $filename);

    return [
        'success' => true,
        'message' => 'Downloaded',
        'filename' => $filename,
        'size_bytes' => $written,
    ];
}

// Uses main admin login; no extra file-finder login required.
$loginError = null;

$searchError = '';
$searchResults = [];
$downloadResults = [];

if (isLoggedIn() && isset($_POST['search_action'])) {
    $query = trim($_POST['query'] ?? '');
    $mode  = trim($_POST['search_mode'] ?? 'web');

    if ($query === '') {
        $searchError = 'Enter a search term.';
    } else {
        $search = searchByMode($query, $mode, $config);

        if (!$search['ok']) {
            $searchError = $search['error'] ?? 'Search failed.';
        } else {
            foreach ($search['results'] as $row) {
                $url = normalizeUrl($row['url'] ?? '');
                if (!$url) continue;

                $inspect = inspectUrlForDownload($url, $config);

                $searchResults[] = [
                    'title'          => $row['title'] ?? '',
                    'url'            => $url,
                    'source'         => $row['source'] ?? '',
                    'description'    => $row['description'] ?? '',
                    'mode'           => $row['mode'] ?? $mode,
                    'can_download'   => $inspect['ok'],
                    'inspect_message'=> $inspect['message'] ?? '',
                    'size_bytes'     => $inspect['size_bytes'] ?? 0,
                    'content_type'   => $inspect['content_type'] ?? '',
                ];
            }

            $_SESSION['last_search_results'] = $searchResults;
            $_SESSION['last_search_query']   = $query;
            $_SESSION['last_search_mode']    = $mode;
        }
    }
}

if (isLoggedIn() && isset($_POST['download_action'])) {
    $storedResults = $_SESSION['last_search_results'] ?? [];
    $selectedUrls = $_POST['selected_urls'] ?? [];

    if (!is_array($selectedUrls) || empty($selectedUrls)) {
        $downloadResults[] = [
            'url' => '',
            'status' => 'Skipped',
            'message' => 'No items selected',
            'filename' => ''
        ];
    } else {
        $allowed = [];
        foreach ($storedResults as $row) {
            if (!empty($row['url'])) {
                $allowed[$row['url']] = true;
            }
        }

        foreach ($selectedUrls as $url) {
            $url = trim((string)$url);

            if (!isset($allowed[$url])) {
                $downloadResults[] = [
                    'url' => $url,
                    'status' => 'Blocked',
                    'message' => 'Not from current results',
                    'filename' => ''
                ];
                continue;
            }

            $download = downloadFile($url, $config);
            $downloadResults[] = [
                'url' => $url,
                'status' => $download['success'] ? 'Downloaded' : 'Failed',
                'message' => $download['message'],
                'filename' => $download['filename'] ?? ''
            ];
        }
    }

    $searchResults = $_SESSION['last_search_results'] ?? [];
}

if (isLoggedIn() && empty($searchResults)) {
    $searchResults = $_SESSION['last_search_results'] ?? [];
}

$currentQuery = $_SESSION['last_search_query'] ?? '';
$currentMode  = $_SESSION['last_search_mode'] ?? 'web';
?>
<?php $pageTitle = "File Finder — Smurfette's Country Delights"; $pageClass='page-admin'; include __DIR__ . '/includes/admin_header.php'; ?>
<style>body.page-admin .finder-table{width:100%;border-collapse:collapse;margin-top:15px;}body.page-admin .finder-table th,body.page-admin .finder-table td{border:1px solid rgba(255,215,120,.18);padding:10px;text-align:left;vertical-align:top;}body.page-admin .finder-table th{background:rgba(255,255,255,.04);}body.page-admin .finder-muted{opacity:.75;}body.page-admin .finder-grid{display:grid;grid-template-columns:1fr 220px;gap:14px;}@media(max-width:800px){body.page-admin .finder-grid{grid-template-columns:1fr;}}</style>
<section class="content-card"> 
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;"><div><h1 class="admin-title" style="margin:0;">🗂️ File Finder</h1><div class="finder-muted">Private search and downloader adapted from your supplied PHP script.</div></div><a class="admin-btn" href="/admin/index.php">Back</a></div>

<?php if (false): ?>
    <h1>Private Search Downloader</h1>
    <p class="finder-muted">Login required.</p>

    <?php if ($loginError): ?>
        <div class="error"><?= esc($loginError) ?></div>
    <?php endif; ?>

    <div class="content-card" style="text-align:left;margin-top:16px;">
        <form method="post">
            <input type="hidden" name="login_action" value="1">

            <label>Username</label>
            <input type="text" name="username" required>

            <label>Password</label>
            <input type="password" name="password" required>

            <button type="submit">Login</button>
        </form>
    </div>

<?php else: ?>
    <div class="topbar">
        <div>
            <h1>Private Search Downloader</h1>
            <div class="finder-muted">
                Primary engine: Brave<br>
                Fallbacks: Internet Archive, Wikimedia Commons, Freesound<br>
                Max file size: <?= (int)$config['max_download_size_mb'] ?> MB
            </div>
        </div>
        <div><a href="?logout=1">Logout</a></div>
    </div>

    <div class="content-card" style="text-align:left;margin-top:16px;">
        <h2>Search</h2>
        <form method="post">
            <input type="hidden" name="search_action" value="1">

            <div class="finder-grid">
                <div>
                    <label>Search query</label>
                    <input
                        type="text"
                        name="query"
                        value="<?= esc($currentQuery) ?>"
                        placeholder="example: old time radio, train documentary, vintage posters"
                        required
                    >
                </div>
                <div>
                    <label>Mode</label>
                    <select name="search_mode">
                        <option value="web"   <?= $currentMode === 'web'   ? 'selected' : '' ?>>Web</option>
                        <option value="image" <?= $currentMode === 'image' ? 'selected' : '' ?>>Image only</option>
                        <option value="video" <?= $currentMode === 'video' ? 'selected' : '' ?>>Video only</option>
                        <option value="audio" <?= $currentMode === 'audio' ? 'selected' : '' ?>>Audio only</option>
                    </select>
                </div>
            </div>

            <button type="submit">Search</button>
        </form>

        <?php if ($searchError): ?>
            <div class="error"><?= esc($searchError) ?></div>
        <?php endif; ?>
    </div>

    <?php if (!empty($searchResults)): ?>
        <div class="content-card" style="text-align:left;margin-top:16px;">
            <h2>Results</h2>

            <form method="post">
                <input type="hidden" name="download_action" value="1">

                <table class="finder-table">
                    <thead>
                        <tr>
                            <th>Select</th>
                            <th>Title / URL</th>
                            <th>Source</th>
                            <th>Info</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($searchResults as $row): ?>
                        <tr>
                            <td>
                                <?php if (!empty($row['can_download'])): ?>
                                    <input type="checkbox" name="selected_urls[]" value="<?= esc($row['url']) ?>">
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?= esc($row['title']) ?></strong><br>
                                <a href="<?= esc($row['url']) ?>" target="_blank"><?= esc($row['url']) ?></a><br>
                                <span class="muted"><?= esc($row['description']) ?></span>
                            </td>
                            <td><?= esc($row['source']) ?></td>
                            <td>
                                Mode: <?= esc($row['mode']) ?><br>
                                Type: <?= esc($row['content_type'] ?: 'unknown') ?><br>
                                Size: <?= !empty($row['size_bytes']) ? esc(number_format((int)$row['size_bytes'])) . ' bytes' : 'unknown' ?>
                            </td>
                            <td class="<?= !empty($row['can_download']) ? 'ok' : 'warn' ?>">
                                <?= esc($row['inspect_message']) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>

                <p style="margin-top:16px;">
                    <button type="submit">Download Selected</button>
                </p>
            </form>
        </div>
    <?php endif; ?>

    <?php if (!empty($downloadResults)): ?>
        <div class="content-card" style="text-align:left;margin-top:16px;">
            <h2>Download Results</h2>
            <table class="finder-table">
                <thead>
                    <tr>
                        <th>URL</th>
                        <th>Status</th>
                        <th>Message</th>
                        <th>Saved File</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($downloadResults as $row): ?>
                    <tr>
                        <td>
                            <?php if (!empty($row['url'])): ?>
                                <a href="<?= esc($row['url']) ?>" target="_blank"><?= esc($row['url']) ?></a>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td><?= esc($row['status']) ?></td>
                        <td><?= esc($row['message']) ?></td>
                        <td><?= esc($row['filename'] ?: '-') ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>

<?php endif; ?>

</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>