<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Portfolio;
use App\Models\PortfolioCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class PortfolioController extends Controller
{
    public function index(Request $request)
    {
        $query = Portfolio::with('category');

        if ($request->filled('search')) {
            $query->where('title', 'like', '%' . $request->search . '%')
                  ->orWhere('client_name', 'like', '%' . $request->search . '%');
        }
        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        $portfolios = $query->orderBy('sort_order')->paginate(15)->withQueryString();
        $categories = PortfolioCategory::active()->get();

        return view('admin.portfolios.index', compact('portfolios', 'categories'));
    }

    public function create()
    {
        $categories = PortfolioCategory::active()->get();
        return view('admin.portfolios.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $data = $this->validateData($request);
        $data['slug'] = Str::slug($data['title']) . '-' . Str::random(4);
        $data['cover_image'] = $request->file('cover_image')->store('portfolios', 'public');

        $gallery = [];
        if ($request->hasFile('gallery')) {
            foreach ($request->file('gallery') as $file) {
                $gallery[] = $file->store('portfolios/gallery', 'public');
            }
        }
        $data['gallery'] = $gallery;

        Portfolio::create($data);

        return redirect()->route('admin.portfolios.index')
            ->with('success', 'Ажил амжилттай нэмэгдлээ.');
    }

    public function edit(Portfolio $portfolio)
    {
        $categories = PortfolioCategory::active()->get();
        return view('admin.portfolios.edit', compact('portfolio', 'categories'));
    }

    public function update(Request $request, Portfolio $portfolio)
    {
        $data = $this->validateData($request, true);

        if ($request->hasFile('cover_image')) {
            if ($portfolio->cover_image) Storage::disk('public')->delete($portfolio->cover_image);
            $data['cover_image'] = $request->file('cover_image')->store('portfolios', 'public');
        }

        $gallery = $portfolio->gallery ?? [];

        // Хадгалж буй хуучин зурагнууд (front-end-ээс ирсэн)
        if ($request->filled('existing_gallery')) {
            $gallery = $request->existing_gallery;
        }

        // Шинэ нэмэгдсэн зурагнууд
        if ($request->hasFile('gallery')) {
            foreach ($request->file('gallery') as $file) {
                $gallery[] = $file->store('portfolios/gallery', 'public');
            }
        }
        $data['gallery'] = array_values($gallery);

        $portfolio->update($data);

        return redirect()->route('admin.portfolios.index')
            ->with('success', 'Ажил амжилттай шинэчлэгдлээ.');
    }

    public function destroy(Portfolio $portfolio)
    {
        if ($portfolio->cover_image) Storage::disk('public')->delete($portfolio->cover_image);
        foreach ($portfolio->gallery ?? [] as $g) Storage::disk('public')->delete($g);

        $portfolio->delete();

        if (request()->wantsJson()) {
            return response()->json(['success' => true]);
        }
        return back()->with('success', 'Ажил устгагдлаа.');
    }

    public function toggle(Portfolio $portfolio)
    {
        $portfolio->update(['is_active' => ! $portfolio->is_active]);
        return response()->json([
            'success'   => true,
            'is_active' => $portfolio->is_active,
        ]);
    }

    private function validateData(Request $request, bool $isUpdate = false): array
    {
        return $request->validate([
            'category_id'  => 'required|exists:portfolio_categories,id',
            'title'        => 'required|string|max:255',
            'client_name'  => 'nullable|string|max:255',
            'subtitle'     => 'nullable|string|max:255',
            'description'  => 'nullable|string',
            'cover_image'  => $isUpdate ? 'nullable|image|max:5120' : 'required|image|max:5120',
            'gallery.*'    => 'nullable|image|max:5120',
            'completed_at' => 'nullable|date',
            'external_url' => 'nullable|url|max:255',
            'is_featured'  => 'nullable|boolean',
            'is_active'    => 'nullable|boolean',
            'sort_order'   => 'nullable|integer',
        ]);
    }
}
