<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use App\Models\Loan;
use App\Models\Client;
use App\Models\ClientGroup;
use App\Notifications\LoanReminderNotification;
use App\Notifications\LoanOverdueNotification;
use App\Notifications\LoanPenaltyNotification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index()
    {
        $notifications = Notification::latest()->paginate(20);
        return view('notifications.index', compact('notifications'));
    }

    public function sendManualNotification(Request $request)
    {
        $request->validate([
            'type' => 'required|in:reminder,overdue,penalty',
            'loan_id' => 'required|exists:loans,id',
            'channel' => 'required|in:email,sms,both'
        ]);

        $loan = Loan::findOrFail($request->loan_id);
        $client = $loan->client;
        $clientGroup = $loan->clientGroup;

        $notification = null;
        switch ($request->type) {
            case 'reminder':
                $notification = new LoanReminderNotification($loan);
                break;
            case 'overdue':
                $penalty = $loan->outstanding_balance * 0.05;
                $notification = new LoanOverdueNotification($loan, null, $penalty);
                break;
            case 'penalty':
                $penalty = $loan->outstanding_balance * 0.05;
                $notification = new LoanPenaltyNotification($loan, $penalty, 'Manual penalty notice');
                break;
        }

        if ($notification) {
            // Persist a record in notifications table for tracking
            $message = null;
            if ($request->channel === 'sms' || $request->channel === 'both') {
                $message = $notification->toSms($client ?? $clientGroup);
            } else {
                // fallback: try mail view or string
                try {
                    $message = method_exists($notification, 'toMail') ? 'Email: ' . class_basename($notification) : '';
                } catch (\Exception $e) {
                    $message = '';
                }
            }

            \App\Models\Notification::create([
                'loan_id' => $loan->id,
                'client_id' => $client->id ?? null,
                'type' => $request->type,
                'channel' => $request->channel,
                'message' => $message,
                'sent' => false,
            ]);

            // Send to client
            if ($client) {
                $client->notify($notification);
            }

            // Send to client group
            if ($clientGroup) {
                $clientGroup->notify($notification);
            }
        }

        return redirect()->back()->with('success', 'Notification sent successfully!');
    }
}
