<?php

namespace Accounting\config;

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

class BranchesController extends ParamSetup
{
    private string $tbl = 'tbl_branch';
    private Request $request;
    private $branch_code;
    private $branch_status;
    private array $others;
    public function setParams()
    {
        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;
                if (in_array($this->filterTable, array_keys(HIDDEN_REQUEST_FIELDS))) $this->others = $this->filterRequest();
                $this->execQuery();
                if ($this->response || $this->request->input("type") === "update") $this->saveOtherDetails();
                if ($this->response && $this->request->input("type") === "delete") $this->deleteDetails();
                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
    {
        if (in_array($this->filterTable, array_keys(HIDDEN_RESPONSE_FIELDS))) $this->filterResponse();
        $responseMsg = "No Data Found!";
        if($this->response) {
            if($action == 'dbInsert') {
                $responseMsg = 'branch_code';
            } else if($action === 'dbGetAll') {
                $response = $this->response;
                foreach ($response as $key => $data) {
                    $data->details = (new DBQueries("tbl_branch_details", null, conditions: ["branch_code" => $data->code]))->dbGetAll();
                    $this->responseParser($data);
                }
                return successResponse("Success", $response);
            } else $responseMsg = "Success";
        }
        return successResponse($responseMsg, $this->response);
    }

    public function saveOtherDetails() : void
    {
        $this->branch_code = $this->getValue('code');
        $this->branch_status = $this->getValue('status');
        if ($this->action === 'dbInsert') {
            $details = $this->others;
            foreach ($details['details'] as $k => $detail) {
                if (is_array($detail) || is_object($detail)) {
                    foreach ($detail as $key => $value) {
                        $this->addOtherDetails($key, $k, $value);
                    }
                } else $this->addOtherDetails($k, 'info', $detail);
            }
        } else if ($this->action === "dbUpdate") {
            DB::table('tbl_branch_details')->where('branch_code', $this->branch_code)
                ->update(['status' => $this->branch_status]);
            $details = $this->others;
            foreach($details['details'] as $k => $detail) {
                if (is_array($detail)) {
                    foreach($detail as $key => $value) {
                        $this->updateOtherDetails($key, $k, $value);
                    }
                } else $this->updateOtherDetails($k, "info", $detail);
            }
        }
    }

    private function addOtherDetails($type, $category, $value): void
    {
        $this->branch_code = $this->getValue('code');
        $values['branch_code'] = $this->branch_code;
        $values['type'] = $type;
        $values['category'] = $category;
        $values['value'] = $value;
        $values['status'] = $this->branch_status;
        $add = new DBQueries('tbl_branch_details', $values);
        $this->response = $add->dbInsert();
    }
    private function updateOtherDetails($type, $category, $value): void
    {
        $this->branch_code = $this->getValue('code');
        $conditions["branch_code"] = $this->branch_code;
        $conditions["type"] = $type;
        $conditions["category"] = $category;
        $values["value"] = $value;
        $values["status"] = $this->branch_status;
        $this->response =  (new DBQueries("tbl_branch_details", $values, $conditions))->dbUpdate();
    }

    private function deleteDetails() : void {
        $branch_code = $this->conditions['code'];

        $conditions["branch_code"] = $branch_code;
        $this->response =  (new DBQueries("tbl_branch_details", null, $conditions))->dbDelete();
    }

    private function responseParser($response) {
        foreach($response->details as $detail) {
            $key = $detail->category;
            $response->$key[$detail->type] = $detail->value ?? "";
        }
        unset($response->details);
    }
}
