<?php

namespace App\Http\Controllers;

use App\Models\SupplierTransaction;
use App\Models\GeneralLedger;
use App\Models\Tax;
use Illuminate\Http\Request;

class SupplierTransactionController extends Controller
{
    public function index()
    {
        return redirect()->route('supplierTransactions.create', ['type' => 'invoice']);
    }

    public function create($type)
    {
        // Sort ledger accounts by code
        $ledgerAccounts = GeneralLedger::orderBy('code')->get();
        $transactions = SupplierTransaction::with([
            'debitLedgerAccount',
            'creditLedgerAccount',
            'taxAccount'
        ])->where('transaction_type', $type)->get();

        return view(
            'maintanance.chart_of_accounts.create_suppliertrans',
            compact('type', 'ledgerAccounts', 'transactions')
        );
    }

    public function store(Request $request)
    {
        $request->validate([
            'transaction_type'          => 'required|in:invoice,credit_note,debit_note',
            'code'                      => 'required|string|max:10|unique:supplier_transactions,code',
            'description'               => 'required|string|max:255',
            'debit_credit'              => 'required|in:debit,credit',
            'debit_ledger_account_id'   => 'required|exists:main_accounts,id',
            'credit_ledger_account_id'  => 'required|exists:main_accounts,id',
            'tax_account_id'            => 'nullable|exists:main_accounts,id', // Changed to main_accounts
            'always_prompt_credit'      => 'boolean',
            'always_split_credit'       => 'boolean',
            'use_tax'                   => 'boolean',
        ]);

        $taxAccountId = $request->use_tax ? $request->tax_account_id : null;

        SupplierTransaction::create([
            'transaction_type'         => $request->transaction_type,
            'code'                     => $request->code,
            'description'              => $request->description,
            'debit_credit'             => $request->debit_credit,
            'debit_ledger_account_id'  => $request->debit_ledger_account_id,
            'credit_ledger_account_id' => $request->credit_ledger_account_id,
            'tax_account_id'           => $taxAccountId,
            'always_prompt_credit'     => $request->always_prompt_credit ?? false,
            'always_split_credit'      => $request->always_split_credit ?? false,
            'use_tax'                  => $request->use_tax ?? false,
        ]);

        return redirect()
            ->route('supplierTransactions.create', ['type' => $request->transaction_type])
            ->with('success', 'Supplier transaction created successfully!');
    }

    public function edit($id)
    {
        $transaction = SupplierTransaction::findOrFail($id);
        // Sort ledger accounts by code
        $ledgerAccounts = GeneralLedger::orderBy('code')->get();

        return view(
            'maintanance.chart_of_accounts.editsuptrans',
            compact('transaction', 'ledgerAccounts')
        );
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'code'                      => 'required|string|max:10|unique:supplier_transactions,code,'.$id,
            'description'               => 'required|string|max:255',
            'debit_credit'              => 'required|in:debit,credit',
            'debit_ledger_account_id'   => 'required|exists:main_accounts,id',
            'credit_ledger_account_id'  => 'required|exists:main_accounts,id',
            'tax_account_id'            => 'nullable|exists:main_accounts,id', // Changed to main_accounts
            'always_prompt_credit'      => 'boolean',
            'always_split_credit'       => 'boolean',
            'use_tax'                   => 'boolean',
        ]);

        $transaction = SupplierTransaction::findOrFail($id);
        $taxAccountId = $request->use_tax ? $request->tax_account_id : null;

        $transaction->update([
            'code'                     => $request->code,
            'description'              => $request->description,
            'debit_credit'             => $request->debit_credit,
            'debit_ledger_account_id'  => $request->debit_ledger_account_id,
            'credit_ledger_account_id' => $request->credit_ledger_account_id,
            'tax_account_id'           => $taxAccountId,
            'always_prompt_credit'     => $request->always_prompt_credit ?? false,
            'always_split_credit'      => $request->always_split_credit ?? false,
            'use_tax'                  => $request->use_tax ?? false,
        ]);

        return redirect()
            ->route('supplierTransactions.create', ['type' => $transaction->transaction_type])
            ->with('success', 'Supplier transaction updated successfully!');
    }

    public function destroy($id)
    {
        $transaction = SupplierTransaction::findOrFail($id);
        $type        = $transaction->transaction_type;
        $transaction->delete();

        return redirect()
            ->route('supplierTransactions.create', ['type' => $type])
            ->with('success', 'Supplier transaction deleted successfully!');
    }
}