<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\ProgressPhoto;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;

/**
 * PhotoController
 * Handles client progress photo management
 */
class PhotoController extends Controller
{
    /**
     * Display the client's photo gallery
     */
    public function index()
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();
        $client = $user->client;

        if (!$client) {
            abort(404, 'Client profile not found');
        }

        $photos = $client->progressPhotos()
            ->orderBy('date', 'desc')
            ->get();

        return Inertia::render('Client/Photos/Index', [
            'photos' => $photos,
            'client' => $client,
        ]);
    }

    /**
     * Upload a new progress photo
     */
    public function upload(Request $request)
    {
        $request->validate([
            'image' => 'required|image|max:10240', // 10MB max
            'after_image' => 'nullable|image|max:10240', // 10MB max
            'type' => 'nullable|in:front,side,back',
            'time_period' => 'nullable|string|max:50',
            'weight' => 'nullable|numeric|min:20|max:500',
            'date' => 'nullable|date',
        ]);

        /** @var \App\Models\User $user */
        $user = auth()->user();
        $client = $user->client;

        if (!$client) {
            abort(404);
        }

        $path = $request->file('image')->store("progress-photos/{$client->id}", 'public');

        $afterPath = null;
        if ($request->hasFile('after_image')) {
            $afterPath = $request->file('after_image')->store("progress-photos/{$client->id}", 'public');
        }

        $client->progressPhotos()->create([
            'image_path' => $path,
            'after_image_path' => $afterPath,
            'type' => $request->type ?? 'front',
            'time_period' => $request->time_period,
            'weight' => $request->weight,
            'date' => $request->date ?? now()->toDateString(),
        ]);

        return back()->with('success', 'Foto subida correctamente');
    }

    /**
     * Delete a progress photo
     */
    public function destroy(ProgressPhoto $photo)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();
        $client = $user->client;

        if (!$client || $photo->client_id !== $client->id) {
            abort(403);
        }

        // Delete the file from storage - use getRawOriginal to avoid accessor path
        $rawPath = $photo->getRawOriginal('image_path');
        if ($rawPath) {
            Storage::disk('public')->delete($rawPath);
        }
        $rawAfterPath = $photo->getRawOriginal('after_image_path');
        if ($rawAfterPath) {
            Storage::disk('public')->delete($rawAfterPath);
        }

        $photo->delete();

        return back()->with('success', 'Foto eliminada');
    }

    /**
     * Generate photo with watermark
     * FASE 3: Añade marca de agua con logo y URL
     */
    public function watermark(ProgressPhoto $photo)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();
        $client = $user->client;

        if (!$client || $photo->client_id !== $client->id) {
            abort(403);
        }

        // Get the image file path - use getRawOriginal to avoid accessor prepending /storage/
        $rawImagePath = $photo->getRawOriginal('image_path');
        $imagePath = storage_path('app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rawImagePath));

        if (!file_exists($imagePath)) {
            abort(404, 'Image not found');
        }

        // Create image resource based on file type
        $imageInfo = getimagesize($imagePath);
        $mimeType = $imageInfo['mime'];

        switch ($mimeType) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($imagePath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($imagePath);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($imagePath);
                break;
            default:
                abort(400, 'Unsupported image type');
        }

        $width = imagesx($image);
        $height = imagesy($image);

        // Create watermark text
        $watermarkText = config('app.url', 'CoachPro.com');
        $watermarkText = str_replace(['http://', 'https://'], '', $watermarkText);

        // Add semi-transparent overlay at bottom
        $overlayHeight = 80;
        $overlayColor = imagecolorallocatealpha($image, 0, 0, 0, 50); // Black with 50% transparency
        imagefilledrectangle($image, 0, $height - $overlayHeight, $width, $height, $overlayColor);

        // Add watermark text
        $white = imagecolorallocate($image, 255, 255, 255);
        $fontSize = min($width / 20, 24); // Responsive font size
        $font = resource_path('fonts/Arial.ttf'); // You can use any TTF font

        // If custom font doesn't exist, use built-in font
        if (!file_exists($font)) {
            // Use built-in font
            $textX = 20;
            $textY = $height - 45;
            imagestring($image, 5, $textX, $textY, $watermarkText, $white);

            // Add coach branding
            $brandText = "🏋️ Powered by CoachPro";
            imagestring($image, 3, $textX, $textY + 20, $brandText, $white);
        } else {
            // Use TTF font for better quality
            $bbox = imagettfbbox($fontSize, 0, $font, $watermarkText);
            $textWidth = abs($bbox[4] - $bbox[0]);
            $textX = ($width - $textWidth) / 2; // Center text
            $textY = $height - 25;

            imagettftext($image, $fontSize, 0, $textX, $textY, $white, $font, $watermarkText);

            // Add small branding
            $brandText = "Powered by CoachPro";
            $smallFontSize = $fontSize * 0.6;
            $bbox2 = imagettfbbox($smallFontSize, 0, $font, $brandText);
            $brandWidth = abs($bbox2[4] - $bbox2[0]);
            $brandX = ($width - $brandWidth) / 2;

            imagettftext($image, $smallFontSize, 0, $brandX, $textY + 25, $white, $font, $brandText);
        }

        // Add date stamp
        $dateText = date('d/m/Y', strtotime($photo->date));
        $dateX = $width - 120;
        $dateY = 30;
        $dateColor = imagecolorallocatealpha($image, 255, 255, 255, 30);
        imagefilledrectangle($image, $dateX - 10, $dateY - 20, $dateX + 110, $dateY + 10, $dateColor);
        imagestring($image, 4, $dateX, $dateY, $dateText, $white);

        // Output image
        ob_start();
        imagejpeg($image, null, 90); // 90% quality
        $imageData = ob_get_clean();
        imagedestroy($image);

        return response($imageData)
            ->header('Content-Type', 'image/jpeg')
            ->header('Content-Disposition', 'attachment; filename="progreso-' . $photo->date . '.jpg"');
    }

    /**
     * Generate combined BEFORE/AFTER image
     */
    public function generateCombined(ProgressPhoto $photo)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();
        $client = $user->client;

        if (!$client || $photo->client_id !== $client->id) {
            return response()->json(['error' => 'No autorizado'], 403);
        }

        if (!$photo->after_image_path) {
            return response()->json(['error' => 'Esta foto no tiene imagen DESPUÉS'], 400);
        }

        try {
            // Load both images - use getRawOriginal to avoid accessor prepending /storage/
            $rawBeforePath = $photo->getRawOriginal('image_path');
            $rawAfterPath = $photo->getRawOriginal('after_image_path');
            $beforePath = storage_path('app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rawBeforePath));
            $afterPath = storage_path('app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rawAfterPath));

            Log::info('Generating combined image', [
                'rawBeforePath' => $rawBeforePath,
                'rawAfterPath' => $rawAfterPath,
                'beforePath' => $beforePath,
                'afterPath' => $afterPath,
                'beforeExists' => file_exists($beforePath),
                'afterExists' => file_exists($afterPath)
            ]);

            if (!file_exists($beforePath)) {
                Log::error('Before image not found', ['path' => $beforePath, 'db_path' => $rawBeforePath]);
                return response()->json(['error' => 'Archivo ANTES no encontrado'], 404);
            }

            if (!file_exists($afterPath)) {
                Log::error('After image not found', ['path' => $afterPath, 'db_path' => $rawAfterPath]);
                return response()->json(['error' => 'Archivo DESPUÉS no encontrado'], 404);
            }

            // Check if GD is available
            if (!function_exists('imagecreatefromstring')) {
                Log::error('GD library not available');
                return response()->json(['error' => 'Extensión GD no disponible en el servidor'], 500);
            }

            // Create images from files
            $beforeContent = file_get_contents($beforePath);
            $afterContent = file_get_contents($afterPath);

            if ($beforeContent === false || $afterContent === false) {
                Log::error('Could not read image files');
                return response()->json(['error' => 'No se pudieron leer los archivos de imagen'], 500);
            }

            $beforeImage = @imagecreatefromstring($beforeContent);
            $afterImage = @imagecreatefromstring($afterContent);

            if (!$beforeImage || !$afterImage) {
                Log::error('Could not create image resources', [
                    'beforeImage' => $beforeImage ? 'ok' : 'failed',
                    'afterImage' => $afterImage ? 'ok' : 'failed'
                ]);
                return response()->json(['error' => 'No se pudieron procesar las imágenes'], 500);
            }

            // Get dimensions
            $beforeWidth = imagesx($beforeImage);
            $beforeHeight = imagesy($beforeImage);
            $afterWidth = imagesx($afterImage);
            $afterHeight = imagesy($afterImage);

            // Use the larger height
            $targetHeight = max($beforeHeight, $afterHeight);
            $gap = 8; // Slim dark gap between images
            $targetWidth = $beforeWidth + $afterWidth + $gap;

            // Create combined image with dark background
            $combined = imagecreatetruecolor($targetWidth, $targetHeight);
            $darkBg = imagecolorallocate($combined, 18, 18, 18);
            imagefill($combined, 0, 0, $darkBg);

            // Copy BEFORE image (left side)
            imagecopyresampled(
                $combined, $beforeImage,
                0, 0, // dest x, y
                0, 0, // src x, y
                $beforeWidth, $targetHeight, // dest width, height
                $beforeWidth, $beforeHeight // src width, height
            );

            // Copy AFTER image (right side with gap)
            $afterStartX = $beforeWidth + $gap;
            imagecopyresampled(
                $combined, $afterImage,
                $afterStartX, 0, // dest x, y
                0, 0, // src x, y
                $afterWidth, $targetHeight, // dest width, height
                $afterWidth, $afterHeight // src width, height
            );

            // Enable alpha blending for overlays
            imagealphablending($combined, true);

            // Colors
            $white = imagecolorallocate($combined, 255, 255, 255);
            $neonGreen = imagecolorallocate($combined, 57, 255, 20); // Brand #39FF14
            $redAccent = imagecolorallocate($combined, 239, 68, 68);
            $greenAccent = imagecolorallocate($combined, 34, 197, 94);

            $fontSize = 42;
            $font = public_path('fonts/Roboto-Bold.ttf');

            if (file_exists($font)) {
                // === TOP OVERLAY BARS ===
                $barHeight = 80;
                $overlay = imagecolorallocatealpha($combined, 0, 0, 0, 45); // ~65% opaque
                $shadow = imagecolorallocatealpha($combined, 0, 0, 0, 30);

                // --- ANTES BAR (left image) ---
                imagefilledrectangle($combined, 0, 0, $beforeWidth, $barHeight, $overlay);
                // Red accent line at bottom of bar
                imagefilledrectangle($combined, 0, $barHeight - 4, $beforeWidth, $barHeight, $redAccent);

                // ANTES text centered in bar
                $textBox = imagettfbbox($fontSize, 0, $font, 'ANTES');
                $textWidth = abs($textBox[4] - $textBox[0]);
                $textHeight = abs($textBox[5] - $textBox[1]);
                $textX = ($beforeWidth - $textWidth) / 2;
                $textY = ($barHeight + $textHeight) / 2 - 2;
                // Text shadow
                imagettftext($combined, $fontSize, 0, (int)$textX + 2, (int)$textY + 2, $shadow, $font, 'ANTES');
                // Main text
                imagettftext($combined, $fontSize, 0, (int)$textX, (int)$textY, $white, $font, 'ANTES');

                // Dumbbell icon left of ANTES text
                $dbX = (int)$textX - 40;
                $dbY = (int)($barHeight / 2);
                imagefilledellipse($combined, $dbX - 10, $dbY, 12, 20, $redAccent);
                imagefilledrectangle($combined, $dbX - 10, $dbY - 3, $dbX + 10, $dbY + 3, $white);
                imagefilledellipse($combined, $dbX + 10, $dbY, 12, 20, $redAccent);

                // --- DESPUÉS BAR (right image) ---
                imagefilledrectangle($combined, $afterStartX, 0, $targetWidth, $barHeight, $overlay);
                // Green accent line at bottom of bar
                imagefilledrectangle($combined, $afterStartX, $barHeight - 4, $targetWidth, $barHeight, $greenAccent);

                // DESPUÉS text centered in bar
                $textBox2 = imagettfbbox($fontSize, 0, $font, 'DESPUÉS');
                $textWidth2 = abs($textBox2[4] - $textBox2[0]);
                $textHeight2 = abs($textBox2[5] - $textBox2[1]);
                $textX2 = $afterStartX + ($afterWidth - $textWidth2) / 2;
                $textY2 = ($barHeight + $textHeight2) / 2 - 2;
                imagettftext($combined, $fontSize, 0, (int)$textX2 + 2, (int)$textY2 + 2, $shadow, $font, 'DESPUÉS');
                imagettftext($combined, $fontSize, 0, (int)$textX2, (int)$textY2, $white, $font, 'DESPUÉS');

                // Dumbbell icon left of DESPUÉS text
                $dbX2 = (int)$textX2 - 40;
                imagefilledellipse($combined, $dbX2 - 10, $dbY, 12, 20, $greenAccent);
                imagefilledrectangle($combined, $dbX2 - 10, $dbY - 3, $dbX2 + 10, $dbY + 3, $white);
                imagefilledellipse($combined, $dbX2 + 10, $dbY, 12, 20, $greenAccent);

                // === BOTTOM GRADIENT BAR ===
                $bottomBarHeight = 100;
                $steps = 25;
                $stepH = (int)ceil($bottomBarHeight / $steps);
                for ($i = 0; $i < $steps; $i++) {
                    $alpha = (int)(127 * (1 - $i / $steps));
                    $gradColor = imagecolorallocatealpha($combined, 0, 0, 0, max(0, $alpha));
                    $y1 = $targetHeight - $bottomBarHeight + ($i * $stepH);
                    $y2 = $y1 + $stepH;
                    imagefilledrectangle($combined, 0, $y1, $targetWidth, $y2, $gradColor);
                }

                // Bottom transformation text
                $bottomFontSize = 30;
                $timePeriod = $photo->time_period;
                $weightKg = $photo->weight;
                $parts = ['MI TRANSFORMACIÓN'];
                if ($timePeriod) {
                    $parts[] = strtoupper($timePeriod);
                }
                if ($weightKg) {
                    $parts[] = "{$weightKg} kg";
                }
                $bottomText = implode('  ·  ', $parts);

                $textBox3 = imagettfbbox($bottomFontSize, 0, $font, $bottomText);
                $textWidth3 = abs($textBox3[4] - $textBox3[0]);
                $textX3 = ($targetWidth - $textWidth3) / 2;
                imagettftext($combined, $bottomFontSize, 0, (int)$textX3, $targetHeight - 35, $neonGreen, $font, $bottomText);

                // Brand line
                $brandFontSize = 16;
                $brandText = 'COACHPRO';
                $textBox4 = imagettfbbox($brandFontSize, 0, $font, $brandText);
                $textWidth4 = abs($textBox4[4] - $textBox4[0]);
                $textX4 = ($targetWidth - $textWidth4) / 2;
                $lightGray = imagecolorallocatealpha($combined, 255, 255, 255, 70);
                imagettftext($combined, $brandFontSize, 0, (int)$textX4, $targetHeight - 10, $lightGray, $font, $brandText);
            } else {
                // Fallback to simple text if font not found
                $redColor = imagecolorallocate($combined, 239, 68, 68);
                imagestring($combined, 5, ($beforeWidth / 2) - 40, 20, 'ANTES', $redColor);
                $greenColor = imagecolorallocate($combined, 34, 197, 94);
                imagestring($combined, 5, $afterStartX + ($afterWidth / 2) - 50, 20, 'DESPUES', $greenColor);
            }

            // Save combined image
            $filename = 'combined-' . $photo->id . '-' . time() . '.jpg';
            $combinedDir = storage_path('app/public/progress-photos/combined');

            // Create directory if it doesn't exist
            if (!is_dir($combinedDir)) {
                Log::info('Creating combined directory: ' . $combinedDir);
                mkdir($combinedDir, 0755, true);
            }

            $savePath = $combinedDir . '/' . $filename;
            Log::info('Saving combined image to: ' . $savePath);

            $result = imagejpeg($combined, $savePath, 90);

            if (!$result) {
                throw new \Exception('No se pudo guardar la imagen combinada');
            }

            // Clean up
            imagedestroy($beforeImage);
            imagedestroy($afterImage);
            imagedestroy($combined);

            // Return URL
            $url = asset('storage/progress-photos/combined/' . $filename);

            return response()->json([
                'success' => true,
                'combined_url' => $url
            ]);

        } catch (\Exception $e) {
            Log::error('Error generating combined image: ' . $e->getMessage());
            return response()->json(['error' => 'Error al generar imagen combinada'], 500);
        }
    }}
