<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\HomeAcademySection;
use App\Models\HomeAcademySectionBox;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AcademySectionController extends Controller
{
    public function index()
    {
        $this->authorize('admin_settings_personalization');

        $academySection = HomeAcademySection::first();
        
        // إذا لم يكن هناك قسم، أنشئ واحداً افتراضياً
        if (empty($academySection)) {
            $academySection = HomeAcademySection::create([
                'title' => 'الأكاديمية تحتوي على',
                'status' => true,
                'order' => 0
            ]);
        }

        $data = [
            'pageTitle' => 'إدارة قسم الأكاديمية',
            'academySection' => $academySection->load('boxes'),
        ];

        return view('admin.settings.home_academy_section', $data);
    }

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

        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'status' => 'boolean',
            'boxes' => 'array',
            'boxes.*.title' => 'required|string|max:255',
            'boxes.*.description' => 'required|string',
            'boxes.*.icon' => 'nullable|string|max:255',
            'boxes.*.icon_type' => 'nullable|in:class,image',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $academySection = HomeAcademySection::first();
        
        if (empty($academySection)) {
            $academySection = HomeAcademySection::create([
                'title' => $request->input('title', 'الأكاديمية تحتوي على'),
                'status' => $request->has('status') ? 1 : 0,
            ]);
        } else {
            $academySection->update([
                'title' => $request->input('title'),
                'status' => $request->has('status') ? 1 : 0,
            ]);
        }

        // حذف الصناديق القديمة
        $academySection->boxes()->delete();

        // إضافة الصناديق الجديدة
        if ($request->has('boxes') && is_array($request->input('boxes'))) {
            foreach ($request->input('boxes') as $index => $boxData) {
                if (!empty($boxData['title']) && !empty($boxData['description'])) {
                    HomeAcademySectionBox::create([
                        'home_academy_section_id' => $academySection->id,
                        'title' => $boxData['title'],
                        'description' => $boxData['description'],
                        'icon' => $boxData['icon'] ?? null,
                        'icon_type' => $boxData['icon_type'] ?? 'class',
                        'order' => $index,
                    ]);
                }
            }
        }

        return redirect('/admin/settings/home-academy-section')->with('success', 'تم حفظ البيانات بنجاح');
    }

    public function updateStatus(Request $request, $id)
    {
        $this->authorize('admin_settings_personalization');

        $academySection = HomeAcademySection::findOrFail($id);
        $academySection->update([
            'status' => $request->input('status', 0)
        ]);

        return response()->json(['success' => true]);
    }

    // Webinar Academy Section Methods
    public function getWebinarAcademySection($webinarId)
    {
        $this->authorize('admin_webinars_edit');

        $webinar = \App\Models\Webinar::findOrFail($webinarId);
        $academySection = $webinar->academy_section;

        if ($academySection) {
            return response()->json([
                'status' => 'success',
                'academySection' => [
                    'id' => $academySection->id,
                    'title' => $academySection->title,
                    'status' => $academySection->status,
                    'boxes' => $academySection->boxes->map(function($box) {
                        return [
                            'id' => $box->id,
                            'title' => $box->title,
                            'description' => $box->description,
                            'icon' => $box->icon,
                            'icon_type' => $box->icon_type,
                        ];
                    })
                ]
            ]);
        }

        return response()->json([
            'status' => 'success',
            'academySection' => null
        ]);
    }

    public function storeWebinarAcademySection(Request $request)
    {
        $this->authorize('admin_webinars_edit');

        // Log all request data
        \Log::info('=== Webinar Academy Section Store Request ===');
        \Log::info('All Request Data:', $request->all());
        \Log::info('Request Method: ' . $request->method());
        \Log::info('Content Type: ' . $request->header('Content-Type'));

        // Filter out empty boxes before validation
        $boxes = $request->input('boxes', []);
        $filteredBoxes = [];
        if (is_array($boxes)) {
            foreach ($boxes as $box) {
                if (!empty($box['title']) && !empty($box['description'])) {
                    $filteredBoxes[] = $box;
                }
            }
        }
        
        // Replace boxes in request
        $request->merge(['boxes' => $filteredBoxes]);
        
        $validator = Validator::make($request->all(), [
            'webinar_id' => 'required|exists:webinars,id',
            'title' => 'required|string|max:255',
            'status' => 'boolean',
            'boxes' => 'required|array|min:1',
            'boxes.*.title' => 'required|string|max:255',
            'boxes.*.description' => 'required|string',
            'boxes.*.icon' => 'nullable|string|max:255',
            'boxes.*.icon_type' => 'nullable|in:class,image',
        ]);

        if ($validator->fails()) {
            \Log::error('Validation Failed:', $validator->errors()->toArray());
            \Log::error('Failed Data:', $request->all());
            
            return response()->json([
                'status' => 'error',
                'msg' => 'التحقق من البيانات فشل: ' . $validator->errors()->first(),
                'errors' => $validator->errors()->toArray()
            ], 422);
        }

        try {
            $webinar = \App\Models\Webinar::findOrFail($request->input('webinar_id'));
            \Log::info('Webinar found: ' . $webinar->id);
            
            // Try to get or create academy section
            $academySection = \App\Models\WebinarAcademySection::where('webinar_id', $webinar->id)->first();
            
            if (empty($academySection)) {
                \Log::info('Creating new academy section');
                
                $title = $request->input('title', 'الأكاديمية تحتوي على');
                // FORCE status to 1 (active) for new sections - always active by default
                $statusValue = $request->input('status');
                if ($statusValue === '0' || $statusValue === 0) {
                    $status = 0;
                    \Log::info('Status explicitly set to 0 (inactive) for new section');
                } else {
                    $status = 1; // Always default to 1 (active) for new sections
                    \Log::info('Status set to 1 (active) - default for new section');
                }
                
                \Log::info('Data to create:', [
                    'webinar_id' => $webinar->id,
                    'title' => $title,
                    'status' => $status,
                ]);
                
                // Use DB facade to ensure creation
                $academySectionId = \DB::table('webinar_academy_sections')->insertGetId([
                    'webinar_id' => $webinar->id,
                    'title' => $title,
                    'status' => $status,
                    'order' => 0,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
                
                \Log::info('Academy section created with ID: ' . $academySectionId);
                
                // Reload the model
                $academySection = \App\Models\WebinarAcademySection::find($academySectionId);
                
                // Verify the section was created
                if (empty($academySection) || empty($academySection->id) || $academySection->id == 0) {
                    \Log::error('Failed to create academy section - ID is 0 or empty');
                    throw new \Exception('فشل في إنشاء قسم الأكاديمية');
                }
            } else {
                \Log::info('Updating existing academy section: ' . $academySection->id);
                $title = $request->input('title', 'الأكاديمية تحتوي على');
                $statusValue = $request->input('status');
                
                // FORCE status to 1 (active) - Always make it active
                // We force it to 1 to ensure the section is always visible
                $status = 1;
                \Log::info('Status forced to 1 (active) - section will always be visible');
                
                \Log::info('Data to update:', [
                    'title' => $title,
                    'status' => $status,
                    'status_raw' => $statusValue,
                    'status_type' => gettype($statusValue),
                ]);
                
                $academySection->update([
                    'title' => $title,
                    'status' => $status,
                ]);
                
                \Log::info('Academy section updated successfully with status: ' . $status);
            }

            // Verify academy section has valid ID before proceeding
            if (empty($academySection->id) || $academySection->id == 0) {
                \Log::error('Academy section ID is invalid: ' . $academySection->id);
                throw new \Exception('معرف قسم الأكاديمية غير صحيح');
            }

            \Log::info('Using academy section ID: ' . $academySection->id);

            // Delete old boxes
            $deletedCount = $academySection->boxes()->delete();
            \Log::info('Deleted ' . $deletedCount . ' old boxes');

            // Add new boxes
            $boxesData = $request->input('boxes', []);
            \Log::info('Boxes data received:', $boxesData);
            
            if (is_array($boxesData) && count($boxesData) > 0) {
                foreach ($boxesData as $index => $boxData) {
                    \Log::info('Processing box ' . $index . ':', $boxData);
                    
                    if (!empty($boxData['title']) && !empty($boxData['description'])) {
                        \Log::info('Creating box with section_id: ' . $academySection->id);
                        \Log::info('Box data:', [
                            'webinar_academy_section_id' => $academySection->id,
                            'title' => $boxData['title'],
                            'description' => $boxData['description'],
                            'icon' => $boxData['icon'] ?? null,
                            'icon_type' => $boxData['icon_type'] ?? 'class',
                            'order' => $index,
                        ]);
                        
                        $box = \App\Models\WebinarAcademySectionBox::create([
                            'webinar_academy_section_id' => $academySection->id,
                            'title' => $boxData['title'],
                            'description' => $boxData['description'],
                            'icon' => $boxData['icon'] ?? null,
                            'icon_type' => $boxData['icon_type'] ?? 'class',
                            'order' => $index,
                        ]);
                        \Log::info('Box created with ID: ' . $box->id);
                    } else {
                        \Log::warning('Skipping box ' . $index . ' - missing title or description');
                    }
                }
            } else {
                \Log::warning('No boxes data or empty array');
            }

            \Log::info('=== Academy Section Saved Successfully ===');
            
            return response()->json([
                'status' => 'success',
                'msg' => 'تم حفظ قسم الأكاديمية بنجاح'
            ]);
        } catch (\Exception $e) {
            \Log::error('Exception in storeWebinarAcademySection: ' . $e->getMessage());
            \Log::error('Stack trace: ' . $e->getTraceAsString());
            
            return response()->json([
                'status' => 'error',
                'msg' => 'حدث خطأ: ' . $e->getMessage()
            ], 500);
        }
    }
}
