<?php
require_once __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Tenant\TenantContext;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Http\Request;

$_SERVER['HTTP_HOST'] = 'localhost';
$_COOKIE['x-tenant-id'] = 'default';
$req = new Request(['x-tenant-id' => 'default'], [], [], [], 'GET', '/');
TenantContext::bootstrapFromRequest($req);

$pdo = ConnectionManager::forTenant();

echo "== Populando mídias padrão para produtos sem mídia ==\n";
$stmt = $pdo->query('SELECT p.id, p.codigo FROM products p LEFT JOIN product_media pm ON p.id = pm.product_id WHERE pm.product_id IS NULL ORDER BY p.id');
$rows = $stmt->fetchAll();

$srcPlaceholder = __DIR__ . '/../public/assets/logo-light.png';
if (!is_file($srcPlaceholder)) { echo "Placeholder não encontrado em public/assets/logo-light.png\n"; exit(1); }

// Função local simples para thumbnail
function create_thumb($src, $dest, $maxW = 80, $maxH = 80) {
    $info = @getimagesize($src); if (!$info) { @copy($src,$dest); return; }
    [$w,$h] = [$info[0],$info[1]]; $type = $info[2] ?? 0;
    switch ($type) {
        case IMAGETYPE_JPEG: $load='imagecreatefromjpeg'; $save='imagejpeg'; break;
        case IMAGETYPE_PNG:  $load='imagecreatefrompng';  $save='imagepng';  break;
        case IMAGETYPE_WEBP: $load='imagecreatefromwebp'; $save='imagewebp'; break;
        default: @copy($src,$dest); return;
    }
    if (!function_exists($load) || !function_exists($save)) { @copy($src,$dest); return; }
    $srcImg = @$load($src); if (!$srcImg) { @copy($src,$dest); return; }
    $ratio = min($maxW / max(1,$w), $maxH / max(1,$h));
    $nw = max(1,(int)floor($w*$ratio)); $nh=max(1,(int)floor($h*$ratio));
    $thumb = imagecreatetruecolor($nw,$nh);
    imagealphablending($thumb,false); imagesavealpha($thumb,true);
    $transparent = imagecolorallocatealpha($thumb,0,0,0,127); imagefilledrectangle($thumb,0,0,$nw,$nh,$transparent);
    imagecopyresampled($thumb,$srcImg,0,0,0,0,$nw,$nh,$w,$h);
    @mkdir(dirname($dest),0775,true);
    if ($save==='imagejpeg') { @$save($thumb,$dest,85); } else if ($save==='imagepng') { @$save($thumb,$dest,6); } else { @$save($thumb,$dest); }
    imagedestroy($thumb); imagedestroy($srcImg);
}

$added = 0;
foreach ($rows as $r) {
    $pid = (int)$r['id'];
    $dir = __DIR__ . '/../public/uploads/products/' . $pid;
    if (!is_dir($dir)) @mkdir($dir, 0775, true);
    $dest = $dir . '/placeholder.png';
    if (!@copy($srcPlaceholder, $dest)) { echo "Falha ao copiar placeholder para produto {$pid}\n"; continue; }
    @mkdir($dir . '/thumbs', 0775, true);
    create_thumb($dest, $dir . '/thumbs/placeholder.png');
    $size = @filesize($dest) ?: 0;
    $stmtIns = $pdo->prepare('INSERT INTO product_media (product_id, type, filename, mime, size, position) VALUES (?,?,?,?,?,?)');
    $stmtIns->execute([$pid, 'image', 'products/' . $pid . '/placeholder.png', 'image/png', $size, 0]);
    $added++;
    echo "Produto {$pid}: placeholder criado.\n";
}

echo "\nConcluído. Itens adicionados: {$added}.\n";