<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Quotation;
use App\Services\ReminderService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ManualReminderController extends Controller
{
    public function __construct(
        private ReminderService $reminderService
    ) {
        $this->middleware('permission:send_manual_reminders');
    }

    public function sendInvoice(Request $request, Invoice $invoice): JsonResponse
    {
        $this->authorize('view', $invoice);

        $validated = $request->validate([
            'recipient_email' => 'required|email',
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'as_follow_up' => 'boolean',
        ]);

        $invoice->loadMissing('customer');

        $ok = $this->reminderService->sendManual(
            $validated['recipient_email'],
            $validated['subject'],
            $validated['body'],
            $invoice->customer_id,
            $invoice->id,
            null,
            $request->boolean('as_follow_up')
        );

        if (! $ok) {
            return response()->json(['success' => false, 'message' => 'Could not send reminder (disabled, invalid email, or queue error).'], 422);
        }

        return response()->json(['success' => true, 'message' => 'Reminder queued or sent.']);
    }

    public function sendQuotation(Request $request, Quotation $quotation): JsonResponse
    {
        $this->authorize('view', $quotation);

        $validated = $request->validate([
            'recipient_email' => 'required|email',
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'as_follow_up' => 'boolean',
        ]);

        $quotation->loadMissing('customer');

        $ok = $this->reminderService->sendManual(
            $validated['recipient_email'],
            $validated['subject'],
            $validated['body'],
            $quotation->customer_id,
            null,
            $quotation->id,
            $request->boolean('as_follow_up')
        );

        if (! $ok) {
            return response()->json(['success' => false, 'message' => 'Could not send reminder (disabled, invalid email, or queue error).'], 422);
        }

        return response()->json(['success' => true, 'message' => 'Reminder queued or sent.']);
    }
}
