<?php
require_once __DIR__.'/../includes/pexels.php';
// We'll try to find a video that combines these themes.
// Since we can't easily find a single clip with everything, we'll pick the most descriptive one.
$query = 'woman laptop kitchen budget cooking';
$url = 'https://api.pexels.com/videos/search?query=' . urlencode($query) . '&orientation=portrait&per_page=1&page=1';
$data = pexels_get($url);

if ($data && !empty($data['videos'])) {
    $video = $data['videos'][0];
    $bestFile = null;
    foreach ($video['video_files'] as $file) {
        if ($file['quality'] == 'hd' && ($file['width'] == 1080 || $file['width'] == 720)) {
            $bestFile = $file;
            break;
        }
    }
    if (!$bestFile) $bestFile = $video['video_files'][0];

    $src = $bestFile['link'];
    $target = __DIR__ . '/../assets/images/auth-video.mp4';
    
    // Using curl for video as file_get_contents might be slow/limited for large files
    $ch = curl_init($src);
    $fp = fopen($target, 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    
    echo "Success: Downloaded " . $target;
} else {
    echo "Error: Failed to fetch video info from Pexels.";
}
