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

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

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

$pdo = ConnectionManager::forTenant();

echo "=== MÍDIAS NA TABELA PRODUCT_MEDIA ===\n";
$stmt = $pdo->query('SELECT product_id, COUNT(*) as total, GROUP_CONCAT(CONCAT("ID:", id, " Pos:", position, " Type:", type, " File:", COALESCE(filename, "NULL"), " URL:", COALESCE(url, "NULL")) SEPARATOR "; ") as detalhes FROM product_media GROUP BY product_id ORDER BY product_id');
$medias = $stmt->fetchAll();

foreach ($medias as $media) {
    echo "Produto {$media['product_id']}: {$media['total']} mídia(s)\n";
    echo "  Detalhes: {$media['detalhes']}\n\n";
}

echo "=== 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');
$noMedia = $stmt->fetchAll();

foreach ($noMedia as $product) {
    echo "Produto {$product['id']}: {$product['codigo']} - SEM MÍDIA\n";
}

echo "\n=== VERIFICAÇÃO DE ARQUIVOS FÍSICOS ===\n";
$stmt = $pdo->query('SELECT product_id, filename FROM product_media WHERE filename IS NOT NULL ORDER BY product_id');
$files = $stmt->fetchAll();

foreach ($files as $file) {
    $fullPath = __DIR__ . '/../public/uploads/' . $file['filename'];
    $exists = file_exists($fullPath) ? 'EXISTE' : 'NÃO EXISTE';
    echo "Produto {$file['product_id']}: {$file['filename']} - {$exists}\n";
}