<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\DB;
use App\Models\Ledger;
use App\Models\LedgerCategory;
use App\Models\BankAccount;
use App\Models\SubBankAccount;
use App\Models\GeneralLedger;
use App\Traits\LogActivityTrait;
use App\Helpers\CalculateBalances;
use Illuminate\Support\Facades\Validator;

class ManageGeneralEntriesController extends Controller
{

    use LogActivityTrait;
    use CalculateBalances;

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index() {

        $all_accounts = array();
        $bank_accounts = DB::table('bank_accounts')->select('id', 'name', 'account_number')->get();
        $sub_bank_accounts = DB::table('sub_bank_accounts')->select('id', 'name', 'account_number')->get();
        $last_bank_accounts = DB::table('last_bank_accounts')->select('id', 'name', 'account_number')->get();
        $more_account_belows = DB::table('more_account_belows')->select('id', 'name', 'account_number')->get();

        // array_push($all_accounts, $bank_accounts);
        // array_push($all_accounts, $sub_bank_accounts);
        // array_push($all_accounts, $last_bank_accounts);
        // array_push($all_accounts, $more_account_belows);


        foreach ($bank_accounts as $value) {
            $data1 = array(
                // 'id' => $value->id,
                'name' => $value->name.' - '.$value->account_number,
                'account_number' => $value->account_number,
            );
            array_push($all_accounts, $data1);
        }
        foreach ($sub_bank_accounts as $value) {
            $data2 = array(
                // 'id' => $value->id,
                'name' => $value->name.' - '.$value->account_number,
                'account_number' => $value->account_number,
            );
            array_push($all_accounts, $data2);
        }
        foreach ($last_bank_accounts as $value) {
            $data3 = array(
                // 'id' => $value->id,
                'name' => $value->name.' - '.$value->account_number,
                'account_number' => $value->account_number,
            );
            array_push($all_accounts, $data3);
        }

        foreach ($more_account_belows as $value) {
            $data4 = array(
                // 'id' => $value->id,
                'name' => $value->name.' - '.$value->account_number,
                'account_number' => $value->account_number,
            );
            array_push($all_accounts, $data4);
        }

        return Inertia::render('ChartOfAccounts/AddGeneralEntryManualComponent', [
            'all_accounts' => $all_accounts,
        ]);
    }


    public function calculateBalanceOnAccount($account_id)
    {
        $bank_account = DB::table('bank_accounts')
            ->select('id', 'account_number')
            ->where('bank_accounts.account_number', $account_id)->first();

        $sub_bank_accounts = DB::table('sub_bank_accounts')
            ->select()
            ->where('sub_bank_accounts.account_number', $account_id)->first();

        $last_bank_accounts = DB::table('last_bank_accounts')
            ->select()
            ->where('last_bank_accounts.account_number', $account_id)->first();

        $bottom_bank_accounts = DB::table('more_account_belows')
            ->select('id', 'account_number')
            ->where('more_account_belows.account_number', $account_id)->first();

        if ($bank_account) {
            $result = $this->calculate_balance_on_addition_of_ledgers($bank_account->account_number);
            echo json_encode($result);
        } else if ($sub_bank_accounts) {
            $result = $this->calculate_balance_on_addition_of_ledgers($sub_bank_accounts->account_number);
            echo json_encode($result);
        } else if ($last_bank_accounts) {
            $result = $this->calculate_balance_on_addition_of_ledgers($last_bank_accounts->account_number);
            echo json_encode($result);
        } else if ($bottom_bank_accounts) {
            $result = $this->calculate_balance_on_addition_of_ledgers($bottom_bank_accounts->account_number);
            echo json_encode($result);
        }
    }


    public function createJournalEntry(Request $request)
    {

        $messages = [
            'comment.required' => 'The Comment field is required',
            'credit_account.required' => 'The Credit Account field is required',
            'credit_amount.required' => 'The Credit Amount field is required',
            'debit_account.required' => 'The Debit Account field is required',
            'debit_amount.required' => 'The Debit Amount field is required',
        ];

        $validator = Validator::make($request->all(), [
            'comment' => 'required',
            'credit_account' => 'required',
            'credit_amount' => 'required',
            'debit_account' => 'required',
            'debit_amount' => 'required'
        ], $messages);

        //VALIDATE THE REQUEST INPUTS
        if($validator->fails()){
            return response()->json($validator->errors(), 400);
        }

        $get_last_reference_number = DB::table('general_ledgers')->select('general_ledgers.*')
            ->latest('general_ledgers.reference')->first();

        if ($get_last_reference_number) {
            $defaut_journal_reference_code = $get_last_reference_number->reference;
            $finalcode = str_pad(intval($defaut_journal_reference_code) + 1, strlen($defaut_journal_reference_code), '0', STR_PAD_LEFT);
        } else {
            $initialreferencecode = '0000001';
            $finalcode = $initialreferencecode;
        }

        $general_ledger1 = GeneralLedger::create([
            'details' => str_replace("'", "''", trim(htmlspecialchars(ucfirst($request->comment)))),
            'account' => $request->debit_account,
            'debit' => $request->debit_amount,
            'reference' => $finalcode,
        ]);

        //CREDIT ACCOUNT

        if ($general_ledger1) {
            GeneralLedger::create([
                'details' => str_replace("'", "''", trim(htmlspecialchars(ucfirst($request->comment)))),
                'account' => $request->credit_account,
                'credit' => $request->credit_amount,
                'reference' => $finalcode,
            ]);
        }

        $subject = 'Creating a ledger Entry';
        $details = 'Creating a ledger entry for credit account '.$request->credit_account.' and debit account '.$request->account  .' and for amount '.$request->amount;
        $this->addToLog($subject, $details);

        return response()->json([
            'success' => true,
            'message' => 'Sucessfully created a new ledger Entry',
        ], 200);
    }

}
