<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Review;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;

class ReviewSelectionController extends Controller
{
    public function index(Request $request)
    {
        $query = Review::with(['user', 'product'])->latest();
        if ($request->filled('rating')) {
            $query->where('rating', (int) $request->rating);
        }
        if ($request->filled('q')) {
            $q = trim($request->q);
            $query->where(function ($sub) use ($q) {
                $sub->where('comment', 'like', "%{$q}%");
            });
        }
        $perPage = (int) $request->input('per_page', 25);
        $perPage = max(10, min(100, $perPage));
        $reviews = $query->paginate($perPage)->withQueryString();
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        $preselectedCsv = $settings['homepage_review_ids'] ?? '';
        $preselected = collect(explode(',', $preselectedCsv))
            ->map(fn($v) => (int) trim($v))
            ->filter(fn($v) => $v > 0)
            ->values()
            ->all();
        // Fetch the currently selected reviews in saved order for sidebar
        $selectedReviews = collect();
        if (!empty($preselected)) {
            $placeholders = implode(',', $preselected);
            $selectedReviews = Review::with(['user', 'product'])
                ->whereIn('id', $preselected)
                ->orderByRaw("FIELD(id, $placeholders)")
                ->get();
        }
        return view('admin.reviews.select', compact('reviews', 'preselected', 'selectedReviews'));
    }

    public function save(Request $request)
    {
        $ids = $request->input('review_ids', []);
        if (!is_array($ids)) {
            $ids = [];
        }
        $ids = array_values(array_unique(array_filter(array_map(fn($v) => (int) $v, $ids))));

        // Merge with existing if requested
        $mode = $request->input('mode', 'merge'); // merge|replace
        if ($mode === 'merge') {
            $existingCsv = Setting::where('key', 'homepage_review_ids')->value('value') ?? '';
            $existing = array_values(array_unique(array_filter(array_map(fn($v) => (int) $v, explode(',', $existingCsv)))));
            $ids = array_values(array_unique(array_filter(array_merge($existing, $ids))));
        }

        // Keep only up to 5 for homepage cleanliness
        $ids = array_slice($ids, 0, 5);
        $csv = implode(',', $ids);
        Setting::updateOrCreate(['key' => 'homepage_review_ids'], ['value' => $csv]);
        // Lock homepage reviews to curated/selected mode
        Setting::updateOrCreate(['key' => 'homepage_reviews_mode'], ['value' => 'curated']);
        // Bust settings cache so frontend gets the latest immediately
        Cache::forget('global_settings');
        return redirect()->route('admin.reviews.select', $request->only(['q','rating','page','per_page']))
            ->with('success', 'Homepage reviews selection updated successfully.');
    }

    public function remove(Request $request)
    {
        $id = (int) $request->input('id');
        if ($id <= 0) {
            return redirect()->route('admin.reviews.select')->with('error', 'Invalid review id.');
        }
        $existingCsv = Setting::where('key', 'homepage_review_ids')->value('value') ?? '';
        $existing = array_values(array_unique(array_filter(array_map(fn($v) => (int) $v, explode(',', $existingCsv)))));
        $filtered = array_values(array_filter($existing, fn($v) => $v !== $id));
        $csv = implode(',', $filtered);
        Setting::updateOrCreate(['key' => 'homepage_review_ids'], ['value' => $csv]);
        // Keep curated mode on and bust cache
        Setting::updateOrCreate(['key' => 'homepage_reviews_mode'], ['value' => 'curated']);
        Cache::forget('global_settings');
        return redirect()->route('admin.reviews.select')->with('success', 'Review removed from homepage selection.');
    }
}
