<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\Setting;
use App\Models\Translation\SettingTranslation;
use Illuminate\Http\Request;

class GraduatesSettingsController extends Controller
{
    public function index(Request $request)
    {
        $name = 'graduates_page';
        $this->authorize('admin_additional_pages');

        $value = [];

        $settings = Setting::where('name', $name)->first();

        $defaultLocale = getDefaultLocale();
        $locale = $request->get('locale', $defaultLocale);

        if (!empty($settings)) {
            storeContentLocale($locale, $settings->getTable(), $settings->id);

            if (!empty($settings->value)) {
                $value = json_decode($settings->value, true);
            }
        }

        $selectedCertificateIds = [];
        if (!empty($value['selected_graduates']) && is_array($value['selected_graduates'])) {
            $selectedCertificateIds = $value['selected_graduates'];
        }

        // Log total certificates count
        $totalCertificates = Certificate::count();
        \Log::info('Graduates Settings - Total Certificates: ' . $totalCertificates);
        
        // Log certificates with students count
        $certificatesWithStudents = Certificate::whereHas('student')->count();
        \Log::info('Graduates Settings - Certificates with Students: ' . $certificatesWithStudents);
        
        $certificates = Certificate::with(['student' => function($query) {
            $query->select('id', 'full_name', 'email');
        }])
            ->whereHas('student')
            ->orderBy('created_at', 'desc')
            ->get(); // Removed limit to show all graduates

        // Log fetched certificates count
        \Log::info('Graduates Settings - Fetched Certificates Count: ' . $certificates->count());
        
        // Log certificates with valid student
        $validCertificates = $certificates->filter(function($cert) {
            return !empty($cert->student);
        });
        \Log::info('Graduates Settings - Valid Certificates (with student): ' . $validCertificates->count());
        
        // Log first and last certificate IDs
        if ($certificates->count() > 0) {
            \Log::info('Graduates Settings - First Certificate ID: ' . $certificates->first()->id);
            \Log::info('Graduates Settings - Last Certificate ID: ' . $certificates->last()->id);
        }

        $data = [
            'pageTitle' => 'إعدادات صفحة الخريجين',
            'value' => $value,
            'selectedLocal' => $locale,
            'certificates' => $certificates,
            'selectedCertificateIds' => $selectedCertificateIds,
        ];

        return view('admin.additional_pages.graduates', $data);
    }

    public function store(Request $request)
    {
        $this->authorize('admin_additional_pages');

        $name = 'graduates_page';
        $values = $request->get('value', null);
        $locale = $request->get('locale', getDefaultLocale());

        // Log received data
        \Log::info('=== Graduates Settings Store ===');
        \Log::info('PHP max_input_vars: ' . ini_get('max_input_vars'));
        \Log::info('PHP post_max_size: ' . ini_get('post_max_size'));
        \Log::info('PHP max_input_time: ' . ini_get('max_input_time'));
        
        // Check for JSON input (new method to avoid max_input_vars limit)
        $selectedGraduatesJson = $request->get('selected_graduates_json');
        if (!empty($selectedGraduatesJson)) {
            $selectedIds = json_decode($selectedGraduatesJson, true);
            \Log::info('Selected Graduates from JSON: ' . count($selectedIds));
            if (is_array($selectedIds) && !empty($selectedIds)) {
                if (!isset($values)) {
                    $values = [];
                }
                $values['selected_graduates'] = $selectedIds;
            }
        }
        
        if (!empty($values)) {
            // Log selected graduates count before filtering
            if (isset($values['selected_graduates']) && is_array($values['selected_graduates'])) {
                \Log::info('Selected Graduates Count (before filter): ' . count($values['selected_graduates']));
                \Log::info('First 10 IDs: ' . json_encode(array_slice($values['selected_graduates'], 0, 10)));
                \Log::info('Last 10 IDs: ' . json_encode(array_slice($values['selected_graduates'], -10)));
            } else {
                \Log::info('Selected Graduates: Not set or not array');
            }
            
            $values = array_filter($values, function ($val) {
                if (is_array($val)) {
                    return array_filter($val);
                }

                return !empty($val);
            });
            
            // Log after filtering
            if (isset($values['selected_graduates']) && is_array($values['selected_graduates'])) {
                \Log::info('Selected Graduates Count (after filter): ' . count($values['selected_graduates']));
            }

            $values = json_encode($values);
            $values = str_replace('record', rand(1, 600), $values);
            
            \Log::info('JSON length: ' . strlen($values));

            $setting = Setting::firstOrCreate(
                ['name' => $name],
                [
                    'page' => 'other',
                    'created_at' => time(),
                    'updated_at' => time(),
                ]
            );

            if ($setting->wasRecentlyCreated === false) {
                $setting->update([
                    'page' => 'other',
                    'updated_at' => time(),
                ]);
            }

            $setting->refresh();

            if ($setting->id) {
                SettingTranslation::updateOrCreate(
                    [
                        'setting_id' => $setting->id,
                        'locale' => mb_strtolower($locale)
                    ],
                    [
                        'value' => $values,
                    ]
                );

                cache()->forget('settings.' . $name);
            }
        }

        removeContentLocale();

        return back()->with('msg', 'تم الحفظ بنجاح');
    }
}


