<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\MontessoriMembershipApplication;
use App\Models\Notification;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

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

        // Banner settings
        $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'] : 'انضم إلى عضوية المونتيسوري واحصل على مزايا حصرية';

        // SEO Settings
        $seoSettings = getSeoMetas('montessori-membership');
        $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('montessori-membership');

        // FAQ Items - can be managed from admin later
        $faqs = !empty($settings['faqs']) ? $settings['faqs'] : [];

        // Benefits Section Background
        $benefitsSectionBg = !empty($settings['benefits_section_bg']) ? $settings['benefits_section_bg'] : null;

        // Membership Price
        $membershipPrice = !empty($settings['membership_price']) ? $settings['membership_price'] : 100;
        $membershipPriceDescription = !empty($settings['membership_price_description']) ? $settings['membership_price_description'] : '';

        // Introduction Section
        $introLogo = !empty($settings['intro_logo']) ? $settings['intro_logo'] : null;
        $introTitle = !empty($settings['intro_title']) ? $settings['intro_title'] : 'عن رابطة مونتيسوري الدولية';
        $introContent = !empty($settings['intro_content']) ? $settings['intro_content'] : '';

        // Benefits Section
        $benefitsTitle = !empty($settings['benefits_title']) ? $settings['benefits_title'] : 'مزايا العضوية';
        $benefitsDescription = !empty($settings['benefits_description']) ? $settings['benefits_description'] : 'الانضمام إلى رابطة مونتيسوري المهنية يوفّر للأعضاء منظومة متكاملة من الدعم والفرص الحقيقية';
        $benefitsItems = !empty($settings['benefits_items']) && is_array($settings['benefits_items']) ? $settings['benefits_items'] : [];

        // Eligibility Section
        $eligibilityTitle = !empty($settings['eligibility_title']) ? $settings['eligibility_title'] : 'من له حق المشاركة في الرابطة؟';
        $eligibilityItems = [];
        if (!empty($settings['eligibility_items'])) {
            if (is_array($settings['eligibility_items'])) {
                $eligibilityItems = $settings['eligibility_items'];
            } else {
                // Split by newline if it's a string
                $eligibilityItems = array_filter(array_map('trim', explode("\n", $settings['eligibility_items'])));
            }
        }

        // Apply Section
        $applyFeeText = !empty($settings['apply_fee_text']) ? $settings['apply_fee_text'] : 'تكلفة الاشتراك السنوية';
        $applyButtonText = !empty($settings['apply_button_text']) ? $settings['apply_button_text'] : 'تقدم الآن';
        $applyBenefitsText = !empty($settings['apply_benefits_text']) ? $settings['apply_benefits_text'] : 'واحصل على وصول فوري للمزايا والفرص الحصرية';

        // Form Fields
        $formFields = !empty($settings['form_fields']) && is_array($settings['form_fields']) ? $settings['form_fields'] : [];

        // Color Settings
        $colorBannerTitle = !empty($settings['color_banner_title']) ? $settings['color_banner_title'] : '#ffffff';
        $colorBannerDescription = !empty($settings['color_banner_description']) ? $settings['color_banner_description'] : '#ffffff';
        $colorSectionTitle = !empty($settings['color_section_title']) ? $settings['color_section_title'] : '#1e3a8a';
        $colorBodyText = !empty($settings['color_body_text']) ? $settings['color_body_text'] : '#4b5563';
        $colorBenefitTitle = !empty($settings['color_benefit_title']) ? $settings['color_benefit_title'] : '#1e40af';
        $colorPrice = !empty($settings['color_price']) ? $settings['color_price'] : '#ef4444';
        $colorApplyButtonBg = !empty($settings['color_apply_button_bg']) ? $settings['color_apply_button_bg'] : '#449cef';
        $colorApplyButtonText = !empty($settings['color_apply_button_text']) ? $settings['color_apply_button_text'] : '#ffffff';
        $colorFaqQuestion = !empty($settings['color_faq_question']) ? $settings['color_faq_question'] : '#1e3a8a';

        // Helper function to clean null bytes and sanitize strings
        $cleanString = function($value) {
            if (is_string($value)) {
                $value = str_replace("\0", '', $value);
                $value = trim($value);
            }
            return $value;
        };

        // Clean all string values
        $bannerImage = $cleanString($bannerImage);
        $bannerTitle = $cleanString($bannerTitle);
        $bannerDescription = $cleanString($bannerDescription);
        $pageTitle = $cleanString($pageTitle);
        $pageDescription = $cleanString($pageDescription);
        $benefitsSectionBg = $cleanString($benefitsSectionBg);
        $introLogo = $cleanString($introLogo);
        $introTitle = $cleanString($introTitle);
        $introContent = $cleanString($introContent);
        $benefitsTitle = $cleanString($benefitsTitle);
        $benefitsDescription = $cleanString($benefitsDescription);
        $eligibilityTitle = $cleanString($eligibilityTitle);
        $applyFeeText = $cleanString($applyFeeText);
        $applyButtonText = $cleanString($applyButtonText);
        $applyBenefitsText = $cleanString($applyBenefitsText);

        // Clean benefits items
        if (!empty($benefitsItems) && is_array($benefitsItems)) {
            foreach ($benefitsItems as &$item) {
                if (isset($item['title'])) {
                    $item['title'] = $cleanString($item['title']);
                }
                if (isset($item['description'])) {
                    $item['description'] = $cleanString($item['description']);
                }
            }
            unset($item);
        }

        // Clean eligibility items
        if (!empty($eligibilityItems) && is_array($eligibilityItems)) {
            foreach ($eligibilityItems as &$item) {
                $item = $cleanString($item);
            }
            unset($item);
        }

        // Clean FAQs
        if (!empty($faqs) && is_array($faqs)) {
            foreach ($faqs as &$faq) {
                if (isset($faq['question'])) {
                    $faq['question'] = $cleanString($faq['question']);
                }
                if (isset($faq['answer'])) {
                    $faq['answer'] = $cleanString($faq['answer']);
                }
            }
            unset($faq);
        }

        // Clean membership price values
        $membershipPriceDescription = $cleanString($membershipPriceDescription);

        // Split intro content into paragraphs
        $introParagraphs = [];
        if (!empty($introContent)) {
            $introParagraphs = array_filter(array_map('trim', explode("\n", $introContent)));
        }

        $data = [
            'pageTitle' => $pageTitle,
            'pageDescription' => $pageDescription,
            'pageRobot' => $pageRobot,
            'bannerImage' => $bannerImage,
            'bannerTitle' => $bannerTitle,
            'bannerDescription' => $bannerDescription,
            'faqs' => $faqs,
            'benefitsSectionBg' => $benefitsSectionBg,
            'membershipPrice' => $membershipPrice,
            'membershipPriceDescription' => $membershipPriceDescription,
            'introLogo' => $introLogo,
            'introTitle' => $introTitle,
            'introParagraphs' => $introParagraphs,
            'benefitsTitle' => $benefitsTitle,
            'benefitsDescription' => $benefitsDescription,
            'benefitsItems' => $benefitsItems,
            'eligibilityTitle' => $eligibilityTitle,
            'eligibilityItems' => $eligibilityItems,
            'applyFeeText' => $applyFeeText,
            'applyButtonText' => $applyButtonText,
            'applyBenefitsText' => $applyBenefitsText,
            'formFields' => $formFields,
            'settings' => $settings,
            'colorBannerTitle' => $colorBannerTitle,
            'colorBannerDescription' => $colorBannerDescription,
            'colorSectionTitle' => $colorSectionTitle,
            'colorBodyText' => $colorBodyText,
            'colorBenefitTitle' => $colorBenefitTitle,
            'colorPrice' => $colorPrice,
            'colorApplyButtonBg' => $colorApplyButtonBg,
            'colorApplyButtonText' => $colorApplyButtonText,
            'colorFaqQuestion' => $colorFaqQuestion,
        ];

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

    public function store(Request $request)
    {
        // Log all incoming data
        Log::info('=== Montessori Membership Form Submission ===');
        Log::info('All Request Data:', $request->all());
        Log::info('All Request Keys:', array_keys($request->all()));
        
        // Get form fields from settings
        $settings = [];
        $settingsModel = Setting::where('name', 'montessori_membership')->first();
        if (!empty($settingsModel) && !empty($settingsModel->value)) {
            $settings = json_decode($settingsModel->value, true);
        }

        $formFields = !empty($settings['form_fields']) && is_array($settings['form_fields']) ? $settings['form_fields'] : [];
        
        Log::info('Form Fields from Settings:', $formFields);

        // Build validation rules from form fields
        $validationRules = [];
        if (!empty($formFields) && count($formFields) > 0) {
            foreach ($formFields as $field) {
                if (!empty($field['name'])) {
                    // Convert spaces to underscores to match HTML name attributes
                    $fieldName = str_replace(' ', '_', $field['name']);
                    
                    Log::info("Processing field: {$fieldName}", [
                        'original_name' => $field['name'],
                        'converted_name' => $fieldName,
                        'label' => $field['label'] ?? '',
                        'type' => $field['type'] ?? '',
                        'required' => $field['required'] ?? ''
                    ]);
                    
                    $rules = [];
                    if (!empty($field['required']) && $field['required'] == '1') {
                        $rules[] = 'required';
                    }
                    
                    if (!empty($field['type'])) {
                        if ($field['type'] == 'email') {
                            $rules[] = 'email';
                        } elseif ($field['type'] == 'file') {
                            $rules[] = 'image';
                            $rules[] = 'mimes:jpeg,jpg,png,gif,webp';
                            $rules[] = 'max:10240'; // 10MB max
                        }
                    }
                    
                    $validationRules[$fieldName] = !empty($rules) ? implode('|', $rules) : 'nullable';
                }
            }
            
            Log::info('Validation Rules:', $validationRules);
        } else {
            // Default validation rules
            $validationRules = [
                'name' => 'required|string|min:3|max:255',
                'country' => 'required|string|max:255',
                'phone' => 'required|string|max:50',
                'email' => 'required|email|max:255',
                'diploma' => 'required|string|max:255',
            ];
        }

        try {
            $this->validate($request, $validationRules);
            Log::info('Validation passed successfully');
        } catch (\Illuminate\Validation\ValidationException $e) {
            Log::error('Validation failed:', [
                'errors' => $e->errors(),
                'failed_rules' => $e->validator->failed()
            ]);
            throw $e;
        }

        // Prepare form data
        $formData = [];
        
        // Handle file uploads first
        foreach ($formFields as $field) {
            if (!empty($field['name']) && !empty($field['type']) && $field['type'] == 'file') {
                // Convert field name to match HTML attribute
                $htmlFieldName = str_replace(' ', '_', $field['name']);
                
                if ($request->hasFile($htmlFieldName)) {
                    $file = $request->file($htmlFieldName);
                    $fileName = time() . '_' . $htmlFieldName . '_' . $file->getClientOriginalName();
                    $destinationPath = public_path('/store/montessori_membership_files');
                    
                    // Create directory if it doesn't exist
                    if (!file_exists($destinationPath)) {
                        mkdir($destinationPath, 0755, true);
                    }
                    
                    $file->move($destinationPath, $fileName);
                    // Store with original field name (with spaces)
                    $formData[$field['name']] = '/store/montessori_membership_files/' . $fileName;
                }
            }
        }
        
        // Get all other form data (except _token and files)
        // Convert underscores back to spaces for storage
        foreach ($request->except(['_token']) as $key => $value) {
            // Convert underscores back to spaces to match original field names
            $originalKey = str_replace('_', ' ', $key);
            
            // Check if this matches any field from settings
            $matchedField = null;
            foreach ($formFields as $field) {
                if (!empty($field['name']) && str_replace(' ', '_', $field['name']) == $key) {
                    $matchedField = $field['name'];
                    break;
                }
            }
            
            if ($matchedField && !isset($formData[$matchedField])) {
                $formData[$matchedField] = $value;
            } elseif (!isset($formData[$originalKey]) && !isset($formData[$key])) {
                // Store with converted key for sub-fields or unmapped fields
                $formData[$key] = $value;
            }
        }

        // Check if table exists
        if (!Schema::hasTable('montessori_membership_applications')) {
            Log::error('Montessori Membership - Table does not exist');
            return back()->withInput()->with(['msg' => 'خطأ: الجدول غير موجود. يرجى الاتصال بالدعم الفني.']);
        }

        // Save to database
        $applicationId = null;
        try {
            $applicationData = [
                'form_data' => json_encode($formData, JSON_UNESCAPED_UNICODE),
                'status' => 'pending',
                'created_at' => time()
            ];
            
            Log::info('Montessori Membership - Attempting to create application', [
                'form_data_keys' => array_keys($formData),
                'created_at' => $applicationData['created_at']
            ]);
            
            $application = MontessoriMembershipApplication::create($applicationData);
            $applicationId = $application->id;
            
            Log::info('Montessori Membership - Application created', [
                'application_id' => $applicationId,
                'application_exists' => !empty($application),
                'application_attributes' => $application->getAttributes() ?? 'N/A'
            ]);
            
            // Send notification to admin (user_id = 1)
            $name = $formData['name'] ?? 'مستخدم جديد';
            $email = $formData['email'] ?? 'غير محدد';
            
            // Build notification message with form details
            $notificationMessage = "تم استلام طلب تسجيل جديد في عضوية المونتيسوري\n\n";
            $notificationMessage .= "الاسم: {$name}\n";
            $notificationMessage .= "البريد الإلكتروني: {$email}\n";
            
            if (!empty($formFields) && count($formFields) > 0) {
                foreach ($formFields as $field) {
                    if (!empty($field['name']) && isset($formData[$field['name']]) && $field['name'] != 'name' && $field['name'] != 'email') {
                        $label = !empty($field['label']) ? $field['label'] : $field['name'];
                        $value = $formData[$field['name']];
                        $notificationMessage .= "{$label}: {$value}\n";
                    }
                }
            } else {
                // Default fields
                if (!empty($formData['country'])) {
                    $notificationMessage .= "البلد: {$formData['country']}\n";
                }
                if (!empty($formData['phone'])) {
                    $notificationMessage .= "الهاتف: {$formData['phone']}\n";
                }
                if (!empty($formData['diploma'])) {
                    $notificationMessage .= "الدبلوم: {$formData['diploma']}\n";
                }
            }
            
            // Log before creating notification
            $logMessage = "========================================\n";
            $logMessage .= "Montessori Membership - Creating Notification - " . date('Y-m-d H:i:s') . "\n";
            $logMessage .= "========================================\n";
            $logMessage .= "Application ID: {$applicationId}\n";
            $logMessage .= "User ID: 1\n";
            $logMessage .= "Notification Title: تسجيل جديد في عضوية المونتيسوري\n";
            $logMessage .= "Notification Message: " . substr($notificationMessage, 0, 200) . "...\n";
            $logMessage .= "Sender: " . Notification::$SystemSender . "\n";
            $logMessage .= "Type: single\n";
            
            Log::info('Montessori Membership - Attempting to create notification', [
                'application_id' => $applicationId,
                'user_id' => 1,
                'notification_title' => 'تسجيل جديد في عضوية المونتيسوري',
            ]);

            try {
                $notificationData = [
                    'user_id' => 1, // Admin user
                    'group_id' => null,
                    'sender_id' => null,
                    'title' => 'تسجيل جديد في عضوية المونتيسوري',
                    'message' => $notificationMessage,
                    'sender' => Notification::$SystemSender,
                    'type' => 'single', // Changed from 'admin' to 'single'
                    'created_at' => time()
                ];
                
                Log::info('Montessori Membership - Attempting to create notification with data', [
                    'user_id' => $notificationData['user_id'],
                    'type' => $notificationData['type'],
                    'sender' => $notificationData['sender'],
                    'title' => $notificationData['title'],
                    'message_length' => strlen($notificationMessage)
                ]);
                
                $notification = Notification::create($notificationData);
                
                // Get ID using multiple methods
                $notificationId = $notification->getKey() ?? $notification->id ?? $notification->getAttribute('id') ?? 0;
                
                // Refresh the model to ensure we have the latest data
                if ($notificationId > 0) {
                    $notification->refresh();
                }
                
                // Verify notification was actually saved by querying DB
                $savedNotification = null;
                if ($notificationId > 0) {
                    $savedNotification = Notification::where('id', $notificationId)
                        ->where('user_id', 1)
                        ->first();
                }
                
                // If ID is 0, try to find the notification by other attributes
                if (!$savedNotification && $notificationId == 0) {
                    $savedNotification = Notification::where('user_id', 1)
                        ->where('title', 'تسجيل جديد في عضوية المونتيسوري')
                        ->where('type', 'single')
                        ->orderBy('created_at', 'desc')
                        ->first();
                    
                    if ($savedNotification) {
                        $notificationId = $savedNotification->id;
                    }
                }
                
                $logMessage .= "✅ SUCCESS: Notification created successfully!\n";
                $logMessage .= "Notification ID: {$notificationId}\n";
                $logMessage .= "Notification Found in DB: " . ($savedNotification ? 'YES' : 'NO') . "\n";
                
                if ($savedNotification) {
                    $logMessage .= "Notification Title from DB: " . ($savedNotification->title ?? 'N/A') . "\n";
                }
                
                Log::info('Montessori Membership - Notification created successfully', [
                    'notification_id' => $notificationId,
                    'application_id' => $applicationId,
                    'notification_exists_in_db' => !empty($savedNotification),
                    'notification_attributes' => $notification->getAttributes() ?? 'N/A',
                    'saved_notification_id' => $savedNotification ? $savedNotification->id : null
                ]);
                
            } catch (\Exception $notificationException) {
                $logMessage .= "❌ ERROR: Failed to create notification\n";
                $logMessage .= "Error Message: " . $notificationException->getMessage() . "\n";
                $logMessage .= "Error File: " . $notificationException->getFile() . " (Line: " . $notificationException->getLine() . ")\n";
                $logMessage .= "Error Trace: " . $notificationException->getTraceAsString() . "\n";
                
                Log::error('Montessori Membership - Failed to create notification', [
                    'error' => $notificationException->getMessage(),
                    'error_line' => $notificationException->getLine(),
                    'error_file' => $notificationException->getFile(),
                    'error_trace' => $notificationException->getTraceAsString(),
                ]);
            }
            
            $logMessage .= "========================================\n\n";
            
            // Write to custom log file
            try {
                $logFile = storage_path('logs/montessori_membership.log');
                File::append($logFile, $logMessage);
            } catch (\Exception $logException) {
                Log::error('Failed to write to montessori_membership.log', [
                    'error' => $logException->getMessage()
                ]);
            }
            
        } catch (\Exception $e) {
            $logMessage = "========================================\n";
            $logMessage .= "Montessori Membership - CRITICAL ERROR - " . date('Y-m-d H:i:s') . "\n";
            $logMessage .= "========================================\n";
            $logMessage .= "❌ ERROR: Failed to save application or create notification\n";
            $logMessage .= "Error Message: " . $e->getMessage() . "\n";
            $logMessage .= "Error File: " . $e->getFile() . " (Line: " . $e->getLine() . ")\n";
            $logMessage .= "Error Trace: " . $e->getTraceAsString() . "\n";
            $logMessage .= "========================================\n\n";
            
            Log::error('Failed to save Montessori Membership Application to database', [
                'error' => $e->getMessage(),
                'error_line' => $e->getLine(),
                'error_file' => $e->getFile(),
                'form_data' => $formData
            ]);
            
            // Write to custom log file
            try {
                $logFile = storage_path('logs/montessori_membership.log');
                File::append($logFile, $logMessage);
            } catch (\Exception $logException) {
                Log::error('Failed to write to montessori_membership.log', [
                    'error' => $logException->getMessage()
                ]);
            }
        }

        // Log application saved successfully
        Log::info('Montessori Membership Application saved successfully', [
            'application_id' => $applicationId ?? null,
            'form_data_count' => count($formData),
        ]);

        return back()->with(['msg' => 'تم إرسال طلب التسجيل بنجاح. سنتواصل معك قريباً.']);
    }
}
