<?php
namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Api\BaseApiController;
use App\Models\Testimonial;
use Illuminate\Http\Request;


class TestimonialController extends BaseApiController
{
    /**
     * List all Testimonials (with optional filters).
     */
    public function getAllTestimonial(Request $request)
    {
        try {
            $tenant = app('tenant.context');
            $fid = $tenant->franchiseeId;

            $language = strtolower((string) $request->get('lang', $tenant->lang ?? 'en'));
            if ($language === '' || $language === 'english') {
                $language = 'en';
            }

            $translationFilter = function ($query) use ($language) {
                $query->where('language', $language)
                    ->where('status', 'publish');
            };

            $franchiseTestimonials = collect();
            $hiddenGlobalIds = [];

            if ($fid) {
                // Every row belonging to this franchise, fetched before any
                // publish filtering. When a franchise touches a global
                // testimonial the admin writes an override row pointing at it,
                // and that row's is_enabled flag is exactly what decides
                // whether the global still shows — so a disabled override must
                // not be filtered out before that decision is made.
                $franchiseRows = Testimonial::with('translations')
                    ->where('franchisee_id', $fid)
                    ->get();

                $hasPublishableTranslation = static function (Testimonial $t) use ($language): bool {
                    return collect($t->translations ?? [])->contains(function ($translation) use ($language) {
                        return strtolower((string) $translation->language) === $language
                            && strtolower((string) $translation->status) === 'publish';
                    });
                };

                // A global is replaced by its override when the franchise
                // switched it off, or when they wrote their own copy in this
                // language. An enabled override carrying no copy of its own
                // falls through to the global's text, which is what the admin
                // list shows for that row too.
                $hiddenGlobalIds = $franchiseRows
                    ->filter(fn(Testimonial $t) => $t->parent_testimonials_id
                        && (!$t->is_enabled || $hasPublishableTranslation($t)))
                    ->pluck('parent_testimonials_id')
                    ->unique()
                    ->values()
                    ->all();

                $franchiseTestimonials = $franchiseRows
                    ->filter(fn(Testimonial $t) => $t->is_enabled && $hasPublishableTranslation($t))
                    ->values();
            }

            $globalTestimonials = Testimonial::with('translations')
                ->where('is_global', true)
                ->where('is_enabled', true)
                ->whereHas('translations', $translationFilter)
                ->whereNotIn('id', $hiddenGlobalIds)
                ->get();

            $testimonials = $franchiseTestimonials
                ->merge($globalTestimonials)
                ->map(fn(Testimonial $t) => $this->projectPublicTestimonial($t, $language))
                ->filter()
                ->sortBy('order_no')
                ->values();

            if ($testimonials->isEmpty() && $language !== 'en') {
                return $this->getAllTestimonial(new Request(['lang' => 'en']));
            }

            return ApiResponse::success($testimonials, 'Testimonials fetched successfully');

        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }

    private function projectPublicTestimonial(Testimonial $testimonial, string $language): ?array
    {
        $translation = collect($testimonial->translations ?? [])->first(function ($t) use ($language) {
            return strtolower((string) $t->language) === $language
                && strtolower((string) $t->status) === 'publish';
        });

        if (!$translation) {
            return null;
        }

        return [
            'id' => $testimonial->id,
            'franchisee_id' => $testimonial->franchisee_id,
            'parent_testimonials_id' => $testimonial->parent_testimonials_id,
            'is_global' => (bool) $testimonial->is_global,
            'is_enabled' => (bool) $testimonial->is_enabled,
            'order_no' => $testimonial->order_no,
            'translation_id' => $translation->id,
            'language' => $translation->language,
            'parent_name' => $translation->parent_name,
            'role' => $translation->role,
            'comment' => $translation->comment,
            'status' => $translation->status,
            'created_at' => $testimonial->created_at,
            'updated_at' => $testimonial->updated_at,
        ];
    }
}
