<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ReminderSetting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ReminderSettingsController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:manage_reminders');
    }

    public function edit(): View
    {
        $settings = ReminderSetting::current();

        return view('admin.reminders.settings', compact('settings'));
    }

    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'enable_invoice_created' => 'boolean',
            'enable_invoice_due_reminder' => 'boolean',
            'enable_invoice_overdue_reminder' => 'boolean',
            'enable_invoice_paid' => 'boolean',
            'enable_partial_payment' => 'boolean',
            'enable_quotation_created' => 'boolean',
            'enable_quotation_expiry' => 'boolean',
            'enable_quotation_accepted' => 'boolean',
            'enable_quotation_rejected' => 'boolean',
            'enable_purchase_order_created' => 'boolean',
            'enable_recurring_invoice_generated' => 'boolean',
            'enable_payment_receipt' => 'boolean',
            'enable_manual_reminders' => 'boolean',
            'enable_customer_welcome' => 'boolean',
            'enable_follow_up_reminder' => 'boolean',
            'due_reminder_days_before' => 'required|integer|min:0|max:90',
            'overdue_reminder_days_after' => 'required|integer|min:0|max:90',
            'quotation_expiry_days_before' => 'required|integer|min:0|max:90',
            'send_copy_to_admin' => 'boolean',
            'email_sending_mode' => 'required|in:instant,queue',
            'attach_pdf_to_emails' => 'boolean',
        ]);

        foreach ([
            'enable_invoice_created',
            'enable_invoice_due_reminder',
            'enable_invoice_overdue_reminder',
            'enable_invoice_paid',
            'enable_partial_payment',
            'enable_quotation_created',
            'enable_quotation_expiry',
            'enable_quotation_accepted',
            'enable_quotation_rejected',
            'enable_purchase_order_created',
            'enable_recurring_invoice_generated',
            'enable_payment_receipt',
            'enable_manual_reminders',
            'enable_customer_welcome',
            'enable_follow_up_reminder',
            'send_copy_to_admin',
            'attach_pdf_to_emails',
        ] as $boolKey) {
            $validated[$boolKey] = $request->boolean($boolKey);
        }

        ReminderSetting::current()->update($validated);

        return redirect()->route('admin.reminders.settings')->with('success', 'Reminder settings saved.');
    }
}
