<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NotificationSetting;
use App\Models\User;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class NotificationSettingsController extends Controller
{
    private $notificationService;

    public function __construct(NotificationService $notificationService)
    {
        $this->notificationService = $notificationService;
    }

    /**
     * Display notification settings page
     */
    public function index()
    {
        $settings = NotificationSetting::getSettings();
        return view('admin.settings.notifications', compact('settings'));
    }

    /**
     * Update notification settings
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            // Toggle switches
            'email_enabled' => 'boolean',
            'push_enabled' => 'boolean',
            'sms_enabled' => 'boolean',
            
            // Email settings
            'mail_mailer' => 'required|string',
            'mail_host' => 'nullable|string',
            'mail_port' => 'nullable|integer',
            'mail_username' => 'nullable|string',
            'mail_password' => 'nullable|string',
            'mail_encryption' => 'nullable|string',
            'mail_from_address' => 'nullable|email',
            'mail_from_name' => 'nullable|string',
            
            // Push settings
            'push_provider' => 'nullable|in:firebase,onesignal',
            'push_api_key' => 'nullable|string',
            'push_server_key' => 'nullable|string',
            
            // SMS settings
            'sms_provider' => 'nullable|in:twilio,nexmo,africas_talking',
            'sms_api_key' => 'nullable|string',
            'sms_api_secret' => 'nullable|string',
            'sms_from_number' => 'nullable|string',
        ]);

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

        $settings = NotificationSetting::getSettings();
        
        // Update toggle switches
        $settings->email_enabled = $request->input('email_enabled', true);
        $settings->push_enabled = $request->input('push_enabled', false);
        $settings->sms_enabled = $request->input('sms_enabled', false);
        
        // Update email settings
        $settings->mail_mailer = $request->input('mail_mailer');
        $settings->mail_host = $request->input('mail_host');
        $settings->mail_port = $request->input('mail_port');
        $settings->mail_username = $request->input('mail_username');
        
        // Only update password if provided
        if ($request->filled('mail_password')) {
            $settings->mail_password = $request->input('mail_password');
        }
        
        $settings->mail_encryption = $request->input('mail_encryption');
        $settings->mail_from_address = $request->input('mail_from_address');
        $settings->mail_from_name = $request->input('mail_from_name');
        
        // Update push settings
        $settings->push_provider = $request->input('push_provider');
        $settings->push_api_key = $request->input('push_api_key');
        $settings->push_server_key = $request->input('push_server_key');
        
        // Update SMS settings
        $settings->sms_provider = $request->input('sms_provider');
        $settings->sms_api_key = $request->input('sms_api_key');
        $settings->sms_api_secret = $request->input('sms_api_secret');
        $settings->sms_from_number = $request->input('sms_from_number');
        
        $settings->save();

        return redirect()->route('admin.settings.notifications')
            ->with('success', 'Notification settings updated successfully.');
    }

    /**
     * Test email notification
     */
    public function testEmail(Request $request)
    {
        try {
            $admin = auth()->user();
            
            $result = $this->notificationService->sendEmail(
                $admin,
                'Test Email',
                'This is a test email from EE Micro LMS notification system.',
                [
                    'action_url' => route('admin.dashboard'),
                    'action_text' => 'Go to Dashboard'
                ]
            );

            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Test email sent successfully! Check your inbox.'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to send email: ' . $result['error']
                ], 500);
            }
        } catch (\Exception $e) {
            Log::error('Test email failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error sending test email: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Test push notification
     */
    public function testPush(Request $request)
    {
        try {
            $admin = auth()->user();
            
            if (!$admin->device_token) {
                return response()->json([
                    'success' => false,
                    'message' => 'No device token found. Please log in from mobile app first.'
                ], 400);
            }

            $result = $this->notificationService->sendPushNotification(
                $admin,
                'Test Push Notification',
                'This is a test push notification from EE Micro LMS.',
                ['type' => 'test']
            );

            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Test push notification sent successfully!'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to send push notification: ' . $result['error']
                ], 500);
            }
        } catch (\Exception $e) {
            Log::error('Test push failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error sending test push: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Test SMS notification
     */
    public function testSms(Request $request)
    {
        try {
            $admin = auth()->user();
            
            if (!$admin->phone) {
                return response()->json([
                    'success' => false,
                    'message' => 'No phone number found. Please update your profile.'
                ], 400);
            }

            $result = $this->notificationService->sendSms(
                $admin,
                'Test SMS',
                'This is a test SMS from EE Micro LMS notification system.'
            );

            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'message' => 'Test SMS sent successfully! Check your phone.'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to send SMS: ' . $result['error']
                ], 500);
            }
        } catch (\Exception $e) {
            Log::error('Test SMS failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error sending test SMS: ' . $e->getMessage()
            ], 500);
        }
    }
}
