<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\Region;
use App\Models\Setting;
use App\Models\Webinar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GraduatesController extends Controller
{
    public function index(Request $request)
    {
        $settings = [];
        $settingsModel = Setting::where('name', 'graduates_page')->first();
        if (!empty($settingsModel) && !empty($settingsModel->value)) {
            $settings = json_decode($settingsModel->value, true);
        }

        $graduatesLimit = !empty($settings['graduates_limit']) ? (int)$settings['graduates_limit'] : 12;
        $showGraduates = !isset($settings['show_graduates']) || $settings['show_graduates'] == '1';
        $bannerImage = !empty($settings['banner_image']) ? $settings['banner_image'] : '/store/1/default_images/category_cover.png';
        $bannerTitle = !empty($settings['banner_title']) ? $settings['banner_title'] : 'الخريجين';
        $bannerDescription = !empty($settings['banner_description']) ? $settings['banner_description'] : '';
        $graduateImages = !empty($settings['graduate_images']) && is_array($settings['graduate_images']) ? $settings['graduate_images'] : [];
        $graduateCountries = !empty($settings['graduate_countries']) && is_array($settings['graduate_countries']) ? $settings['graduate_countries'] : [];
        $graduateFlags = !empty($settings['graduate_flags']) && is_array($settings['graduate_flags']) ? $settings['graduate_flags'] : [];

        $graduatesQuery = (new Certificate)->newQuery();
        
        // Always ensure we only get certificates with students
        $graduatesQuery->whereHas('student');

        $selectedGraduates = [];
        if (!empty($settings['selected_graduates']) && is_array($settings['selected_graduates']) && count($settings['selected_graduates']) > 0) {
            $selectedGraduates = $settings['selected_graduates'];
            \Log::info('Graduates Page - Selected Graduates Count: ' . count($selectedGraduates));
            \Log::info('Graduates Page - First 10 IDs: ' . json_encode(array_slice($selectedGraduates, 0, 10)));
            \Log::info('Graduates Page - Last 10 IDs: ' . json_encode(array_slice($selectedGraduates, -10)));
            $graduatesQuery->whereIn('id', $selectedGraduates);
        }

        if ($request->has('search') && !empty($request->search)) {
            $search = $request->search;

            $graduatesQuery = $graduatesQuery->whereHas('student', function ($query) use($search) {
                $query->where('full_name', 'like', '%'.$search.'%');
            });
        }

        if ($request->has('course') && !empty($request->course)) {
            $search = $request->course;

            $graduatesQuery = $graduatesQuery->whereHas('quiz', function ($query) use($search) {
                $query->whereHas('webinar', function ($query) use($search) {
                    $query->whereTranslationLike('title', "%$search%");
                });
            });
        }

        if ($request->has('country_id') && !empty($request->country_id)) {
            $search = $request->country_id;

            $graduatesQuery = $graduatesQuery->whereHas('student', function ($query) use($search) {
                $query->where('country_id', $search);
            });
        }

        if (!empty($selectedGraduates) && count($selectedGraduates) > 0) {
            // Get all certificates first
            $allCertificates = $graduatesQuery->get();
            \Log::info('Graduates Page - Fetched Certificates Count: ' . $allCertificates->count());
            
            // Filter certificates that have students
            $graduates = $showGraduates ? $allCertificates->filter(function($cert) {
                return !empty($cert->student);
            })->sortBy(function($cert) use ($selectedGraduates) {
                $index = array_search($cert->id, $selectedGraduates);
                return $index !== false ? $index : 999999;
            })->values() : collect([]);
            
            \Log::info('Graduates Page - Final Graduates Count (with student): ' . $graduates->count());
            \Log::info('Graduates Page - Missing Count: ' . (count($selectedGraduates) - $graduates->count()));
        } else {
            $graduates = $showGraduates ? $graduatesQuery->limit($graduatesLimit)->get() : collect([]);
        }

        $seoSettings = getSeoMetas('graduates');
        $pageTitle = !empty($settings['seo_title']) ? $settings['seo_title'] : (!empty($seoSettings['title']) ? $seoSettings['title'] : 'الخريجين');
        $pageDescription = !empty($settings['seo_description']) ? $settings['seo_description'] : (!empty($seoSettings['description']) ? $seoSettings['description'] : 'الخريجين');
        $pageRobot = getPageRobot('graduates');

        $courses = Webinar::all();

        $graduatesCount = $graduates->pluck('student_id')->unique()->count();

        $countries = Region::select(DB::raw('*, ST_AsText(geo_center) as geo_center'))
            ->where('type', Region::$country)
            ->get();

        $data = [];

        $data['title'] = $bannerTitle;
        $data['page'] = 'graduates';
        $data['pageTitle'] = $pageTitle;
        $data['pageDescription'] = $pageDescription;
        $data['pageRobot'] = $pageRobot;
        $data['graduatesCount'] = $graduatesCount;
        $data['graduates'] = $graduates;
        $data['courses'] = $courses;
        $data['countries'] = $countries;
        $data['bannerImage'] = $bannerImage;
        $data['bannerDescription'] = $bannerDescription;
        $data['showGraduates'] = $showGraduates;
        $data['graduateImages'] = $graduateImages;
        $data['graduateCountries'] = $graduateCountries;
        $data['graduateFlags'] = $graduateFlags;

        return view('web.default.pages.graduates', $data);
    }
}
