<?php
define('FCPATH', __DIR__ . '/public/');
require FCPATH . '../app/Config/Paths.php';
$paths = new Config\Paths();
define('WRITEPATH', $paths->writableDirectory . DIRECTORY_SEPARATOR);

$db = new PDO('mysql:host=127.0.0.1;dbname=kopdigi;port=3306', 'root', '');
$products = $db->query("SELECT id, foto FROM products WHERE foto LIKE 'http%'")->fetchAll(PDO::FETCH_ASSOC);

if (!is_dir(WRITEPATH . 'uploads/img')) {
    mkdir(WRITEPATH . 'uploads/img', 0777, true);
}

foreach ($products as $p) {
    echo "Downloading image for product {$p['id']}... ";
    $imgData = @file_get_contents($p['foto']);
    if ($imgData) {
        $filename = 'product_' . $p['id'] . '_' . uniqid() . '.jpg';
        file_put_contents(WRITEPATH . 'uploads/img/' . $filename, $imgData);
        $newUrl = 'api/products/image/' . $filename;
        $db->exec("UPDATE products SET foto = '$newUrl' WHERE id = {$p['id']}");
        echo "Saved as $filename\n";
    } else {
        echo "Failed to download\n";
    }
}
echo "Done.\n";
