<?php

namespace App\Http\Controllers;

use App\Models\ProgressPhoto;
use App\Models\PhotoComment;
use App\Models\PhotoLike;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

/**
 * PublicPhotoController
 * FASE 4: Gestiona la visualización pública de fotos de progreso
 */
class PublicPhotoController extends Controller
{
    /**
     * Show public photo with likes and comments
     */
    public function show(string $token): Response
    {
        $photo = ProgressPhoto::where('public_token', $token)
            ->where('is_public', true)
            ->with(['client.user', 'client.portalUser', 'comments' => fn($q) => $q->latest()])
            ->firstOrFail();

        // Increment views
        $photo->incrementViews();

        // Check if user already liked (by IP)
        $ipAddress = request()->ip();
        $hasLiked = $photo->likes()->where('ip_address', $ipAddress)->exists();

        // Get client avatar - try client.avatar first, then portalUser.avatar_url
        $clientAvatar = null;
        if ($photo->client->avatar) {
            $clientAvatar = str_starts_with($photo->client->avatar, 'http')
                ? $photo->client->avatar
                : asset('storage/' . $photo->client->avatar);
        } elseif ($photo->client->portalUser?->avatar_url) {
            $clientAvatar = $photo->client->portalUser->avatar_url;
        }

        return Inertia::render('Public/Photo', [
            'photo' => [
                'id' => $photo->id,
                'image_path' => $photo->image_path,
                'after_image_path' => $photo->after_image_path,
                'type' => $photo->type,
                'weight' => $photo->weight,
                'date' => $photo->date->format('Y-m-d'),
                'views_count' => $photo->views_count,
                'likes_count' => $photo->likes_count,
                'shared_at' => $photo->shared_at?->diffForHumans(),
                'client_name' => $photo->client->name ?? 'Usuario',
                'client_avatar' => $clientAvatar,
                'has_liked' => $hasLiked,
            ],
            'comments' => $photo->comments->map(fn($comment) => [
                'id' => $comment->id,
                'author_name' => $comment->author_name,
                'comment' => $comment->comment,
                'likes_count' => $comment->likes_count,
                'created_at' => $comment->created_at->diffForHumans(),
            ]),
        ]);
    }

    /**
     * Toggle like on photo
     */
    public function toggleLike(string $token, Request $request)
    {
        $photo = ProgressPhoto::where('public_token', $token)
            ->where('is_public', true)
            ->firstOrFail();

        $ipAddress = $request->ip();

        $like = $photo->likes()->where('ip_address', $ipAddress)->first();

        if ($like) {
            // Unlike
            $like->delete();
            $photo->decrement('likes_count');
            $hasLiked = false;
        } else {
            // Like
            $photo->likes()->create(['ip_address' => $ipAddress]);
            $photo->increment('likes_count');
            $hasLiked = true;
        }

        return response()->json([
            'success' => true,
            'likes_count' => $photo->fresh()->likes_count,
            'has_liked' => $hasLiked,
        ]);
    }

    /**
     * Add comment to photo
     */
    public function addComment(string $token, Request $request)
    {
        $request->validate([
            'author_name' => 'required|string|max:100',
            'comment' => 'required|string|max:1000',
        ]);

        $photo = ProgressPhoto::where('public_token', $token)
            ->where('is_public', true)
            ->firstOrFail();

        $comment = $photo->comments()->create([
            'author_name' => $request->author_name,
            'comment' => $request->comment,
            'ip_address' => $request->ip(),
        ]);

        return response()->json([
            'success' => true,
            'comment' => [
                'id' => $comment->id,
                'author_name' => $comment->author_name,
                'comment' => $comment->comment,
                'likes_count' => 0,
                'created_at' => $comment->created_at->diffForHumans(),
            ],
        ]);
    }

    /**
     * Make photo public and get shareable link
     */
    public function makePublic(ProgressPhoto $photo, Request $request)
    {
        $user = $request->user();
        $client = $user->client;

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

        $photo->makePublic();

        return response()->json([
            'success' => true,
            'public_url' => $photo->getPublicUrl(),
            'public_token' => $photo->public_token,
        ]);
    }
}
