<?php

namespace App\Http\Controllers;

use App\Models\CompanyChartsOfAccount;
use App\Models\CompanyCurrency;
use App\Models\CompanyFinancialMainAccount;
use App\Models\Payment;
use App\Models\Receipt;
use Illuminate\Http\Request;

class CompanyChartsOfAccountController extends Controller
{
    /**Get Chart of Account Details if Exist**/
    protected function accountDetailsWithStamp($stamp){
        $account = [];
        if(CompanyChartsOfAccount::firstWhere('stamp', $stamp)){
            $account = CompanyChartsOfAccount::where('stamp', $stamp)->first();
        }
        return $account;
    }

    /**See Full List of Company Charts Of Account**/
    public function index(){
        $branch = auth()->user()->branch;
        $lists = $name = $accounts = $allAccounts =[];
        $NonCurrentAssetaccounts = $CurrentAssetaccounts=[];
        $table = '';

        if(CompanyFinancialMainAccount::exists()){
            $list = CompanyFinancialMainAccount::distinct()->get('category');
            foreach ($list as $row){
                if($row->category == 'non_c_asset'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Non Current Assets</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'non_c_asset')->get();
                }elseif($row->category == 'c_asset'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Current Assets</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'c_asset')->get();
                }elseif ($row->category == 'income'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Income</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'income')->get();
                }elseif ($row->category == 'c_liability'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Current Liabilities</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'c_liability')->get();
                }elseif ($row->category == 'non_c_liability'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Non Current Liabilities</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'non_c_liability')->get();
                }elseif ($row->category == 'equity'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Equity</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'equity')->get();
                }elseif ($row->category == 'investment'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Investment</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'investment')->get();
                }elseif ($row->category == 'acc_dep_asset'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Accumulated Depreciation - Asset</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';

                    $allAccounts = CompanyFinancialMainAccount::where('category', 'acc_dep_asset')->get();
                }elseif ($row->category == 'expense'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Expense</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';
                    $allAccounts = CompanyFinancialMainAccount::where('category', 'expense')->get();
                }elseif ($row->category == 'purchases'){
                    $table .= '<tr style="border: 1px solid lightgray">';
                    $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px; background-color: #b3fdb3"><span class="error">Purchases</span></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;"></th>';
                    $table .= '<th style="border-right: 1px solid grey;" colspan="3"></th>';
                    $table .= '</tr>';
                    $allAccounts = CompanyFinancialMainAccount::where('category', 'purchases')->get();
                }

                /**Work on it now**/
                if($allAccounts != null){
                    foreach ($allAccounts as $account){
                        $table .= '<tr style="background-color: lightcyan; border: 1px solid lightgray">';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        $table .= '<th style="border-right: 1px solid grey; text-align: left; padding: 5px;"><b >'.strtoupper($account->name).'</b></th>';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        $table .= '<th style="border-right: 1px solid grey"></th>';
                        // $table .= '<th style=""></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th>';
                        $table .= '</tr>';
                        if(count($account->ledgerAccounts) > 0){
                            foreach ($account->ledgerAccounts as $row){
                                $table .= '<tr style="border: 1px solid lightgray">';
                                $table .= '<td style="border-right: 1px solid grey"></td>';
                                $table .= '<td style="border-right: 1px solid grey; padding: 5px" class="ar"></td>';
                                $table .= '<td style="border-right: 1px solid grey"><a href="/general-ledger-account/'.$row->stamp.'" class="inner" target="_blank"><b class="error">'.$row->acc_no.'</b></a></td>';
                                $table .= '<td style="border-right: 1px solid grey">'.$row->acc_name.'</td>';
                                $table .= '<td style="border-right: 1px solid grey">'.$account->category_type.'</td>';
                                if($row->currencyDetails != null){
                                    $table .= '<td style="border-right: 1px solid grey"><b>'.$row->currencyDetails->abbr.'</b></td>';
                                }else{
                                    $table .= '<td style="border-right: 1px solid grey"><i class="error">--Not Available--</i></td>';
                                }
                                $table .= '<td style="border-right: 1px solid grey">'.date('d-m-Y', strtotime($row->created_at)).'</td>';
                                if($row->user != null){
                                    $table .= '<td style="border-right: 1px solid grey">'.$row->user->firstName.' '.$row->user->lastName.'</td>';
                                }else{
                                    $table .= '<td style="border-right: 1px solid grey">-</td>';
                                }
                                $table .= '<td style="border-right: 1px solid grey"></td>';
                                $table .='</tr>';
                            }
                        }else{
                            $table .= '<tr style="border: 1px solid lightgray">';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '<th style="border-right: 1px solid grey; text-align: center; padding: 5px;"><i>No Ledger(s) Available</i></th>';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '<th style="border-right: 1px solid grey"></th>';
                            $table .= '</tr>';
                        }
                    }
                }
            }
            //dd($type);
            $lists = [
                'name' => $name,
                'accounts' => $accounts,
                'c_asset' => $CurrentAssetaccounts
            ];
        }

        //dd($lists);
        return view('charts-of-accounts', compact('lists', 'table'));
    }

    /**SEARCH  A RECEIPT **/
    public function searchGeneralLedger():object
    {
        $branch = auth()->user()->branch;

        $accounts = [];
        if(CompanyChartsOfAccount::where('branch', $branch)->orderBy('acc_name', 'asc')->first()){
            $accounts = CompanyChartsOfAccount::where('branch', $branch)->orderBy('acc_name', 'asc')->get();
        }
        return view('search.search-general-ledger', compact('accounts'));
    }

    /**Show a Single Chart of Account Details**/
    public function show($id){
        if($this->accountDetailsWithStamp($id)){
            $account = $this->accountDetailsWithStamp($id);
            $accounts = CompanyChartsOfAccount::where('branch', auth()->user()->branch)->get();

            /**At this Point, we want to get the Last 10 transaction of this Account**/


            return view('general-ledger-account', compact('account','accounts'));
        }
        return view('errors.404');
    }

    /**Create a New Chart of Account for the Company**/
    public function create(){
        $mainAccounts = [];
        if(CompanyFinancialMainAccount::first()){
            $mainAccounts = CompanyFinancialMainAccount::orderBy('type', 'asc')->orderBy('name', 'asc')->get();
        }
        $currencies = [];
        if(CompanyCurrency::where('status', 1)->first()){
            $currencies = CompanyCurrency::where('status', 1)->get();
        }
        return view('adds.add-company-chart-of-account', compact('mainAccounts','currencies'));
    }

    /**Store the Entered Details for the New Charts of Account**/
    public function store(Request $request):string
    {
        $branch = auth()->user()->branch;
        $type_id  = $request['type'];
        $currency = null;
        if(CompanyCurrency::where('type', 'base')->first()){
            $currency = CompanyCurrency::where('type', 'base')->first()->id;
        }
        $name = $request['account-name'];
        $number = $request['account-number'];

        $res = 'empty type';
        if(!empty($type_id)){
            if(CompanyFinancialMainAccount::where('id', $type_id)->first()->category == 'CB'){
                $currency = $request['currency'] ?? 'empty';
            }
            $res = 'empty currency';
            if($currency != 'empty'){
                $res = 'empty name';
                if(!empty($name)){
                    $res = 'empty number';
                    if(!empty($number)){
                        /**Generate a Unique Stamp**/
                        $stamp = (new RandomNumbersController)->getRandomMix(30);

                        $res = 'error';
                        if(!CompanyChartsOfAccount::where('stamp', $stamp)->first()){
                            /**Check if No such Account Name Exists under the Company Branch**/
                            $res = 'account exists';
                            if(!CompanyChartsOfAccount::where('branch', $branch)->where('acc_name', $name)->first()){
                                $res = 'number exists';
                                if(!CompanyChartsOfAccount::where('branch', $branch)->where('acc_no', $number)->first()){
                                    /**Create an Instance of the Charts Model and Insert the Data**/
                                    $init = new CompanyChartsOfAccount;

                                    if($init->create(
                                        [
                                            'branch' => $branch,
                                            'type_id' => $type_id,
                                            'acc_no' => $number,
                                            'acc_name' => $name,
                                            'stamp' => $stamp,
                                            'currency' => $currency,
                                            'created_by' => auth()->user()->id
                                        ]
                                    )){
                                        $res = '/general-ledger-account/'.$stamp.'?type=summary';
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $res;
    }

    /**Create a Function that will sum all receipts made to a Ledger, and also all payment made from the Ledger**/
    public function ledgerBalance($id){
        $balance = 0;
        /**The Above $id is the id of the charts of account for this Ledger **/
        $acc = CompanyChartsOfAccount::find($id);

        /**A ledger ID is related to the Main Ledger Type by the type_id attribute**/
        $mainAccount = CompanyFinancialMainAccount::find($acc->type_id);

        /**At this Point we need to go through each and Every Account and understand its Type**/
        if($mainAccount->category == 'c_asset'){
            /**We start with the Current Assets Account**/
            //1. If the Account is a CB, this means it is a Bank and Cash Account (Accepts Money in and Out) - Cannot be Mapped
            if($mainAccount->category_type == 'CB'){
                /**We need to sum up all items in the Acc Receipts Table connected to this Account**/
                $paidIn = Receipt::where('acc_id', $id)->sum('amount') ?? 0;
                $paidOut = Payment::where('acc_id', $id)->sum('amount') ?? 0;

                $balance = $paidIn - $paidOut;
            }//2. If the Account is just a LA, this means that it is just a normal Asset Account - Can be mapped
            elseif ($mainAccount->category_type == 'LA'){
                //my code goes in here
            }//2. If the Account is just a PC, this means
            elseif ($mainAccount->category_type == 'PC'){
                //my code goes in here
                $paidIn = Payment::where('ledger_id', $id)->sum('amount') ?? 0;
                $paidOut = Payment::where('acc_id', $id)->sum('amount') ?? 0;

                $balance = $paidIn - $paidOut;
            }
        }
        return $balance;
    }

    /**Create a Function that will be used to get all Account type Lists**/
    public function showAccountTypeList($type){
        $accounts = $mainAccounts = [];
        if($type == 'expense'){
            $mainAccounts = CompanyFinancialMainAccount::where('category', 'expense')->get();
        }elseif ($type == 'c_asset'){
            $mainAccounts = CompanyFinancialMainAccount::where('category', 'c_asset')->get();
        }elseif ($type == 'non_c_asset'){
            $mainAccounts = CompanyFinancialMainAccount::where('category', 'non_c_asset')->get();
        }elseif ($type == 'purchases'){
            $mainAccounts = CompanyFinancialMainAccount::where('category', 'purchases')->get();
        }

        /**Now Check through the List of returned main Accounts**/
        if($mainAccounts != null){
            foreach ($mainAccounts as $row){
                /**Each Main Account has a List of Charts of Accounts affiliated to It**/
                if($row->ledgerAccounts != null){
                    foreach ($row->ledgerAccounts as $ledger){
                        $accounts[] = $ledger;
                    }

                }
            }
        }
        return view('finance.get-account-type-list', compact('accounts'));
    }
}
