<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\ReminderNotificationLog;
use App\Services\AuditService;
use App\Services\LoanReminderService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;

class ReminderNotificationController extends Controller
{
    public function index(Request $request): View
    {
        $branchIds=$this->allowedBranchIds($request);
        $query=ReminderNotificationLog::query()->with(['customer','loan','installment','branch','template'])->whereIn('branch_id',$branchIds);
        $search=trim((string)$request->string('search'));
        $status=(string)$request->string('status'); $channel=(string)$request->string('channel'); $type=(string)$request->string('type');
        if($search!=='') $query->where(function($q) use($search): void {
            $q->where('recipient','like',"%{$search}%")->orWhere('message','like',"%{$search}%")
                ->orWhereHas('loan',fn($loan)=>$loan->where('loan_number','like',"%{$search}%"))
                ->orWhereHas('customer',fn($customer)=>$customer->where('customer_number','like',"%{$search}%")->orWhere('phone','like',"%{$search}%")->orWhere('first_name','like',"%{$search}%")->orWhere('last_name','like',"%{$search}%"));
        });
        if(in_array($status,['pending','delivered','failed'],true)) $query->where('status',$status);
        if(in_array($channel,['sms','whatsapp','email','in_system'],true)) $query->where('channel',$channel);
        if(in_array($type,['pre_due','due','overdue'],true)) $query->where('reminder_type',$type);
        if($request->filled('date_from')) $query->whereDate('scheduled_for','>=',$request->date('date_from'));
        if($request->filled('date_to')) $query->whereDate('scheduled_for','<=',$request->date('date_to'));
        $logs=$query->latest('scheduled_for')->latest('id')->paginate(30)->withQueryString();
        $summary=ReminderNotificationLog::query()->whereIn('branch_id',$branchIds)->selectRaw("status, COUNT(*) as aggregate")->groupBy('status')->pluck('aggregate','status');
        return view('notifications.index',compact('logs','summary','search','status','channel','type'));
    }

    public function retry(Request $request, ReminderNotificationLog $notification, LoanReminderService $service): RedirectResponse
    {
        Gate::forUser($request->user())->authorize('retry', $notification);
        $before=$notification->toArray();
        $updated=$service->retry($notification);
        AuditService::record('notifications.delivery.retried',$updated,$before,$updated->toArray(),$updated->branch_id);
        return back()->with($updated->status==='delivered' ? 'success' : 'error',$updated->status==='delivered' ? 'Notification delivered on retry.' : 'Notification retry failed. Review the recorded provider error.');
    }

    private function allowedBranchIds(Request $request)
    {
        return collect(app(\App\Services\BranchAccessService::class)->accessibleBranchIds($request->user()));
    }
}
