<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Support\FormTextRules;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AccountController extends Controller
{
    public function __construct()
    {
        $this->middleware('finance.treasury');
    }

    public function index()
    {
        $accounts = Account::orderBy('name')->paginate(15);

        return view('finance.accounts', compact('accounts'));
    }

    public function create()
    {
        return view('finance.accounts-create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => FormTextRules::notNumericOnly(true, 191),
            'code' => 'nullable|string|max:50',
            'type' => 'required|in:bank,cash,other',
            'opening_balance' => 'required|numeric',
        ], FormTextRules::messages());
        $validated['current_balance'] = $validated['opening_balance'];
        $validated['company_id'] = Auth::user()?->company_id;
        Account::create($validated);

        return redirect()->route('accounts.index')->with('success', 'Account created successfully.');
    }

    public function edit(Account $account)
    {
        $this->authorizeAccount($account);

        return view('finance.accounts-edit', compact('account'));
    }

    public function update(Request $request, Account $account)
    {
        $this->authorizeAccount($account);
        $validated = $request->validate([
            'name' => FormTextRules::notNumericOnly(true, 191),
            'code' => 'nullable|string|max:50',
            'type' => 'required|in:bank,cash,other',
            'current_balance' => 'required|numeric',
        ], FormTextRules::messages());
        $account->update($validated);

        return redirect()->route('accounts.index')->with('success', 'Account updated successfully.');
    }

    public function destroy(Account $account)
    {
        $this->authorizeAccount($account);
        $account->delete();

        return redirect()->route('accounts.index')->with('success', 'Account deleted successfully.');
    }

    protected function authorizeAccount(Account $account): void
    {
        $companyId = Auth::user()?->company_id;
        if ($companyId && $account->company_id !== $companyId) {
            abort(403);
        }
    }
}
