<?php

namespace App\Http\Controllers;

use App\Models\Organization;
use App\Models\Slider;
use App\Models\StaffHistory;
use App\Models\Gallery;
use App\Models\GalleryType;
use App\Models\GalleryImage;
use Illuminate\Http\Request;

class LandingPageController extends Controller
{
    /**
     * Display the landing page with all dynamic content.
     */
    public function index(Request $request)
    {
        // Organization details (for header, footer, contact)
        $organization = Organization::first();

        // Published sliders ordered by sort order
        $sliders = Slider::published()->get();

        // Current staff (mediation experts)
        $experts = StaffHistory::with('organization')
            ->current()
            ->orderByStartDate('asc')
            ->get();

        // Gallery types for filtering
        $galleryTypes = GalleryType::active()->ordered()->get();

        // Gallery with images - paginated
        $galleryQuery = Gallery::with(['images', 'type'])
            ->published()
            ->ordered();

        // Filter by gallery type if requested
        if ($request->has('gallery_type') && $request->gallery_type) {
            $galleryQuery->ofType($request->gallery_type);
        }

        // Search galleries
        if ($request->has('search') && $request->search) {
            $galleryQuery->search($request->search);
        }

        $galleries = $galleryQuery->paginate(6);

        // Collect all images for the portfolio grid display
        $allImagesQuery = GalleryImage::with('gallery.type')
            ->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc');

        // Filter by gallery type
        if ($request->has('gallery_type') && $request->gallery_type) {
            $allImagesQuery->whereHas('gallery', function ($q) use ($request) {
                $q->where('gallery_type_id', $request->gallery_type);
            });
        }

        // Search images
        if ($request->has('search') && $request->search) {
            $allImagesQuery->where(function ($q) use ($request) {
                $q->where('title', 'like', "%{$request->search}%")
                  ->orWhere('description', 'like', "%{$request->search}%");
            });
        }

        $galleryImages = $allImagesQuery->paginate(12);

        return view('landing.index', compact(
            'organization',
            'sliders',
            'experts',
            'galleryTypes',
            'galleries',
            'galleryImages'
        ));
    }

    /**
     * Get organization details for API/AJAX calls.
     */
    public function getOrganization()
    {
        return Organization::first();
    }

    /**
     * Get sliders for API/AJAX calls.
     */
    public function getSliders()
    {
        return Slider::published()->get();
    }
}
