<?php

namespace App\Http\Controllers;

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

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

    private function authorizeTaxAccess(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('manage settings') ||
            $user->can('process payments') ||
            $user->can('create orders')
        )) {
            return;
        }

        abort(403, 'Anda tidak memiliki akses pengaturan PPN.');
    }

    public function index(Request $request)
    {
        $this->authorizeTaxAccess($request);

        return view('pages.tax-settings.index', [
            'title' => 'Pengaturan PPN',
            'taxSetting' => TaxSetting::current(),
        ]);
    }

    public function update(Request $request)
    {
        $this->authorizeTaxAccess($request);

        $validated = $request->validate([
            'rate' => ['required', 'numeric', 'min:0', 'max:100'],
            'is_active' => ['nullable'],
            'npwp' => ['nullable', 'string', 'max:100'],
            'pkp_name' => ['nullable', 'string', 'max:255'],
            'pkp_address' => ['nullable', 'string', 'max:2000'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ]);

        $taxSetting = TaxSetting::current();

        $taxSetting->update([
            'name' => 'PPN',
            'rate' => $validated['rate'],
            'is_active' => $request->boolean('is_active'),
            'npwp' => $validated['npwp'] ?? null,
            'pkp_name' => $validated['pkp_name'] ?? null,
            'pkp_address' => $validated['pkp_address'] ?? null,
            'notes' => $validated['notes'] ?? null,
        ]);

        return back()->with('success', 'Pengaturan PPN berhasil disimpan.');
    }
}
