<?php

namespace App\Http\Controllers;

use App\Models\Business;
use App\Models\NotificationTemplate;
use App\Services\AuditService;
use App\Services\ModuleManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class NotificationSettingsController extends Controller
{
    public function edit(ModuleManager $modules): View
    {
        $business=Business::firstOrCreate(['id'=>1],['name'=>'Microfinance']);
        $templates=NotificationTemplate::query()->where('business_id',$business->id)->orderByRaw("CASE event_type WHEN 'pre_due' THEN 1 WHEN 'due' THEN 2 ELSE 3 END")->orderByRaw("CASE channel WHEN 'in_system' THEN 1 WHEN 'sms' THEN 2 WHEN 'whatsapp' THEN 3 ELSE 4 END")->get();
        $nextSmsConfigured=filled($business->nextsms_api_key) && filled($business->nextsms_sender_id);
        $whatsAppConfigured=filled($business->whatsapp_api_endpoint) || filled(config('reminders.providers.whatsapp.endpoint'));
        $channelEnabled=[
            'in_system'=>true,
            'sms'=>$modules->enabled('sms_messaging',$business->id),
            'whatsapp'=>$modules->enabled('whatsapp_messaging',$business->id),
            'email'=>true,
        ];
        $providerStatus=[
            'in_system'=>true,
            'sms'=>$channelEnabled['sms'] && ($nextSmsConfigured || filled(config('reminders.providers.sms.endpoint'))),
            'whatsapp'=>$channelEnabled['whatsapp'] && $whatsAppConfigured,
            'email'=>!in_array((string)config('mail.default'),['','log','array'],true),
        ];
        return view('notifications.settings',compact('business','templates','providerStatus','nextSmsConfigured','whatsAppConfigured','channelEnabled'));
    }

    public function update(Request $request, ModuleManager $modules): RedirectResponse
    {
        $business=Business::firstOrCreate(['id'=>1],['name'=>'Microfinance']);
        $availableChannels=['in_system','email'];
        if($modules->enabled('sms_messaging',$business->id)) $availableChannels[]='sms';
        if($modules->enabled('whatsapp_messaging',$business->id)) $availableChannels[]='whatsapp';

        $before=$business->only(['reminders_enabled','reminder_pre_due_days','reminder_due_date_enabled','reminder_overdue_enabled','reminder_overdue_frequency','reminder_channels']);
        $beforeNextSms=[
            'configured'=>filled($business->nextsms_api_key) && filled($business->nextsms_sender_id),
            'sender_id'=>$business->nextsms_sender_id,
        ];
        $beforeWhatsApp=[
            'configured'=>filled($business->whatsapp_api_endpoint) || filled(config('reminders.providers.whatsapp.endpoint')),
            'endpoint'=>$business->whatsapp_api_endpoint,
        ];
        $data=$request->validate([
            'reminders_enabled'=>['nullable','boolean'],
            'reminder_pre_due_days'=>['nullable','string','max:100',function(string $attribute,mixed $value,\Closure $fail): void {
                if(blank($value)) return;
                foreach(explode(',',(string)$value) as $part){
                    $part=trim($part);
                    if(!ctype_digit($part) || (int)$part<1 || (int)$part>30){ $fail('Pre-due reminder days must be comma-separated numbers from 1 to 30.'); return; }
                }
            }],
            'reminder_due_date_enabled'=>['nullable','boolean'],
            'reminder_overdue_enabled'=>['nullable','boolean'],
            'reminder_overdue_frequency'=>['required',Rule::in(['daily','every_2_days','every_3_days','weekly'])],
            'reminder_channels'=>[Rule::requiredIf($request->boolean('reminders_enabled')),'array'],
            'reminder_channels.*'=>[Rule::in($availableChannels)],
            'nextsms_api_key'=>['nullable','string','max:2000'],
            'nextsms_sender_id'=>['nullable','string','max:100'],
            'clear_nextsms_api_key'=>['nullable','boolean'],
            'whatsapp_api_endpoint'=>['nullable','string','max:2000'],
            'whatsapp_api_token'=>['nullable','string','max:4000'],
            'clear_whatsapp_api_token'=>['nullable','boolean'],
        ]);

        $days=blank($data['reminder_pre_due_days'] ?? null) ? [] : collect(explode(',',(string)$data['reminder_pre_due_days']))->map(fn($day)=>(int)trim($day))->unique()->sortDesc()->values()->all();
        $business->update([
            'reminders_enabled'=>$request->boolean('reminders_enabled'),
            'reminder_pre_due_days'=>$days,
            'reminder_due_date_enabled'=>$request->boolean('reminder_due_date_enabled'),
            'reminder_overdue_enabled'=>$request->boolean('reminder_overdue_enabled'),
            'reminder_overdue_frequency'=>$data['reminder_overdue_frequency'],
            'reminder_channels'=>array_values(array_unique($data['reminder_channels'] ?? [])),
            'nextsms_sender_id'=>filled($data['nextsms_sender_id'] ?? null) ? trim((string)$data['nextsms_sender_id']) : null,
            'whatsapp_api_endpoint'=>filled($data['whatsapp_api_endpoint'] ?? null) ? trim((string)$data['whatsapp_api_endpoint']) : null,
        ]);

        if($request->boolean('clear_nextsms_api_key')) {
            $business->update(['nextsms_api_key'=>null]);
        } elseif(filled($data['nextsms_api_key'] ?? null)) {
            $business->update(['nextsms_api_key'=>trim((string)$data['nextsms_api_key'])]);
        }

        if($request->boolean('clear_whatsapp_api_token')) {
            $business->update(['whatsapp_api_token'=>null]);
        } elseif(filled($data['whatsapp_api_token'] ?? null)) {
            $business->update(['whatsapp_api_token'=>trim((string)$data['whatsapp_api_token'])]);
        }

        $business->refresh();
        AuditService::record('notifications.settings.updated',$business,[
            'reminders'=>$before,
            'nextsms'=>$beforeNextSms,
            'whatsapp'=>$beforeWhatsApp,
        ],[
            'reminders'=>$business->only(array_keys($before)),
            'nextsms'=>[
                'configured'=>filled($business->nextsms_api_key) && filled($business->nextsms_sender_id),
                'sender_id'=>$business->nextsms_sender_id,
            ],
            'whatsapp'=>[
                'configured'=>filled($business->whatsapp_api_endpoint) || filled(config('reminders.providers.whatsapp.endpoint')),
                'endpoint'=>$business->whatsapp_api_endpoint,
            ],
        ]);
        return back()->with('success','Reminder and messaging provider settings updated.');
    }

    public function updateTemplate(Request $request, NotificationTemplate $template, ModuleManager $modules): RedirectResponse
    {
        $business=Business::firstOrCreate(['id'=>1],['name'=>'Microfinance']);
        abort_unless($template->business_id===$business->id,404);
        if($template->channel==='sms' && !$modules->enabled('sms_messaging',$business->id)) {
            return back()->withErrors(['template'=>'SMS Messaging is disabled in System Settings.']);
        }
        if($template->channel==='whatsapp' && !$modules->enabled('whatsapp_messaging',$business->id)) {
            return back()->withErrors(['template'=>'WhatsApp Messaging is disabled in System Settings.']);
        }
        $before=$template->toArray();
        $data=$request->validate(['subject'=>['nullable','string','max:255'],'body'=>['required','string','max:5000'],'active'=>['nullable','boolean']]);
        $template->update(['subject'=>$data['subject'] ?? null,'body'=>$data['body'],'active'=>$request->boolean('active')]);
        AuditService::record('notifications.template.updated',$template,$before,$template->fresh()->toArray());
        return back()->with('success','Notification template updated.');
    }
}
