<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreBannerRequest;
use App\Http\Requests\Api\UpdateBannerRequest;
use App\Models\Banner;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    private function storageUrl(string $path): string
    {
        // APP_URL (dans .env) est la source de vérité pour construire des URLs absolues.
        $appUrl = (string) (env('APP_URL') ?: config('app.url') ?: url('/'));
        $appUrl = rtrim($appUrl, '/');

        return $appUrl . '/storage/' . ltrim($path, '/');
    }

    private function bannerResponseFields(Banner $banner): array
    {
        return [
            'id' => $banner->id,
            'title' => $banner->title,
            'subtitle' => $banner->subtitle,
            'image_url' => $banner->image_url,
            'image_url_2' => $banner->image_url_2,
            'image_url_3' => $banner->image_url_3,
            'cta_label' => $banner->cta_label,
            'whatsapp_number' => $banner->whatsapp_number,
            'whatsapp_message' => $banner->whatsapp_message,
            'is_active' => $banner->is_active,
            'sort_order' => $banner->sort_order,
            'created_at' => $banner->created_at,
            'updated_at' => $banner->updated_at,
        ];
    }

    public function index(): JsonResponse
    {
        $banners = Banner::query()
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->orderByDesc('id')
            ->get([
                'id',
                'title',
                'subtitle',
                'image_url',
                'image_url_2',
                'image_url_3',
                'cta_label',
                'whatsapp_number',
                'whatsapp_message',
            ]);

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

    public function show(Banner $banner): JsonResponse
    {
        if (! $banner->is_active) {
            abort(404);
        }

        return response()->json([
            'data' => [
                'id' => $banner->id,
                'title' => $banner->title,
                'subtitle' => $banner->subtitle,
                'image_url' => $banner->image_url,
                'image_url_2' => $banner->image_url_2,
                'image_url_3' => $banner->image_url_3,
                'cta_label' => $banner->cta_label,
                'whatsapp_number' => $banner->whatsapp_number,
                'whatsapp_message' => $banner->whatsapp_message,
                'created_at' => $banner->created_at,
            ],
        ]);
    }

    // -----------------------------
    // Admin CRUD
    // -----------------------------

    public function adminIndex(): JsonResponse
    {
        // Accessible via routes role:super_admin,admin.
        $banners = Banner::query()
            ->orderByDesc('id')
            ->get();

        return response()->json([
            'data' => $banners->map(fn (Banner $b) => $this->bannerResponseFields($b)),
        ]);
    }

    public function adminShow(Banner $banner): JsonResponse
    {
        return response()->json([
            'data' => $this->bannerResponseFields($banner),
        ]);
    }

    public function adminStore(StoreBannerRequest $request): JsonResponse
    {
        $data = $request->validated();

        $whatsappNumber = $data['whatsapp_number'] ?? null;
        if ($whatsappNumber) {
            $whatsappNumber = preg_replace('/\D+/', '', $whatsappNumber);
        }

        $banner = Banner::create([
            'title' => $data['title'],
            'subtitle' => $data['subtitle'] ?? null,
            'cta_label' => $data['cta_label'] ?? null,
            'whatsapp_number' => $whatsappNumber,
            'whatsapp_message' => $data['whatsapp_message'] ?? null,
            'is_active' => $data['is_active'] ?? true,
            'sort_order' => $data['sort_order'] ?? 0,

            // images (optionnel)
            'image_url' => $data['image_url'] ?? null,
            'image_url_2' => null,
            'image_url_3' => null,
        ]);

        $files = $request->file('images', []);
        if (is_array($files) && count($files) > 0) {
            $urls = [];
            foreach ($files as $file) {
                $path = $file->store('banners', 'public');
                $urls[] = $this->storageUrl($path);
            }

            $banner->update([
                'image_url' => $urls[0] ?? $banner->image_url,
                'image_url_2' => $urls[1] ?? null,
                'image_url_3' => $urls[2] ?? null,
            ]);
        }

        return response()->json([
            'data' => $this->bannerResponseFields($banner->fresh()),
        ], 201);
    }

    public function adminUpdate(UpdateBannerRequest $request, Banner $banner): JsonResponse
    {
        $data = $request->validated();

        $whatsappNumber = $data['whatsapp_number'] ?? $banner->whatsapp_number;
        if ($whatsappNumber) {
            $whatsappNumber = preg_replace('/\D+/', '', (string) $whatsappNumber);
        }

        $payload = [
            'title' => $data['title'] ?? $banner->title,
            'subtitle' => array_key_exists('subtitle', $data) ? ($data['subtitle'] ?? null) : $banner->subtitle,
            'cta_label' => $data['cta_label'] ?? $banner->cta_label,
            'whatsapp_number' => $whatsappNumber,
            'whatsapp_message' => $data['whatsapp_message'] ?? $banner->whatsapp_message,
            'is_active' => $data['is_active'] ?? $banner->is_active,
            'sort_order' => $data['sort_order'] ?? $banner->sort_order,
        ];

        // Si une URL image est envoyée directement
        if (array_key_exists('image_url', $data) && $data['image_url'] !== null) {
            $payload['image_url'] = $data['image_url'];
        }

        $banner->update($payload);

        // Upload images[] => remplace les 3 emplacements (si des fichiers sont fournis)
        $files = $request->file('images', []);
        if (is_array($files) && count($files) > 0) {
            $urls = [];
            foreach ($files as $file) {
                $path = $file->store('banners', 'public');
                $urls[] = $this->storageUrl($path);
            }

            $banner->update([
                'image_url' => $urls[0] ?? $banner->image_url,
                'image_url_2' => $urls[1] ?? null,
                'image_url_3' => $urls[2] ?? null,
            ]);
        }

        return response()->json([
            'data' => $this->bannerResponseFields($banner->fresh()),
        ]);
    }

    public function adminDestroy(Request $request, Banner $banner): JsonResponse
    {
        $banner->delete();

        return response()->json([
            'message' => 'Banner supprimé.',
        ]);
    }
}

