<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\BankAccount;
use App\Models\BillingProfile;
use App\Models\InvoiceSetting;
use App\Models\ReceiptSetting;
use Illuminate\Http\Request;

class BillingSettingsController extends Controller
{
    public function billing()
    {
        $tenantId = auth()->user()->tenant_id;
        $profile = BillingProfile::firstOrCreate(['tenant_id' => $tenantId]);
        $bankAccounts = BankAccount::where('tenant_id', $tenantId)->get();

        return view('tenant.settings.billing.index', compact('profile', 'bankAccounts'));
    }

    public function updateBillingProfile(Request $request)
    {
        $tenantId = auth()->user()->tenant_id;
        $profile = BillingProfile::firstOrCreate(['tenant_id' => $tenantId]);

        $profile->update($request->only([
            'legal_business_name', 'billing_address', 'trn', 'billing_email', 'billing_mobile',
            'customer_prefix', 'application_prefix', 'invoice_prefix', 'receipt_prefix', 'quotation_prefix', 'renewal_prefix', 'employee_prefix',
            'default_currency', 'default_vat_percentage', 'vat_enabled', 'price_includes_vat',
        ]));

        return back()->with('status', 'Billing profile and reference numbering sequences updated.');
    }

    public function invoiceDesign()
    {
        $tenantId = auth()->user()->tenant_id;
        $invoiceSetting = InvoiceSetting::firstOrCreate(['tenant_id' => $tenantId]);
        $receiptSetting = ReceiptSetting::firstOrCreate(['tenant_id' => $tenantId]);

        return view('tenant.settings.billing.design', compact('invoiceSetting', 'receiptSetting'));
    }

    public function updateInvoiceDesign(Request $request)
    {
        $tenantId = auth()->user()->tenant_id;
        $invoiceSetting = InvoiceSetting::firstOrCreate(['tenant_id' => $tenantId]);
        $receiptSetting = ReceiptSetting::firstOrCreate(['tenant_id' => $tenantId]);

        $invoiceSetting->update($request->only(['arabic_company_name', 'terms_and_conditions', 'footer_note', 'bank_details_text']));
        $receiptSetting->update($request->only(['receipt_size', 'header_text', 'footer_text', 'print_automatically']));

        return back()->with('status', 'Invoice & Receipt print templates saved.');
    }
}
