<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\InvestmentProduct;
use App\Models\InvestmentProductImage;
use App\Models\InvestmentCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class InvestmentProductController extends Controller
{
    /**
     * Liste des produits d'investissement
     */
    public function index()
    {
        $products = InvestmentProduct::with(['category', 'productImages'])->orderBy('order')->get();
        return view('admin.investment-products.index', compact('products'));
    }

    /**
     * Formulaire de création
     */
    public function create()
    {
        $categories = InvestmentCategory::where('is_active', true)->orderBy('name')->get();
        return view('admin.investment-products.create', compact('categories'));
    }

    /**
     * Enregistrer un nouveau produit
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'category_id' => 'nullable|exists:investment_categories,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'roi_percentage' => 'nullable|numeric|min:0|max:100',
            'duration_months' => 'nullable|integer|min:1',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'images' => 'nullable|array|max:10',
            'images.*' => 'image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'features' => 'nullable|string',
            'order' => 'nullable|integer',
            'is_active' => 'sometimes'
        ]);

        $validated['is_active'] = $request->has('is_active') ? 1 : 0;
        $validated['order'] = $validated['order'] ?? 0;

        // Créer le produit
        $product = InvestmentProduct::create([
            'category_id' => $validated['category_id'] ?? null,
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'price' => $validated['price'],
            'roi_percentage' => $validated['roi_percentage'] ?? null,
            'duration_months' => $validated['duration_months'] ?? null,
            'features' => $validated['features'] ?? null,
            'order' => $validated['order'],
            'is_active' => $validated['is_active']
        ]);

        // Gérer l'image principale
        if ($request->hasFile('image')) {
            $this->uploadImage($product, $request->file('image'), true);
        }

        // Gérer les images additionnelles
        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                $this->uploadImage($product, $image, false);
            }
        }

        // Synchroniser les images
        $product->syncImagesColumn();

        return redirect()->route('admin.investment-products.index')
            ->with('success', 'Produit d\'investissement créé avec succès.');
    }

    /**
     * Formulaire d'édition
     */
    public function edit(InvestmentProduct $investmentProduct)
    {
        $investmentProduct->load('productImages');
        $categories = InvestmentCategory::where('is_active', true)->orderBy('name')->get();
        return view('admin.investment-products.edit', compact('investmentProduct', 'categories'));
    }

    /**
     * Mettre à jour un produit
     */
    public function update(Request $request, InvestmentProduct $investmentProduct)
    {
        $validated = $request->validate([
            'category_id' => 'nullable|exists:investment_categories,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'roi_percentage' => 'nullable|numeric|min:0|max:100',
            'duration_months' => 'nullable|integer|min:1',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'images' => 'nullable|array|max:10',
            'images.*' => 'image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'features' => 'nullable|string',
            'order' => 'nullable|integer',
            'is_active' => 'sometimes',
            'remove_image' => 'sometimes'
        ]);

        $validated['is_active'] = $request->has('is_active') ? 1 : 0;

        // Gestion de la suppression de toutes les images
        if ($request->has('remove_image')) {
            $this->deleteAllImages($investmentProduct);
            $investmentProduct->update(['image' => null, 'thumbnail' => null, 'images' => null]);
        }

        // Gestion du nouvel upload image principale
        if ($request->hasFile('image')) {
            // Supprimer l'ancienne image principale uniquement
            $primaryImage = $investmentProduct->productImages()->where('is_primary', true)->first();
            if ($primaryImage) {
                $primaryImage->deleteFile();
                $primaryImage->delete();
            }
            
            $this->uploadImage($investmentProduct, $request->file('image'), true);
        }

        // Gérer les images additionnelles
        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $image) {
                $this->uploadImage($investmentProduct, $image, false);
            }
        }

        // Synchroniser les images avant la mise à jour
        $investmentProduct->syncImagesColumn();

        // Mettre à jour les autres champs
        $investmentProduct->update([
            'category_id' => $validated['category_id'] ?? null,
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'price' => $validated['price'],
            'roi_percentage' => $validated['roi_percentage'] ?? null,
            'duration_months' => $validated['duration_months'] ?? null,
            'features' => $validated['features'] ?? null,
            'order' => $validated['order'] ?? 0,
            'is_active' => $validated['is_active']
        ]);

        return redirect()->route('admin.investment-products.index')
            ->with('success', 'Produit d\'investissement modifié avec succès.');
    }

    /**
     * Supprimer un produit
     */
    public function destroy(InvestmentProduct $investmentProduct)
    {
        $this->deleteAllImages($investmentProduct);
        $investmentProduct->delete();

        return redirect()->route('admin.investment-products.index')
            ->with('success', 'Produit supprimé avec succès.');
    }

    /**
     * Supprimer une image spécifique
     */
    public function deleteImage(InvestmentProduct $investmentProduct, InvestmentProductImage $image)
    {
        if ($image->investment_product_id !== $investmentProduct->id) {
            abort(403);
        }

        $wasPrimary = $image->is_primary;
        $image->deleteFile();
        $image->delete();

        // Si c'était l'image principale, promouvoir la suivante
        if ($wasPrimary) {
            $nextImage = $investmentProduct->productImages()->orderBy('position')->first();
            if ($nextImage) {
                $nextImage->setAsPrimary();
            }
        }

        $investmentProduct->syncImagesColumn();

        return back()->with('success', 'Image supprimée avec succès.');
    }

    /**
     * Définir une image comme principale
     */
    public function setPrimaryImage(InvestmentProduct $investmentProduct, InvestmentProductImage $image)
    {
        if ($image->investment_product_id !== $investmentProduct->id) {
            abort(403);
        }

        $image->setAsPrimary();
        $investmentProduct->syncImagesColumn();

        return back()->with('success', 'Image principale définie.');
    }

    /**
     * Réorganiser les images
     */
    public function reorderImages(Request $request, InvestmentProduct $investmentProduct)
    {
        $request->validate([
            'order' => 'required|array',
            'order.*' => 'integer|exists:investment_product_images,id'
        ]);

        foreach ($request->order as $position => $imageId) {
            InvestmentProductImage::where('id', $imageId)
                ->where('investment_product_id', $investmentProduct->id)
                ->update(['position' => $position]);
        }

        $investmentProduct->syncImagesColumn();

        return response()->json(['success' => true]);
    }

    /**
     * Upload une image
     */
    protected function uploadImage(InvestmentProduct $product, $file, bool $isPrimary): ?InvestmentProductImage
    {
        try {
            $folder = 'investment-products';
            $extension = $file->getClientOriginalExtension() ?: 'jpg';
            $filename = time() . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $extension;
            
            // Chemin relatif
            $relativePath = $folder . '/' . $filename;
            
            // Stocker le fichier
            $file->storeAs($folder, $filename, 'public');
            
            // Copier vers public/storage (Windows/cPanel compatibilité)
            $this->copyToPublic($relativePath, $file);
            
            // Créer la miniature
            $thumbnailPath = $this->createThumbnail($file, $folder, $filename);

            // Calculer la position
            $maxPosition = $product->productImages()->max('position') ?? -1;
            $position = $maxPosition + 1;

            // Si c'est la première image ou demandée comme principale
            $isFirstImage = $product->productImages()->count() === 0;
            if ($isPrimary || $isFirstImage) {
                // Retirer le flag des autres
                $product->productImages()->update(['is_primary' => false]);
            }

            // Créer l'enregistrement
            $image = InvestmentProductImage::create([
                'investment_product_id' => $product->id,
                'path' => $relativePath,
                'filename' => $filename,
                'thumbnail_path' => $thumbnailPath,
                'position' => $position,
                'is_primary' => $isPrimary || $isFirstImage,
                'alt_text' => $product->name,
                'size' => $file->getSize()
            ]);

            return $image;

        } catch (\Exception $e) {
            Log::error("Erreur upload image investissement: " . $e->getMessage());
            return null;
        }
    }

    /**
     * Copier vers public/storage (compatibilité Windows/cPanel sans symlink)
     */
    protected function copyToPublic(string $relativePath, $file): void
    {
        try {
            $publicDir = public_path('storage/' . dirname($relativePath));
            if (!is_dir($publicDir)) {
                mkdir($publicDir, 0755, true);
            }
            
            $publicPath = public_path('storage/' . $relativePath);
            copy($file->getRealPath(), $publicPath);
        } catch (\Exception $e) {
            Log::warning("Copie vers public/storage échouée: " . $e->getMessage());
        }
    }

    /**
     * Créer une miniature
     */
    protected function createThumbnail($file, string $folder, string $filename): ?string
    {
        try {
            // Vérifier que GD est disponible
            if (!function_exists('imagecreatefromjpeg')) {
                return null;
            }

            $thumbWidth = 300;
            $thumbHeight = 300;
            
            // Créer le nom de la miniature
            $pathInfo = pathinfo($filename);
            $thumbFilename = $pathInfo['filename'] . '_thumb.' . $pathInfo['extension'];
            $thumbnailPath = $folder . '/thumbnails/' . $thumbFilename;
            
            // Charger l'image source
            $mimeType = $file->getMimeType();
            $sourcePath = $file->getRealPath();
            
            switch ($mimeType) {
                case 'image/jpeg':
                    $source = @imagecreatefromjpeg($sourcePath);
                    break;
                case 'image/png':
                    $source = @imagecreatefrompng($sourcePath);
                    break;
                case 'image/gif':
                    $source = @imagecreatefromgif($sourcePath);
                    break;
                case 'image/webp':
                    $source = @imagecreatefromwebp($sourcePath);
                    break;
                default:
                    return null;
            }
            
            if (!$source) {
                return null;
            }
            
            // Dimensions originales
            $origWidth = imagesx($source);
            $origHeight = imagesy($source);
            
            // Calculer les dimensions de la miniature (ratio préservé)
            $ratio = min($thumbWidth / $origWidth, $thumbHeight / $origHeight);
            $newWidth = (int)($origWidth * $ratio);
            $newHeight = (int)($origHeight * $ratio);
            
            // Créer la miniature
            $thumb = imagecreatetruecolor($newWidth, $newHeight);
            
            // Préserver la transparence pour PNG/GIF
            if ($mimeType === 'image/png' || $mimeType === 'image/gif') {
                imagealphablending($thumb, false);
                imagesavealpha($thumb, true);
                $transparent = imagecolorallocatealpha($thumb, 255, 255, 255, 127);
                imagefilledrectangle($thumb, 0, 0, $newWidth, $newHeight, $transparent);
            }
            
            // Redimensionner
            imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
            
            // Créer le dossier thumbnails
            $storageThumbDir = storage_path('app/public/' . $folder . '/thumbnails');
            $publicThumbDir = public_path('storage/' . $folder . '/thumbnails');
            
            if (!is_dir($storageThumbDir)) {
                mkdir($storageThumbDir, 0755, true);
            }
            if (!is_dir($publicThumbDir)) {
                mkdir($publicThumbDir, 0755, true);
            }
            
            // Sauvegarder dans storage
            $storagePath = storage_path('app/public/' . $thumbnailPath);
            $publicPath = public_path('storage/' . $thumbnailPath);
            
            switch ($mimeType) {
                case 'image/jpeg':
                    imagejpeg($thumb, $storagePath, 85);
                    imagejpeg($thumb, $publicPath, 85);
                    break;
                case 'image/png':
                    imagepng($thumb, $storagePath, 8);
                    imagepng($thumb, $publicPath, 8);
                    break;
                case 'image/gif':
                    imagegif($thumb, $storagePath);
                    imagegif($thumb, $publicPath);
                    break;
                case 'image/webp':
                    imagewebp($thumb, $storagePath, 85);
                    imagewebp($thumb, $publicPath, 85);
                    break;
            }
            
            // Libérer la mémoire
            imagedestroy($source);
            imagedestroy($thumb);
            
            return $thumbnailPath;
            
        } catch (\Exception $e) {
            Log::warning("Création miniature échouée: " . $e->getMessage());
            return null;
        }
    }

    /**
     * Générer description (optionnel - ne bloque pas si IA non disponible)
     */
    public function generateDescription(InvestmentProduct $investmentProduct)
    {
        // Message simple sans dépendance IA
        return back()->with('info', 'La génération IA de description n\'est pas activée. Vous pouvez saisir une description manuellement.');
    }

    /**
     * Supprimer toutes les images d'un produit
     */
    protected function deleteAllImages(InvestmentProduct $product): void
    {
        // Supprimer depuis la table
        foreach ($product->productImages as $image) {
            $image->deleteFile();
            $image->delete();
        }

        // Supprimer l'ancienne image si elle existe (colonne image)
        if ($product->image) {
            // Storage
            if (Storage::disk('public')->exists($product->image)) {
                Storage::disk('public')->delete($product->image);
            }
            // Public
            $publicPath = public_path('storage/' . $product->image);
            if (file_exists($publicPath)) {
                @unlink($publicPath);
            }
        }
    }
}
