<?php

namespace App\Http\Controllers;

use App\Models\DigitalMachine;
use App\Models\HealthInstitution;
use App\Models\Member;
use App\Models\MembershipCategory;
use App\Models\RPartner;
use App\Models\TrainingPackage;
use Illuminate\Support\Facades\DB;
use App\Services\SliderService;
use App\Services\HeroCardService;
use App\Services\WhatWeDoImageService;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class HomeController extends Controller
{
    private SliderService $sliderService;
    private HeroCardService $heroCardService;
    private WhatWeDoImageService $whatWeDoImageService;

    public function __construct(
        SliderService $sliderService,
        HeroCardService $heroCardService,
        WhatWeDoImageService $whatWeDoImageService
    ) {
        $this->sliderService        = $sliderService;
        $this->heroCardService      = $heroCardService;
        $this->whatWeDoImageService = $whatWeDoImageService;
    }

    /**
     * Render the public homepage.
     * No redirects — guests and authenticated users both see the homepage.
     */
    public function index(): View
    {
        // Published sliders for the hero slider component (Requirement 13.4)
        $sliders   = $this->sliderService->getPublished();

        // Active hero cards for the info cards section (Requirement 13.4)
        $heroCards = $this->heroCardService->getActive();

        // What-We-Do images: keyed array slot → image_path (or null)
        // Requirements: 5.3, 5.4
        $whatWeDoImages = $this->whatWeDoImageService->getAllSlots()
            ->pluck('image_path', 'slot')
            ->toArray();

        // Cached 60 min — membership categories rarely change
        $membershipCategories = Cache::remember('home.membership_categories', 3600, fn () =>
            MembershipCategory::where('is_active', true)
                ->orderBy('sort_order')
                ->orderBy('name')
                ->get()
        );

        // Latest 12 published institutions — column-selective
        $institutions = HealthInstitution::where('is_published', true)
            ->where('listing_status', 'published')
            ->latest()
            ->limit(12)
            ->get(['id', 'name', 'slug', 'email', 'website_url', 'description', 'logo', 'city', 'country']);

        // All distinct cities from published institutions (for filter dropdown)
        $institutionCities = HealthInstitution::where('is_published', true)
            ->where('listing_status', 'published')
            ->whereNotNull('city')
            ->where('city', '!=', '')
            ->distinct()
            ->orderBy('city')
            ->pluck('city');

        // Latest 6 published machines — column-selective, ordered by published_at
        $machines = DigitalMachine::where('is_published', true)
            ->where('listing_status', 'published')
            ->orderByDesc('published_at')
            ->limit(6)
            ->get(['id', 'name', 'slug', 'brand', 'model', 'category', 'images', 'primary_image', 'description']);

        // All distinct categories from published machines (for filter dropdown)
        $machineCategories = DigitalMachine::where('is_published', true)
            ->where('listing_status', 'published')
            ->whereNotNull('category')
            ->where('category', '!=', '')
            ->distinct()
            ->orderBy('category')
            ->pluck('category');

        // All distinct brands from published machines (for filter dropdown)
        $machineBrands = DigitalMachine::where('is_published', true)
            ->where('listing_status', 'published')
            ->whereNotNull('brand')
            ->where('brand', '!=', '')
            ->distinct()
            ->orderBy('brand')
            ->pluck('brand');

        // Active directory partners — column-selective
        $partners = RPartner::where('partnership_status', 'active')
            ->where('show_in_directory', true)
            ->orderBy('partnership_start_date')
            ->get(['id', 'organization_name', 'slug', 'logo', 'organization_type', 'partnership_start_date', 'partnership_level']);

        // Live stats for hero counters
        $stats = [
            'institutions' => HealthInstitution::where('is_published', true)
                ->where('listing_status', 'published')
                ->count(),
            'machines' => DigitalMachine::where('is_published', true)
                ->where('listing_status', 'published')
                ->count(),
            'partners' => RPartner::where('partnership_status', 'active')
                ->where('show_in_directory', true)
                ->count(),
            'members'  => Member::where('status', 'active')->count(),
            'training' => TrainingPackage::count(),
        ];

        return view('home', compact('sliders', 'heroCards', 'whatWeDoImages', 'membershipCategories', 'institutions', 'institutionCities', 'machines', 'machineCategories', 'machineBrands', 'partners', 'stats'));
    }
}
