<?php
require_once __DIR__ . '/db/config.php';

// Helper functions from guidelines
function pexels_key() {
    $k = getenv('PEXELS_KEY');
    return $k && strlen($k) > 0 ? $k : 'Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18';
}

function pexels_get($url) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [ 'Authorization: '. pexels_key() ],
        CURLOPT_TIMEOUT => 15,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($code >= 200 && $code < 300 && $resp) return json_decode($resp, true);
    return null;
}

function download_to($srcUrl, $destPath) {
    $data = file_get_contents($srcUrl);
    if ($data === false) return false;
    if (!is_dir(dirname($destPath))) mkdir(dirname($destPath), 0775, true);
    return file_put_contents($destPath, $data) !== false;
}

$db = db();
$posts = $db->query("SELECT id, title FROM posts WHERE image_path IS NULL OR image_path = ''")->fetchAll();

foreach ($posts as $post) {
    $q = urlencode($post['title'] . " android tech");
    $url = 'https://api.pexels.com/v1/search?query=' . $q . '&orientation=landscape&per_page=1&page=1';
    $data = pexels_get($url);
    if ($data && !empty($data['photos'])) {
        $photo = $data['photos'][0];
        $src = $photo['src']['large'] ?? $photo['src']['original'];
        $filename = 'assets/images/pexels/' . $photo['id'] . '.jpg';
        $target = __DIR__ . '/' . $filename;
        if (download_to($src, $target)) {
            $db->prepare("UPDATE posts SET image_path = ? WHERE id = ?")->execute([$filename, $post['id']]);
            echo "Added image to: " . $post['title'] . "\n";
        } else {
            echo "Failed to download image for: " . $post['title'] . "\n";
        }
    } else {
        echo "No image found for: " . $post['title'] . "\n";
    }
}

