<?php

namespace App\Http\Controllers;

use App\Models\MainAccount;
use App\Models\SubAccount;
use App\Services\AccountService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class SubAccountController extends Controller
{
    public function __construct(protected AccountService $service)
    {
        $this->middleware('permission:accounts.view')->only(['index', 'show']);
        $this->middleware('permission:accounts.create')->only(['create', 'store']);
        $this->middleware('permission:accounts.edit')->only(['edit', 'update']);
        $this->middleware('permission:accounts.delete')->only(['destroy']);
    }

    public function index(Request $request)
    {
        $accounts = SubAccount::query()->with('mainAccount')->search($request->get('q'))->latest()->paginate(per_page())->withQueryString();

        return view('accounts.sub.index', compact('accounts'));
    }

    public function create()
    {
        return view('accounts.sub.create', ['mains' => MainAccount::query()->orderBy('name')->get()]);
    }

    public function store(Request $request)
    {
        $account = $this->service->createSub($this->validated($request));

        return redirect()->route('sub-accounts.show', $account)->with('success', __('messages.created'));
    }

    public function show(SubAccount $subAccount)
    {
        $subAccount->load(['mainAccount', 'customers', 'lines.currentPlan', 'invoices']);

        return view('accounts.sub.show', [
            'account' => $subAccount,
            'outstanding' => $this->service->outstanding($subAccount),
        ]);
    }

    public function edit(SubAccount $subAccount)
    {
        return view('accounts.sub.edit', [
            'account' => $subAccount,
            'mains' => MainAccount::query()->orderBy('name')->get(),
        ]);
    }

    public function update(Request $request, SubAccount $subAccount)
    {
        $this->service->updateSub($subAccount, $this->validated($request, $subAccount));

        return redirect()->route('sub-accounts.show', $subAccount)->with('success', __('messages.updated'));
    }

    public function destroy(SubAccount $subAccount)
    {
        if ($subAccount->lines()->exists() || $subAccount->invoices()->exists()) {
            $subAccount->update(['status' => 'inactive']);
        } else {
            $subAccount->delete();
        }

        return redirect()->route('sub-accounts.index')->with('success', __('messages.updated'));
    }

    protected function validated(Request $request, ?SubAccount $account = null): array
    {
        return $request->validate([
            'main_account_id' => ['required', 'exists:main_accounts,id'],
            'name' => ['required', 'string', 'max:255'],
            'code' => ['required', 'string', 'max:50', Rule::unique('sub_accounts', 'code')->ignore($account?->id)->where('main_account_id', $request->input('main_account_id'))],
            'phone' => ['nullable', 'string', 'max:30'],
            'email' => ['nullable', 'email'],
            'status' => ['required', Rule::in(['active', 'inactive'])],
            'notes' => ['nullable', 'string'],
        ]);
    }
}
