<?php

namespace App\Http\Controllers;

use App\Models\TransactionType;
use App\Models\GeneralLedger;
use Illuminate\Http\Request;

class TransactionTypeController extends Controller
{
    public function index()
    {
        $accounts = GeneralLedger::all();
        $records = TransactionType::with('generalLedger')->get();
        return view('maintanance.chart_of_accounts.create_transactionType', compact('accounts', 'records'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'gl_account' => 'required|exists:general_ledgers,id',
            'account_group' => 'required|in:tenants,customers,suppliers'
        ]);

        TransactionType::create([
            'gl_account' => $request->gl_account,
            'account_group' => $request->account_group
        ]);

        return redirect()->route('transactionTypes.index')->with('success', 'Transaction type created successfully!');
    }

    public function edit($id)
    {
        $type = TransactionType::findOrFail($id);
        $accounts = GeneralLedger::all();
        return view('maintanance.transaction_types.edit', compact('type', 'accounts'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'gl_account' => 'required|exists:general_ledgers,id',
            'account_group' => 'required|in:tenants,customers,suppliers'
        ]);

        $type = TransactionType::findOrFail($id);
        $type->update($request->only(['gl_account', 'account_group']));

        return redirect()->route('transactionTypes.index')->with('success', 'Transaction type updated successfully!');
    }

    public function destroy($id)
    {
        $type = TransactionType::findOrFail($id);
        $type->delete();
        return redirect()->route('transactionTypes.index')->with('success', 'Transaction type deleted successfully!');
    }
}