<?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 ---
        // Strategy: getFeatured() returns courses flagged is_featured=1.
        // If empty (no featured flag set OR column missing), fall back to all
        // active courses. If THAT is also empty (no courses at all), $featuredCourses
        // stays empty and the home view shows static fallback cards.
        try {
            $courseModel = $this->model('Course');
            $featuredCourses = $courseModel->getFeatured(6);
        } catch (\Throwable $e) {
            error_log('Home courses (getFeatured) error: ' . $e->getMessage());
            $featuredCourses = [];
        }

        // If no featured courses, fall back to all active courses (limit 6)
        if (empty($featuredCourses)) {
            try {
                $courseModel = $this->model('Course');
                $allActive = $courseModel->where('active', 1);
                if (!empty($allActive)) {
                    $featuredCourses = array_slice($allActive, 0, 6);
                }
            } catch (\Throwable $e) {
                error_log('Home courses (fallback) 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 ---
        // Read offer popup settings DIRECTLY from database.
        // Check BOTH column pairs: key_name/value (old) AND setting_key/setting_value (new)
        // because the settings table has a dual-column schema.
        $offerPopup = [
            'enabled'     => false,
            'title'       => '',
            'description' => '',
            'image'       => '',
            'link'        => '',
            'link_text'   => 'Learn More',
        ];

        try {
            // First try setting_key / setting_value (new schema)
            $popStmt = $this->db->prepare(
                'SELECT `setting_key`, `setting_value` FROM `settings` WHERE `setting_key` LIKE :pattern'
            );
            $popStmt->execute([':pattern' => 'offer_popup_%']);
            $popRows = $popStmt->fetchAll(\PDO::FETCH_ASSOC);

            $rawPopup = [];
            if (!empty($popRows)) {
                foreach ($popRows as $row) {
                    if (!empty($row['setting_key'])) {
                        $rawPopup[$row['setting_key']] = $row['setting_value'];
                    }
                }
            }

            // Also check key_name / value (old schema) — fill any missing keys
            $popStmt2 = $this->db->prepare(
                'SELECT `key_name`, `value` FROM `settings` WHERE `key_name` LIKE :pattern'
            );
            $popStmt2->execute([':pattern' => 'offer_popup_%']);
            $popRows2 = $popStmt2->fetchAll(\PDO::FETCH_ASSOC);

            if (!empty($popRows2)) {
                foreach ($popRows2 as $row) {
                    if (!empty($row['key_name'])) {
                        // Old schema value takes priority only if new schema doesn't have it
                        if (!isset($rawPopup[$row['key_name']]) || $rawPopup[$row['key_name']] === '') {
                            $rawPopup[$row['key_name']] = $row['value'];
                        }
                    }
                }
            }

            // Map to view array
            if (!empty($rawPopup)) {
                $offerPopup['enabled']     = ($rawPopup['offer_popup_enabled'] ?? '0') === '1';
                $offerPopup['title']       = $rawPopup['offer_popup_title']       ?? '';
                $offerPopup['description'] = $rawPopup['offer_popup_description'] ?? '';
                $offerPopup['image']       = $rawPopup['offer_popup_image']       ?? '';
                $offerPopup['link']        = $rawPopup['offer_popup_link']        ?? '';
                $offerPopup['link_text']   = $rawPopup['offer_popup_link_text']   ?? 'Learn More';
            }
        } catch (\Throwable $e) {
            error_log('Offer popup query error: ' . $e->getMessage());
        }

        // 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);
        }

        // --- 12. Newsletter Settings ---
        // Read newsletter settings DIRECTLY from database.
        // Check BOTH column pairs: key_name/value (old) AND setting_key/setting_value (new)
        $newsletterSettings = [
            'newsletter_enabled'        => '1',
            'newsletter_title'          => 'Stay Updated with Gmind Institute',
            'newsletter_subtitle'       => 'Subscribe to get latest updates on new courses, batch schedules, and exclusive offers directly in your inbox.',
            'newsletter_button_text'    => 'Subscribe Now',
            'newsletter_success_message'=> 'Thank you for subscribing! You will receive updates from Gmind Institute.',
        ];

        try {
            // First try setting_key / setting_value (new schema)
            $nlStmt = $this->db->prepare(
                'SELECT `setting_key`, `setting_value` FROM `settings` WHERE `setting_key` LIKE :pattern'
            );
            $nlStmt->execute([':pattern' => 'newsletter_%']);
            $nlRows = $nlStmt->fetchAll(\PDO::FETCH_ASSOC);

            $rawNl = [];
            if (!empty($nlRows)) {
                foreach ($nlRows as $row) {
                    if (!empty($row['setting_key'])) {
                        $rawNl[$row['setting_key']] = $row['setting_value'];
                    }
                }
            }

            // Also check key_name / value (old schema) — fill any missing keys
            $nlStmt2 = $this->db->prepare(
                'SELECT `key_name`, `value` FROM `settings` WHERE `key_name` LIKE :pattern'
            );
            $nlStmt2->execute([':pattern' => 'newsletter_%']);
            $nlRows2 = $nlStmt2->fetchAll(\PDO::FETCH_ASSOC);

            if (!empty($nlRows2)) {
                foreach ($nlRows2 as $row) {
                    if (!empty($row['key_name'])) {
                        if (!isset($rawNl[$row['key_name']]) || $rawNl[$row['key_name']] === '') {
                            $rawNl[$row['key_name']] = $row['value'];
                        }
                    }
                }
            }

            // Merge with defaults
            if (!empty($rawNl)) {
                $newsletterSettings = array_merge($newsletterSettings, $rawNl);
            }
        } catch (\Throwable $e) {
            error_log('Newsletter settings query error: ' . $e->getMessage());
        }

        // ═══════════════════════════════════════════════════════════════════
        // NEW SECTIONS — Video Testimonials, Featured Batches, Countdown
        // ═══════════════════════════════════════════════════════════════════

        // --- 13. Video Testimonials ---
        $videoTestimonials = [];
        try {
            $videoTestimonialModel = $this->model('VideoTestimonial');
            $videoTestimonials = $videoTestimonialModel->getActive(8);
        } catch (\Throwable $e) {
            error_log('Home video testimonials error: ' . $e->getMessage());
        }

        // --- 14. Featured Batches ---
        $featuredBatches = [];
        try {
            $batchModel = $this->model('BatchSchedule');
            $featuredBatches = $batchModel->getFeatured(4);
        } catch (\Throwable $e) {
            error_log('Home featured batches error: ' . $e->getMessage());
        }

        // --- 15. Countdown Timer ---
        // Priority: 1) Batch with show_countdown=1  2) Settings countdown_target_date
        $countdownBatch = null;
        try {
            $batchModel2 = $this->model('BatchSchedule');
            $countdownBatch = $batchModel2->getCountdownBatch();
        } catch (\Throwable $e) {
            error_log('Home countdown batch error: ' . $e->getMessage());
        }

        // If no batch countdown, check settings
        $countdownData = null;
        if ($countdownBatch) {
            // Batch start_date is a DATE column (YYYY-MM-DD). Append T09:00:00 for 9 AM local.
            $countdownData = [
                'title'    => $countdownBatch['batch_name'] . ' Starting Soon!',
                'subtitle' => 'Limited seats available. Don\'t miss out!',
                'date'     => $countdownBatch['start_date'] . 'T09:00:00',
                'btn_text' => 'Enroll Now',
                'btn_url'  => BASE_PATH . '/admission',
            ];
        } else {
            // Check settings for manual countdown
            $cdEnabled = $settings['countdown_enabled'] ?? '0';
            $cdDate    = $settings['countdown_target_date'] ?? '';
            if ($cdEnabled === '1' && !empty($cdDate)) {
                // datetime-local inputs return 'YYYY-MM-DDTHH:MM' — that's already
                // valid ISO format for JS new Date() (parsed as local time).
                // If the stored value uses a space separator instead, normalise to 'T'.
                // Ensure seconds are present so the format is 'YYYY-MM-DDTHH:MM:SS'.
                $normalisedDate = $cdDate;
                $normalisedDate = str_replace(' ', 'T', $normalisedDate);
                if (preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/', $normalisedDate)) {
                    $normalisedDate .= ':00';
                }

                $countdownData = [
                    'title'    => $settings['countdown_title'] ?? 'Next Batch Starting Soon!',
                    'subtitle' => $settings['countdown_subtitle'] ?? 'Limited seats available. Enroll now!',
                    'date'     => $normalisedDate,
                    'btn_text' => $settings['countdown_button_text'] ?? 'Enroll Now',
                    'btn_url'  => $settings['countdown_button_url'] ?? BASE_PATH . '/admission',
                ];
            }
        }

        // 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,
            'videoTestimonials'   => $videoTestimonials,
            'featuredBatches'     => $featuredBatches,
            'countdownData'       => $countdownData,
            'stats'               => $stats,
            'settings'            => $settings,
            'homeFaqs'            => $homeFaqs,
            'offerPopup'          => $offerPopup,
            'newsletterSettings'  => $newsletterSettings,
            'csrfToken'           => $csrfToken,
            'currentPage'         => 'home',
        ]);
    }
}
