<?php
/**
 * Sistema de Upload de Imagens de Produtos
 */

function debugLog(string $msg): void {
    file_put_contents('/home/socialar/dev.duolead.com.br/logs/debug.log', date('Y-m-d H:i:s') . ' - ' . $msg . "\n", FILE_APPEND);
}

function processProductImages(PDO $pdo, int $storeId, int $productId): array {
    $uploadDir = __DIR__ . "/../uploads/products/";
    $baseUrl = "/uploads/products/";
    $uploadedImages = [];
    $mainImageUrl = null;
    $mainIndex = intval($_POST['main_image_index'] ?? 0);

    debugLog("processProductImages - storeId: $storeId, productId: $productId, mainIndex: $mainIndex");
    debugLog("processProductImages - existing_images POST: " . ($_POST['existing_images'] ?? 'empty'));
    debugLog("processProductImages - FILES: " . json_encode($_FILES));

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    // Processar imagens existentes (da galeria ou já salvas)
    $existingImages = [];
    if (!empty($_POST['existing_images'])) {
        $decoded = json_decode($_POST['existing_images'], true);
        debugLog("processProductImages - decoded existing_images: " . json_encode($decoded));
        if (is_array($decoded)) {
            foreach ($decoded as $index => $img) {
                if (is_string($img)) {
                    $existingImages[] = $img;
                } elseif (isset($img['url'])) {
                    $existingImages[] = $img['url'];
                }
            }
        }
    }

    $hasNewImages = !empty($_FILES['product_images']['name'][0]);
    debugLog("processProductImages - hasNewImages: " . ($hasNewImages ? 'true' : 'false'));
    debugLog("processProductImages - existingImages count: " . count($existingImages));

    // Se não tem imagens existentes nem novos uploads, buscar do banco
    if (empty($existingImages) && !$hasNewImages && $productId) {
        debugLog("processProductImages - Buscando imagens do banco para produto $productId");
        $stmt = $pdo->prepare("SELECT image_url, images FROM products WHERE id = ?");
        $stmt->execute([$productId]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($current) {
            debugLog("processProductImages - Dados do banco: " . json_encode($current));
            if ($current['image_url']) {
                $existingImages[] = $current['image_url'];
            }
            if ($current['images']) {
                $currentImages = json_decode($current['images'], true);
                if (is_array($currentImages)) {
                    foreach ($currentImages as $img) {
                        if (!in_array($img, $existingImages)) {
                            $existingImages[] = $img;
                        }
                    }
                }
            }
        }
    }

    // Processar novos uploads
    if ($hasNewImages) {
        $files = $_FILES['product_images'];

        for ($i = 0; $i < count($files['name']); $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $tmpName = $files['tmp_name'][$i];
                $originalName = $files['name'][$i];
                $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

                $allowed = ['jpg', 'jpeg', 'png', 'webp'];
                if (!in_array($ext, $allowed)) continue;

                if ($files['size'][$i] > 5 * 1024 * 1024) continue;

                $newName = "product_" . $storeId . "_" . uniqid() . "." . $ext;
                $targetPath = $uploadDir . $newName;

                debugLog("processProductImages - Tentando mover arquivo para: $targetPath");

                if (move_uploaded_file($tmpName, $targetPath)) {
                    $imageUrl = $baseUrl . $newName;
                    $uploadedImages[] = $imageUrl;
                    debugLog("processProductImages - Imagem salva: $imageUrl");
                } else {
                    debugLog("processProductImages - ERRO ao mover arquivo!");
                }
            } else {
                debugLog("processProductImages - Erro no upload: " . $files['error'][$i]);
            }
        }
    }

    // Combinar todas as imagens (existentes + novos uploads)
    $allImages = array_merge($existingImages, $uploadedImages);
    
    debugLog("processProductImages - allImages: " . json_encode($allImages));
    debugLog("processProductImages - mainIndex recebido: $mainIndex");

    // Definir a imagem principal baseado no índice
    if (count($allImages) > 0) {
        if ($mainIndex >= 0 && $mainIndex < count($allImages)) {
            $mainImageUrl = $allImages[$mainIndex];
        } else {
            $mainImageUrl = $allImages[0];
        }
    }

    // Remover a imagem principal do array de imagens adicionais
    $additionalImages = array_filter($allImages, function($img) use ($mainImageUrl) {
        return $img !== $mainImageUrl;
    });
    $additionalImages = array_values($additionalImages); // Reindexar

    debugLog("processProductImages - Resultado final: main=$mainImageUrl, additional=" . json_encode($additionalImages));

    return [
        'main' => $mainImageUrl,
        'all' => $additionalImages
    ];
}

function updateProductImages(PDO $pdo, int $productId, ?string $mainImage, array $allImages): bool {
    debugLog("updateProductImages - productId: $productId, mainImage: $mainImage, allImages: " . json_encode($allImages));
    $stmt = $pdo->prepare("UPDATE products SET image_url = ?, images = ? WHERE id = ?");
    $result = $stmt->execute([$mainImage, json_encode($allImages), $productId]);
    debugLog("updateProductImages - Resultado: " . ($result ? 'sucesso' : 'falha'));
    return $result;
}

function deleteProductImages(int $productId, array $images): void {
    $uploadDir = __DIR__ . "/../uploads/products/";
    if (is_array($images)) {
        foreach ($images as $imageUrl) {
            $filename = basename($imageUrl);
            $filePath = $uploadDir . $filename;
            if (file_exists($filePath)) {
                @unlink($filePath);
            }
        }
    }
}
