<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Home Controller
 *
 * Handles the homepage of the Gmind Institute website.
 * Each section's data is fetched inside a try-catch so that
 * a single failing query does NOT break the entire page.
 */
class HomeController extends Controller
{
    /**
     * Display the home page.
     *
     * Gathers data for all home page sections with individual
     * error handling so one broken section won't crash the page.
     *
     * @return void
     */
    public function index(): void
    {
        // Initialise all section data with safe defaults
        $sliders         = [];
        $announcements   = [];
        $featuredCourses = [];
        $branches        = [];
        $affiliations    = [];
        $partners        = [];
        $galleryItems    = [];
        $toppers         = [];
        $testimonials    = [];
        $avgRating       = 0.0;
        $stats = [
            'total_students'   => '0',
            'total_branches'   => '0',
            'total_courses'    => '0',
            'placement_rate'   => '0',
            'years_experience' => '0',
        ];
        $settings = [];

        // --- 1. Sliders ---
        try {
            $sliderModel = $this->model('Slider');
            $sliders = $sliderModel->getActive();
        } catch (\Throwable $e) {
            error_log('Home sliders error: ' . $e->getMessage());
        }

        // --- 2. Announcements ---
        try {
            $announcementModel = $this->model('Announcement');
            $announcements = $announcementModel->getActive();
        } catch (\Throwable $e) {
            error_log('Home announcements error: ' . $e->getMessage());
        }

        // --- 3. Featured Courses ---
        try {
            $courseModel = $this->model('Course');
            $featuredCourses = $courseModel->getFeatured(6);
            // If no featured courses, get all active courses (limit 6)
            if (empty($featuredCourses)) {
                $featuredCourses = $courseModel->where('active', 1);
                $featuredCourses = array_slice($featuredCourses, 0, 6);
            }
        } catch (\Throwable $e) {
            error_log('Home courses error: ' . $e->getMessage());
        }

        // --- 4. Branches ---
        try {
            $branchModel = $this->model('Branch');
            $branches = $branchModel->getLatest(8);
        } catch (\Throwable $e) {
            error_log('Home branches error: ' . $e->getMessage());
        }

        // --- 5. Affiliations & Partners ---
        try {
            $affiliationModel = $this->model('Affiliation');
            $affiliations = $affiliationModel->getByType('affiliation');
            $partners     = $affiliationModel->getByType('partner');
        } catch (\Throwable $e) {
            error_log('Home affiliations error: ' . $e->getMessage());
        }

        // --- 6. Gallery ---
        try {
            $galleryModel = $this->model('Gallery');
            $galleryItems = $galleryModel->getForHome(8);
        } catch (\Throwable $e) {
            error_log('Home gallery error: ' . $e->getMessage());
        }

        // --- 7. Toppers ---
        try {
            $topperModel = $this->model('Topper');
            $toppers = $topperModel->getActive(8);
        } catch (\Throwable $e) {
            error_log('Home toppers error: ' . $e->getMessage());
        }

        // --- 8. Testimonials ---
        try {
            $testimonialModel = $this->model('Testimonial');
            $testimonials = $testimonialModel->getApproved(6);
            $avgRating    = $testimonialModel->getAverageRating();
        } catch (\Throwable $e) {
            error_log('Home testimonials error: ' . $e->getMessage());
        }

        // --- 9. Stats ---
        try {
            $settingModel = $this->model('Setting');
            $settings = $settingModel->getAll();
            $stats['total_students']   = $settingModel->get('stat_total_students') ?? '0';
            $stats['total_courses']    = $settingModel->get('stat_total_courses') ?? '0';
            $stats['placement_rate']   = $settingModel->get('stat_placement_rate') ?? '0';
            $stats['years_experience'] = $settingModel->get('stat_years_experience') ?? '0';
        } catch (\Throwable $e) {
            error_log('Home settings error: ' . $e->getMessage());
        }

        // --- 10. Home Page FAQs ---
        $homeFaqs = [];
        try {
            $faqModel = $this->model('Faq');
            $homeFaqs = $faqModel->getForHome(6);
        } catch (\Throwable $e) {
            error_log('Home FAQs error: ' . $e->getMessage());
        }

        // --- 11. Offer Popup ---
        $offerPopup = [
            'enabled'     => !empty($settings['offer_popup_enabled']) && $settings['offer_popup_enabled'] === '1',
            'title'       => $settings['offer_popup_title']       ?? '',
            'description' => $settings['offer_popup_description'] ?? '',
            'image'       => $settings['offer_popup_image']       ?? '',
            'link'        => $settings['offer_popup_link']        ?? '',
            'link_text'   => $settings['offer_popup_link_text']   ?? 'Learn More',
        ];

        // Branch count (separate try-catch in case Branch model works but Setting doesn't)
        try {
            $branchModel2 = $this->model('Branch');
            $stats['total_branches'] = (string) $branchModel2->getActiveCount();
        } catch (\Throwable $e) {
            // Fallback: count branches we already fetched
            $stats['total_branches'] = (string) count($branches);
        }

        // Generate CSRF token for the page
        $csrfToken = generateCsrfToken();

        // Pass all data to the view
        $this->view('home/index', [
            'sliders'         => $sliders,
            'announcements'   => $announcements,
            'featuredCourses' => $featuredCourses,
            'branches'        => $branches,
            'affiliations'    => $affiliations,
            'partners'        => $partners,
            'galleryItems'    => $galleryItems,
            'toppers'         => $toppers,
            'testimonials'    => $testimonials,
            'avgRating'       => $avgRating,
            'stats'           => $stats,
            'settings'        => $settings,
            'homeFaqs'        => $homeFaqs,
            'offerPopup'      => $offerPopup,
            'csrfToken'       => $csrfToken,
            'currentPage'     => 'home',
        ]);
    }
}
