<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\DiplomaRegistration;
use App\Models\Setting;
use App\Models\Webinar;
use Illuminate\Http\Request;

class DiplomaRegistrationController extends Controller
{
    public function index()
    {
        // Get settings from admin panel
        $settings = [];
        $settingsModel = Setting::where('name', 'diploma_registration')->first();
        if (!empty($settingsModel) && !empty($settingsModel->value)) {
            $settings = json_decode($settingsModel->value, true);
        }

        $diplomasLimit = !empty($settings['diplomas_limit']) ? (int)$settings['diplomas_limit'] : 50;
        $showDiplomasList = !isset($settings['show_diplomas_list']) || $settings['show_diplomas_list'] == '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'] : 'سجل الآن في برامج الدبلوم المتاحة';

        // Get all diploma programs (webinars)
        $diplomasQuery = Webinar::where('status', 'active')
            ->orderBy('created_at', 'desc');

        $diplomas = $showDiplomasList ? $diplomasQuery->limit($diplomasLimit)->get() : collect([]);

        // SEO Settings - use admin settings if available, otherwise use default SEO
        $seoSettings = getSeoMetas('diploma-registration');
        $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('diploma-registration');

        $requireCaptcha = !isset($settings['require_captcha']) || $settings['require_captcha'] == '1';

        $data = [
            'pageTitle' => $pageTitle,
            'pageDescription' => $pageDescription,
            'pageRobot' => $pageRobot,
            'diplomas' => $diplomas,
            'bannerImage' => $bannerImage,
            'bannerTitle' => $bannerTitle,
            'bannerDescription' => $bannerDescription,
            'showDiplomasList' => $showDiplomasList,
            'requireCaptcha' => $requireCaptcha
        ];

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

    public function store(Request $request)
    {
        // Check if captcha is required from settings
        $settings = [];
        $settingsModel = Setting::where('name', 'diploma_registration')->first();
        if (!empty($settingsModel) && !empty($settingsModel->value)) {
            $settings = json_decode($settingsModel->value, true);
        }
        $requireCaptcha = !isset($settings['require_captcha']) || $settings['require_captcha'] == '1';

        $validationRules = [
            'full_name' => 'required|string|min:3|max:255',
            'email' => 'required|email|max:255',
            'mobile' => 'required|string|max:20',
            'diploma_id' => 'required|exists:webinars,id',
            'message' => 'nullable|string|max:1000',
        ];

        if ($requireCaptcha) {
            $validationRules['captcha'] = 'required|captcha';
        }

        $this->validate($request, $validationRules);

        $data = $request->all();
        $data['created_at'] = time();
        $data['status'] = 'pending';

        DiplomaRegistration::create($data);

        // Get success message from settings
        $settings = [];
        $settingsModel = Setting::where('name', 'diploma_registration')->first();
        if (!empty($settingsModel) && !empty($settingsModel->value)) {
            $settings = json_decode($settingsModel->value, true);
        }
        $successMessage = !empty($settings['success_message']) ? $settings['success_message'] : 'تم إرسال طلب التسجيل بنجاح. سنتواصل معك قريباً.';

        // Send notification to admin
        $notifyOptions = [
            '[u.name]' => $data['full_name'],
            '[diploma.title]' => Webinar::find($data['diploma_id'])->title ?? 'غير محدد'
        ];
        sendNotification('new_diploma_registration', $notifyOptions, 1);

        return back()->with(['msg' => $successMessage]);
    }
}

