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

class SubSubAccountController 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', '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();

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

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

    public function createASubSubBankAccount(Request $request)
    {
        $messages = [
            'sub_bank_account_id.required' => 'The Sub Bank Account field is required',
            'account_name.required' => 'The Account Name field is required'
        ];

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

        // //Get the last created sub account under a sub account
        // $last_account = DB::table('last_bank_accounts')
        //     ->select('last_bank_accounts.*')
        //     ->latest('last_bank_accounts.created_at')
        //     ->where('last_bank_accounts.sub_bank_account_id', $request->sub_bank_account_id)
        //     ->first();
        // //Get information about a given sub account
        // $sub_account = SubBankAccount::find($request->sub_bank_account_id);

        // if ($last_account) {
        //     //Get last two digits of item code
        //     $new_string = substr($last_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 = $sub_account->account_number . '-' . $intact_code;
        //     } else {
        //         $new_last_digit = $integer_string + 1;
        //         $code = (string) $new_last_digit;
        //         $new_item_code = $sub_account->account_number . '-' . $code;
        //     }
            LastBankAccount::create([
                'sub_bank_account_id' => $request->sub_bank_account_id,
                'name' => str_replace("'", "''", trim(htmlspecialchars(ucwords($request->account_name)))),
                'account_number' => str_replace("'", "''", trim(htmlspecialchars($request->item_code))),
            ]);
            $subject = 'Creating a sub 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 Sub Acccount',
            ], 201);

        // } else {
        //     $new_item_code = $sub_account->account_number . '-01';
        //     LastBankAccount::create([
        //         'sub_bank_account_id' => $request->sub_bank_account_id,
        //         'name' => ucwords($request->account_name),
        //         'account_number' => $new_item_code
        //     ]);
        //     $subject = 'Creating a sub 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 Sub Acccount',
        //     ], 201);
        // }
    }


    public function updateSubSubBankAccount(Request $request) {
        $messages = [
            'sub_bank_account_id.required' => 'The Sub Bank Account field is required',
            'account_name.required' => 'The Account Name field is required'
        ];

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

        //Get the last created sub account under a sub account
        $last_bank_account = LastBankAccount::select('id', 'sub_bank_account_id', 'account_number', 'name')
        ->where('id', $request->last_bank_accounts_id)->first();

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

        $subject = 'Updating a sub 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 Sub  Bank Account'
        ], 200);

    }
}
