<?php

namespace Accounting\entries;

use Accounting\ParamSetup;
use Base\DBQueries;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class JournalEntries extends ParamSetup
{
    private string $tbl = 'tbl_entries';
    private Request $request;

    public function setParams(): array { return ['request' => $this->request, 'table' => $this->tbl]; }

    public function main (Request $request) : JsonResponse {
        $this->request = $request;
        try {
            if($this->generateParams()){
                $this->filterTable = $this->table;
                $action = $this->action;
                return successResponse("Success",$this->values);
                //$this->details = $this->filterRequest();
                $this->addValues('status', 1);
                //$this->billingNumber = $this->getValue('billing_number');
                $this->execQuery();
                return $this->getResponse($action);
            }
        }
        catch (\Exception $ex){
            return failedResponse("ERROR", ["msg" => $ex->getMessage()], 422);
        }
        return failedResponse("ERROR", ["msg" => "Unknown Error!"], 400);
    }

    private function getResponse($action) : ?JsonResponse{
        $this->filterResponse();
        $responseMsg = "No Data Found!";
        if($this->response) {
            if ($action === 'dbGet') {
                $response = $this->response;
                $this->responseParser($response);
                $details = (new DBQueries("tbl_billing_details", null, conditions: ["billing_number" => $response->billing_number]))->dbGetAll();
                $details->map(function ($details){
                    $details->amount = number_format($details->amount, 2, '.',',');
                });
                $response->details = $details;
                return successResponse("Success",$response);
            }
            else if ($action === 'dbGetAll') {
                $response = $this->response;
                foreach($response as $res){
                    $this->responseParser($res);
                }

                return successResponse("Success",$response);
            }
            else $responseMsg = "Success";
        }
        return successResponse($responseMsg, $this->response);
    }

    private function responseParser($response) {
        $response->dueDate = Carbon::parse($response->due_date)->format('d-M-Y');
        $response->billingDate = Carbon::parse($response->billing_date)->format('d-M-Y');
        $response->billingDateDetails = Carbon::parse($response->billing_date)->format('j F Y');
        $response->dueDateDetails = Carbon::parse($response->due_date)->format('j F Y');
        $response->termsDetails = $response->terms.' '.$response->unit;
        $response->amount = number_format($response->amount, 2, '.',',');
        $response->payment = number_format($response->payment, 2, '.',',');
        $response->outstanding = number_format($response->outstanding, 2, '.',',');
        return $response;
    }

    public function addEntries($entries) : void {
        foreach ($entries as $entry){
            $add = new DBQueries($this->tbl, $entry);
            $add->dbInsert();
        }
    }

    public function addSubsidiaryEntries($entries) : void {
        foreach ($entries as $entry){
            foreach($entry['items'] as $items){
                $count = DB::table('tbl_entries_details')->where('acc_code',$entry['acc_code'])->where('key',$items['key'])
                    ->where('trans_code',$entry['trans_code'])->count();
                if($count > 0){
                    DB::table('tbl_entries_details')->where('acc_code',$entry['acc_code'])->where('key',$items['key'])
                        ->where('trans_code',$entry['trans_code'])->update([
                            'key' => $items['key'],'value' => $items['value'],
                        ]);
                }
                else {
                    $items['acc_code'] = $entry['acc_code'];
                    $items['trans_code'] = $entry['trans_code'];
                    $items['status'] = '1';
                    $items['created_at'] = date('Y-m-d H:i:s');
                    $items['updated_at'] = date('Y-m-d H:i:s');
                    $add = new DBQueries('tbl_entries_details', $items);
                    $add->dbInsert();
                }

            }
        }
    }
}
