<?php

namespace App\Http\Controllers;

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

class CustomerTransactionController extends Controller
{
    /**
     * Display the transaction type form.
     */
    public function index()
    {
        // Redirect to invoice by default
        return redirect()->route('customerTransactions.create', ['type' => 'invoice']);
    }

    /**
     * Show the form to create a new transaction type.
     */
    public function create($type)
    {
        // Get ledger accounts ordered by code
        $ledgerAccounts = GeneralLedger::orderBy('code')->get();
        $transactions   = CustomerTransaction::with([
                              'debitLedgerAccount',
                              'creditLedgerAccount',
                              'taxAccount'
                          ])
                          ->where('transaction_type', $type)
                          ->get();

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

    /**
     * Store a newly created customer transaction.
     */
    public function store(Request $request)
    {
        $request->validate([
            'transaction_type'          => 'required|in:invoice,credit_note,debit_note',
            'code'                      => 'required|string|max:10|unique:customer_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',
            'always_prompt_credit'      => 'sometimes|boolean',
            'always_split_credit'       => 'sometimes|boolean',
            'use_tax'                   => 'sometimes|boolean',
        ]);

        $taxAccountId = $request->boolean('use_tax') && $request->filled('tax_account_id')
            ? $request->tax_account_id
            : null;

        CustomerTransaction::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->boolean('always_prompt_credit'),
            'always_split_credit'      => $request->boolean('always_split_credit'),
            'use_tax'                  => $request->boolean('use_tax'),
        ]);

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

    /**
     * Show the form for editing an existing transaction.
     */
    public function edit($id)
    {
        $transaction    = CustomerTransaction::findOrFail($id);
        $ledgerAccounts = GeneralLedger::orderBy('code')->get();

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

    /**
     * Update an existing customer transaction.
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'code'                      => 'required|string|max:10|unique:customer_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',
            'always_prompt_credit'      => 'sometimes|boolean',
            'always_split_credit'       => 'sometimes|boolean',
            'use_tax'                   => 'sometimes|boolean',
        ]);

        $transaction = CustomerTransaction::findOrFail($id);

        $taxAccountId = $request->boolean('use_tax') && $request->filled('tax_account_id')
            ? $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->boolean('always_prompt_credit'),
            'always_split_credit'      => $request->boolean('always_split_credit'),
            'use_tax'                  => $request->boolean('use_tax'),
        ]);

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

    /**
     * Delete a customer transaction.
     */
    public function destroy($id)
    {
        $transaction = CustomerTransaction::findOrFail($id);
        $type        = $transaction->transaction_type;
        $transaction->delete();

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