<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Setting;
use App\Models\TaxSetting;
use Illuminate\Http\Request;

class InvoicePrintController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    private function authorizeInvoicePrint(Request $request): void
    {
        $user = $request->user();

        if (!$user) {
            abort(403);
        }

        if (method_exists($user, 'isDeveloper') && $user->isDeveloper()) {
            return;
        }

        if (method_exists($user, 'can') && (
            $user->can('view orders') ||
            $user->can('create orders') ||
            $user->can('process payments') ||
            $user->can('print spk') ||
            $user->can('manage settings')
        )) {
            return;
        }

        abort(403, 'Anda tidak memiliki akses cetak invoice.');
    }

    private function getSettingValue(string $method, mixed $default = null): mixed
    {
        try {
            if (class_exists(Setting::class) && method_exists(Setting::class, $method)) {
                return Setting::{$method}();
            }
        } catch (\Throwable $e) {
            return $default;
        }

        return $default;
    }

    public function print(Request $request, Order $order)
    {
        $this->authorizeInvoicePrint($request);

        $order->loadMissing(['items', 'customer']);

        try {
            $order->loadMissing(['payments']);
        } catch (\Throwable $e) {
            // Kalau relasi payments tidak ada, invoice tetap bisa dicetak.
        }

        $paperSize = $request->query('paper', 'a4');

        if (!in_array($paperSize, ['a4', 'a5', '215x165'], true)) {
            $paperSize = 'a4';
        }

        try {
            $taxSetting = TaxSetting::current();
        } catch (\Throwable $e) {
            $taxSetting = new TaxSetting([
                'name' => 'PPN',
                'rate' => 11,
                'is_active' => false,
            ]);
        }

        // PPN tidak lagi dipaksa dari URL cetak.
        // Invoice hanya membaca data PPN yang sudah tersimpan saat proses pembayaran.
        $usePpn = (bool) ($order->use_ppn ?? false);
        $ppnRate = (float) ($order->ppn_rate ?: ($taxSetting->rate ?? 0));

        return view('print.invoice-multi', [
            'order' => $order,
            'paperSize' => $paperSize,
            'taxSetting' => $taxSetting,
            'usePpn' => $usePpn,
            'ppnRate' => $ppnRate,

            'shopName' => $this->getSettingValue('getShopName', config('app.name')),
            'shopAddress' => $this->getSettingValue('getShopAddress', ''),
            'shopPhone' => $this->getSettingValue('getShopPhone', ''),
            'shopLogo' => $this->getSettingValue('getShopLogo', ''),
            'shopFooter' => $this->getSettingValue('getShopFooter', ''),

            'printedAt' => now(),
        ]);
    }
}
