<?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\Traits\LogActivityTrait;
use Illuminate\Support\Facades\Validator;

class SubBankAccountsController extends Controller
{
    use LogActivityTrait;

    public function __construct()
    {
        $this->middleware('auth');
    } 
    
    public function index() {
        $ledgers = DB::table('ledgers')
        ->select('id', 'name', 'item_code', 'created_at')
        ->orderBy('ledgers.created_at', 'DESC')
        ->get();
        $ledger_categories = DB::table('ledger_categories')
        ->select('ledger_categories.id as ledger_category_id',
            'ledger_categories.name as category_name',
            'ledger_categories.ledger_id as account_group_id',
            'ledgers.name', 'ledger_categories.created_at', 'ledger_categories.item_code')
        ->leftJoin('ledgers', 'ledger_categories.ledger_id', '=', 'ledgers.id')
        ->orderBy('ledger_categories.created_at', 'DESC')
        ->get();

        $bank_accounts = DB::table('bank_accounts')
        ->select('bank_accounts.id as bank_id', 'bank_accounts.name as account_name',
            'bank_accounts.account_number',
            'ledger_categories.id as ledger_category_id',
            'ledgers.id as account_group_id',
            'ledger_categories.name as category_name', 'ledgers.name as ledger_name', 'bank_accounts.created_at')
        ->leftJoin('ledgers', 'bank_accounts.ledger_id', '=', 'ledgers.id')
        ->leftJoin('ledger_categories', 'bank_accounts.ledger_category_id', '=', 'ledger_categories.id')
        ->orderBy('bank_accounts.created_at', 'DESC')
        ->get();

        $sub_bank_accounts = DB::table('sub_bank_accounts')
        ->select('sub_bank_accounts.id as sub_bank_account_id',
            'sub_bank_accounts.name as account_name', 'sub_bank_accounts.bank_account_id  as bank_id',
            'sub_bank_accounts.account_number as item_code', 'bank_accounts.name', 'sub_bank_accounts.created_at')
        ->leftJoin('bank_accounts', 'sub_bank_accounts.bank_account_id', '=', 'bank_accounts.id')
        ->orderBy('sub_bank_accounts.created_at', 'DESC')
        ->get();

        return Inertia::render('ChartOfAccounts/SubBankAccountsComponent', [
            'ledgers' => $ledgers,
            'ledger_categories' => $ledger_categories,
            'bank_accounts' => $bank_accounts,
            'sub_bank_accounts' => $sub_bank_accounts
        ]);
    }

    public function getLedgerWhereBankAccountExist($bank_id) {
        $bank_account = BankAccount::select('id', 'ledger_id')->where('id', $bank_id)->first();


        $ledger = Ledger::select('id', 'name')->where('id', $bank_account->ledger_id)->first();

        return  $ledger;
    }

    public function getBankAccountsUnderGivenSelectedLedger($id) {
        $bank_account    = DB::table('bank_accounts')
        ->select('bank_accounts.id as bank_id', 'bank_accounts.name as account_name',
            'bank_accounts.account_number',
            'ledger_categories.id as ledger_category_id',
            'ledgers.id as account_group_id',
            'ledger_categories.name as category_name', 'ledgers.name as ledger_name', 'bank_accounts.created_at')
        ->leftJoin('ledgers', 'bank_accounts.ledger_id', '=', 'ledgers.id')
        ->leftJoin('ledger_categories', 'bank_accounts.ledger_category_id', '=', 'ledger_categories.id')
        ->orderBy('bank_accounts.created_at', 'DESC')
        ->where('bank_accounts.ledger_id', $id)
        ->get();


        return $bank_account;
    }

    public function createSubBankAccount(Request $request)
    {
        $messages = [
            'account_group_id.required' => 'The Account Group field is required',
            'bank_id.required' => 'The Bank Account field is required',
            'account_name.required' => 'The Account Name field is required'
        ];

        $validator = Validator::make($request->all(), [
            'account_group_id' => 'required',
            'account_name' => 'required',
            'bank_id' => 'required',
            'item_code' => 'required'
        ], $messages);
            
        //VALIDATE THE REQUEST INPUTS
        if($validator->fails()){
            return response()->json($validator->errors(), 400);
        }

        // //Get the last created sub account
        // $last_sub_account = DB::table('sub_bank_accounts')
        //     ->latest('sub_bank_accounts.created_at')
        //     ->where('sub_bank_accounts.bank_account_id', 
        //     $request->bank_id)->first();
        // //Get A given account
        // $account = BankAccount::find($request->bank_id);
        // if ($last_sub_account) {
        //     //Get last two digits of item code
        //     $new_string = substr($last_sub_account->account_number, -2);
        //     //convert string to integer
        //     $integer_string = (int) $new_string;

        //     if ($integer_string <= 9) {
        //         $new_last_digit = $integer_string + 1;
        //         $code = (string) $new_last_digit;
        //         $intact_code = '0' . $code;
        //         $new_item_code = $account->account_number . '-' . $intact_code;
        //     } else {
        //         $new_last_digit = $integer_string + 1;
        //         $code = (string) $new_last_digit;
        //         $new_item_code = $account->account_number . '-' . $code;
        //     }
            SubBankAccount::create([
                'bank_account_id' => $request->bank_id,
                'name' => str_replace("'", "''", trim(htmlspecialchars(ucwords($request->account_name)))),
                'account_number' => str_replace("'", "''", trim(htmlspecialchars($request->item_code)))
            ]);
            $subject = 'Creating a sub bank account';
            $details = 'Creating account with name : ' . $request->account_name;
            $this->addToLog($subject, $details);
            
            return response()->json([
                'success' => true,
                'message' => 'Sucessfully created a Sub Acccount',
            ], 200);

        // } else {
            // $new_item_code = $account->account_number . '-01';
            // SubBankAccount::create([
            //     'bank_account_id' => $request->bank_id,
            //     'name' => ucwords($request->account_name),
            //     'account_number' => $new_item_code,
            // ]);

            // $subject = 'Creating a sub bank account';
            // $details = 'Creating account with name : ' . $request->account_name;
            // $this->addToLog($subject, $details);

            // return response()->json([
            //     'success' => true,
            //     'message' => 'Sucessfully created a Sub Acccount',
            // ], 200);
        // }
    }

    public function updateSubBankAccount(Request $request)
    {
        $messages = [
            'account_group_id.required' => 'The Account Group field is required',
            'bank_id.required' => 'The Bank Account field is required',
            'account_name.required' => 'The Account Name field is required'
        ];

        $validator = Validator::make($request->all(), [
            'account_group_id' => 'required',
            'account_name' => 'required',
            'bank_id' => 'required',
            'item_code' => 'required'
        ], $messages);
            
        //VALIDATE THE REQUEST INPUTS
        if($validator->fails()){
            return response()->json($validator->errors(), 400);
        }

        //Retrieve the Bank and update
        $account = SubBankAccount::select('id', 'bank_account_id', 
        'account_number', 'name')->where('id', $request->sub_bank_account_id)->first();

        $account->name = str_replace("'", "''", trim(htmlspecialchars(ucwords($request->account_name))));
        $account->bank_account_id = $request->bank_id;
        $account->account_number = str_replace("'", "''", trim(htmlspecialchars(ucwords($request->item_code))));
        $account->save();

        $subject = 'Updating a sub bank account';
        $details = 'Updating account with name : ' . $request->account_name;
        $this->addToLog($subject, $details);
        return response()->json([
            'success' => true,
            'message' => 'Sucessfully updated '.$request->account_name.' a Sub Bank Account'
        ], 200);
    }
}
