<?php

namespace App\Http\Controllers;

use App\Models\Review;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Services\BunnyCDNService;
use Illuminate\Http\Response;

class ReviewController extends Controller
{
    protected $bunnyCDNService;

    public function __construct(BunnyCDNService $bunnyCDNService)
    {
        $this->bunnyCDNService = $bunnyCDNService;
    }

    public function create(Request $request)
    {
        $validated = $request->validate([
            'comment' => 'required|string',
            'product_id' => 'required|exists:products,id',
            'rating' => 'required|numeric|min:1|max:5',
            'images' => 'nullable|array',
            'images.*' => 'string', // Ensure each image is a base64 string
            'author' => 'nullable|string',

        ]);

        $uploadedImageUrls = [];

        if ($request->has('images') && is_array($request->images)) {
            foreach ($request->images as $base64Image) {
                // Extract only the base64 part
                $imageData = preg_replace('#^data:image/\w+;base64,#i', '', $base64Image);
                $decodedImage = base64_decode($imageData);

                if (!$decodedImage) {
                    return response()->json(['error' => 'Invalid image data'], 422);
                }

                $fileName = Str::uuid() . '.jpg';
                $tempPath = storage_path('app/public/temp/' . $fileName);

                // Ensure temp directory exists
                if (!file_exists(dirname($tempPath))) {
                    mkdir(dirname($tempPath), 0777, true);
                }

                file_put_contents($tempPath, $decodedImage);

                // Upload to BunnyCDN
                $uploadedImageUrl = $this->bunnyCDNService->uploadImage($tempPath, $fileName);
                $uploadedImageUrls[] = $uploadedImageUrl;

                // Delete temp file
                unlink($tempPath);
            }
        }

        // Save review
        $review = Review::create([
            'author' => $validated['author'],

            'comment' => $validated['comment'],
            'product_id' => $validated['product_id'],
            'rating' => $validated['rating'],
            'user_id' => $request->user()->id,
            'images' => json_encode($uploadedImageUrls), // Store as JSON
        ]);

        return response()->json([
            'message' => 'Review created successfully',
            'review' => $review
        ], 201);
    }




    public function update(Request $request, $id)
    {
        $review = Review::findOrFail($id);

        $validated = $request->validate([
            'comment' => 'required|string',
            'product_id' => 'required|exists:products,id',
            'rating' => 'required|numeric',
            'images' => 'nullable|array',
            'author' => 'required|string',

        ]);
        // Start with existing images
        $uploadedImageUrls =  [];

        if ($request->has('images')) {
            $newImageUrls = [];

            foreach ($request->input('images') as $image) {
                if (filter_var($image, FILTER_VALIDATE_URL)) {
                    // If it's a URL, add it directly
                    $newImageUrls[] = $image;
                } else {
                    // If it's base64, upload to BunnyCDN
                    $fileName = Str::uuid() . '.jpg';
                    $imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $image));

                    if ($imageData === false) {
                        return response()->json(['error' => 'Invalid image data'], 400);
                    }

                    $tempDirectory = storage_path('app/public/temp');
                    $tempFilePath = $tempDirectory . '/' . $fileName;

                    if (!file_exists($tempDirectory)) {
                        mkdir($tempDirectory, 0777, true);
                    }

                    file_put_contents($tempFilePath, $imageData);

                    $cdnUrl = $this->bunnyCDNService->uploadImage($tempFilePath, $fileName);

                    if ($cdnUrl) {
                        $newImageUrls[] = $cdnUrl;
                    } else {
                        return response()->json(['error' => 'Image upload failed'], 500);
                    }

                    unlink($tempFilePath);
                }
            }

            // Merge existing and new images
            $uploadedImageUrls = array_merge($uploadedImageUrls, $newImageUrls);
        }

        // Update the review with the merged images
        $review->update(array_merge($validated, ['images' => $uploadedImageUrls]));

        return response()->json([
            'message' => 'review created successfully',
            'review' => $review
        ], 201);
    }


    public function search(Request $request)
    {
        $query = Review::with(['product', 'user']);

        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where('comment', 'LIKE', "%{$search}%")
                ->orWhereHas('review', function ($q) use ($search) {
                    $q->where('name', 'LIKE', "%{$search}%");
                })
                ->orWhereHas('user', function ($q) use ($search) {
                    $q->where('fullName', 'LIKE', "%{$search}%");
                });
        }
        return response()->json($query->paginate(10));
    }



    public function searchClient()
    {
        $reviews = Review::query()
            ->with([
                'user:id,fullName',
                'product:id,name',
            ])
            ->latest('id')
            ->get()
            ->map(function ($r) {
                return [
                    'id' => $r->id,
                    'rating' => (int) $r->rating,
                    'comment' => $r->comment,

                    // name to show in UI
                    'author' => $r->author ?: ($r->user?->fullName ?? 'Anonymous'),

                    // arrays for images
                    'images' => is_array($r->images)
                        ? $r->images
                        : (json_decode($r->images ?? '[]', true) ?: []),

                    // optional: show product name if you want
                    'product' => $r->product ? [
                        'id' => $r->product->id,
                        'name' => $r->product->name,
                    ] : null,

                    // optional placeholders for your design
                    'location' => null,
                    'avatar' => null,
                ];
            });

        return response()->json([
            'data' => $reviews
        ]);
    }


    public function delete($id)
    {
        $review = Review::findOrFail($id);
        $review->delete();

        return response()->json(['message' => 'Review deleted successfully']);
    }
}
