<?php

namespace App\Http\Controllers\Owner;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

use App\Http\Helpers\ResponseBuilder;
use App\Http\Helpers\ParamsValidator;
use App\Http\History\HistoryData;
use App\Http\History\HistoryTables;
use App\Modules\Shared\Infraestructure\LaravelExceptionHandler;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use App\Modules\UserCountry\Application\UserCountryInserter;
use App\Modules\UserCountry\Application\UserCountryUpdater;
use App\Modules\UserCountry\Domain\IdUserCountry;
use App\Modules\UserCountry\Domain\UserCountry;
use App\Modules\UserCountry\Domain\UserCountryCode;
use App\Modules\UserCountry\Domain\UserCountryFrequent;
use App\Modules\UserCountry\Domain\UserCountryFrequentOrder;
use App\Modules\UserCountry\Domain\UserCountryImg;
use App\Modules\UserCountry\Domain\UserCountryName;
use App\Modules\UserCountry\Domain\UserCountryPhoneCode;
use App\Modules\UserCountry\Domain\UserCountryStatus;
use App\Modules\UserCountry\Infraestructure\MysqlUserCountryRepository;
use App\Modules\UserCountry\Infraestructure\UserCountryValidators;
use Illuminate\Support\Facades\DB;
use Intervention\Image\ImageManagerStatic as Image;
use Throwable;

class c_User_Country extends Controller
{
    private $oDomain;
    /** @var HistoryData */
    private $history;


    public function __construct()
    {
        $this->oDomain = "User Country";
        $this->history = new HistoryData(HistoryTables::user_country);
    }

    public function Insert(Request $request)
    {
        try {
            return $this->InsertCountry($request);
        } catch (Throwable $ex) {
            return (new LaravelExceptionHandler())->handle($ex);
        }
    }

    public function InsertCountry(Request $Request)
    {
        $validator = (new LaravelValidator());
        $validator->validate($Request->all(), $this->oDomain, UserCountryValidators::insert);

        $oData = (new UserCountryInserter(new MysqlUserCountryRepository))->__invoke(
            new UserCountry(
                new UserCountryName(Str::title($Request->input("UserCountry_Name"))),
                new UserCountryCode(Str::upper($Request->input("UserCountry_Code"))),
                new UserCountryPhoneCode($Request->input("UserCountry_PhoneCode")),
                new UserCountryImg(" "),
                new UserCountryFrequent($Request->input("UserCountry_Frequent")),
                new UserCountryFrequentOrder($Request->input("UserCountry_FrequentOrder")),
                new UserCountryStatus($Request->input("UserCountry_Status"))
            )
        );
        $data = null;
        //  RESPONSE
        if ($oData[0]->Response_Success == 1) {
            //region HISTORY EXEC
            $this->history->insertBasic($Request, false);
            //endregion
            $data = ['Id' => $oData[0]->Response_Id];
        } else {
        }

        $oResponse["Response_Status"]           = $oData[0]->Response_Status;
        $oResponse["Response_Code"]             = $oData[0]->Response_Code;
        $oResponse["Response_Domain"]           = $this->oDomain;
        $oResponse["Response_Message"]          = $oData[0]->Response_Message;
        $oResponse["Response_Data"]             = $data;
        $oResponse["Response_Error_Message"]    = $oData[0]->Response_Message;
        $oResponse["Response_Error_Reason"]     = $oData[0]->Response_Reason;


        return ResponseBuilder::Response($oResponse);
    }
    public function Update(Request $Request)
    {
        $oResponse  = array();


        // VALIDANDO DATOS
        $oResponse = ParamsValidator::Validate_Request($Request, UserCountryValidators::update, $this->oDomain);

        //  INGRESANDO DATOS
        if ($oResponse["Response_Code"] == 200) {

            //region HISTORY VARIABLES
            $this->history->obtainOld($Request->input('Id_UserCountry'), '');
            //endregion

            // $Image_Current  = SELF::IndexImage($Request->input("Id_UserCountry"))[0]->UserCountry_Img;
            // $oResponse      = SELF::Upload($Request);

            $oData = (new UserCountryUpdater(new MysqlUserCountryRepository))->__invoke(
                new UserCountry(
                    new UserCountryName(Str::title($Request->input("UserCountry_Name"))),
                    new UserCountryCode(Str::upper($Request->input("UserCountry_Code"))),
                    new UserCountryPhoneCode($Request->input("UserCountry_PhoneCode")),
                    new UserCountryImg($Request->input("UserCountry_Img")),
                    new UserCountryFrequent($Request->input("UserCountry_Frequent")),
                    new UserCountryFrequentOrder($Request->input("UserCountry_FrequentOrder")),
                    new UserCountryStatus($Request->input("UserCountry_Status")),
                    new IdUserCountry($Request->input("Id_UserCountry"))
                )
            );

            //  RESPONSE
            if ($oData[0]->Response_Success == 1) {
                // if( $Request->hasFile( "UserCountry_Img" ) ){
                //     SELF::Remove($Image_Current);
                // }
                //region HISTORY EXEC
                $this->history->updateBasic($Request->input("Id_UserCountry"), $Request);
                //endregion
            } else {

                // ELIMINA ARCHIVO SUBIDO
                // SELF::Remove($oResponse["Image_Name"]);
            }

            $oResponse["Response_Status"]           = $oData[0]->Response_Status;
            $oResponse["Response_Code"]             = $oData[0]->Response_Code;
            $oResponse["Response_Domain"]           = $this->oDomain;
            $oResponse["Response_Message"]          = $oData[0]->Response_Message;
            $oResponse["Response_Data"]             = null;
            $oResponse["Response_Error_Message"]    = $oData[0]->Response_Message;
            $oResponse["Response_Error_Reason"]     = $oData[0]->Response_Reason;
        }

        return ResponseBuilder::Response($oResponse);
    }
    public function Delete(Request $Request, $Id)
    {
        $oResponse  = array();

        // VALIDANDO DATOS
        $oResponse = ParamsValidator::Validate_Id($Id, $this->oDomain);

        //  INGRESANDO DATOS
        if ($oResponse["Response_Code"] == 200) {

            //region HISTORY
            $this->history->obtainOld($Id, '');
            //endregion

            //$Image_Current  = SELF::Index($Id)[0]->UserCountry_Img_path;

            $oParam = array($Id);
            $oData  = DB::select('call sp_user_country_delete(?)', $oParam);

            //  RESPONSE
            if ($oData[0]->Response_Success == 1) {
                //region HISTORY EXEC
                $this->history->deleteBasic($Id, $Request);
                //endregion
            } else {
            }

            $oResponse["Response_Status"]           = $oData[0]->Response_Status;
            $oResponse["Response_Code"]             = $oData[0]->Response_Code;
            $oResponse["Response_Domain"]           = $this->oDomain;
            $oResponse["Response_Message"]          = $oData[0]->Response_Message;
            $oResponse["Response_Data"]             = null;
            $oResponse["Response_Error_Message"]    = $oData[0]->Response_Message;
            $oResponse["Response_Error_Reason"]     = $oData[0]->Response_Reason;
        }

        return ResponseBuilder::Response($oResponse);
    }
    public function Index(Request $Request, $Id)
    {
        $oResponse  = array();

        // VALIDANDO DATOS
        $oResponse = ParamsValidator::Validate_Id($Id, $this->oDomain);

        //  INGRESANDO DATOS
        if ($oResponse["Response_Code"] == 200) {

            $Path_Thumb     = config("var.PATH_PUBLIC") . config("var.USER_COUNTRY_THUMB");
            $oParam = array($Id, $Path_Thumb);
            $oData  = DB::select('call sp_user_country_index(?,?)', $oParam);

            $oResponse["Response_Status"]           = 200;
            $oResponse["Response_Code"]             = 200;
            $oResponse["Response_Domain"]           = $this->oDomain;
            $oResponse["Response_Message"]          = $this->oDomain . " Index";
            $oResponse["Response_Data"]             = $oData;
            $oResponse["Response_Error_Message"]    = "";
            $oResponse["Response_Error_Reason"]     = "";
        }

        return ResponseBuilder::Response($oResponse);
    }
    public function List(Request $Request, $Id)
    {
        $oResponse  = array();

        $oResponse = ParamsValidator::Validate_Action($Id, $this->oDomain);

        if ($oResponse["Response_Code"] == 200) {

            $Path_Thumb     = config("var.PATH_PUBLIC") . config("var.USER_COUNTRY_THUMB");
            $oParam = array($Id, $Path_Thumb);

            $oData  = DB::select('call sp_user_country_list(?,?)', $oParam);

            $oResponse["Response_Status"]           = 200;
            $oResponse["Response_Code"]             = 200;
            $oResponse["Response_Domain"]           = $this->oDomain;
            $oResponse["Response_Message"]          = $this->oDomain . " list " . $Id;
            $oResponse["Response_Data"]             = $oData;
            $oResponse["Response_Error_Message"]    = "";
            $oResponse["Response_Error_Reason"]     = "";
        }

        return ResponseBuilder::Response($oResponse);
    }

    public function Selector(Request $Request, $Id)
    {
        if (is_numeric($Id)) {
            return SELF::Index($Request, $Id);
        } else {
            return SELF::List($Request, $Id);
        }
    }


    public function IndexImage($Id_UserCountry)
    {
        $Path_Thumb     = config("var.PATH_PUBLIC") . config("var.USER_COUNTRY_THUMB");
        $oParam = array($Id_UserCountry, $Path_Thumb);
        $oData  = DB::select('call sp_user_country_index(?,?)', $oParam);

        return $oData;
    }
    public function Upload(Request $Request)
    {

        // ----------------------------------------------------------------------------------------------------------------------------------
        // INICIA VARIABLES DE FUNCCION
        // ----------------------------------------------------------------------------------------------------------------------------------
        $oResponse      = array();
        $oData          = array();

        $Image_Input    = "UserCountry_Img";
        $Image_Prefix   = "USERCOUNTRY_";
        $Path_Temp      = config("var.PATH_PRIVATE") . config("var.PATH_TEMP");
        $Path_Thumb     = config("var.PATH_PRIVATE") . config("var.USER_COUNTRY_THUMB");

        // ----------------------------------------------------------------------------------------------------------------------------------
        // OBTIENE VALOR DE LA IMAGEN ACTUAL
        // ----------------------------------------------------------------------------------------------------------------------------------

        if ($Request->input("Id_UserCountry")) {
            $oData      = SELF::IndexImage($Request->input("Id_UserCountry"));
        }

        // ----------------------------------------------------------------------------------------------------------------------------------
        // SUBE ARCHIVO NUEVO O DEVUELVE URL DE ARCHIVO ACTUAL
        // ----------------------------------------------------------------------------------------------------------------------------------

        if ($Request->hasFile($Image_Input)) {

            $Image_Ext      = $Request->file($Image_Input)->getClientOriginalExtension();
            $Image_Name     = $Image_Prefix . date("ymd_His") . "." . $Image_Ext;

            if ($Request->file($Image_Input)->move($Path_Temp, $Image_Name)) {
                //
                //  Redimensiona Imagen Thumb
                //
                $Image_Thumb = Image::make($Path_Temp . $Image_Name);
                $Image_Thumb->fit(config("var.ICON_W"), config("var.ICON_W"));
                $Image_Thumb->save($Path_Thumb . $Image_Name);


                //
                //  ELIMINA TEMPORAL
                //
                unlink($Path_Temp . $Image_Name);


                //
                //  RESPONSE
                //
                $oResponse["RespCode"]      = 200;
                $oResponse["Image_Name"]    = $Image_Name;
                $oResponse["RespMessage"]   = null;
                $oResponse["RespData"]      = null;
                $oResponse["ErDomain"]      = null;
                $oResponse["ErReason"]      = null;
                $oResponse["ErMessage"]     = null;
            } else {
                $oResponse["RespCode"]      = 422;
                $oResponse["Image_Name"]    = "";
                $oResponse["RespMessage"]   = "Error uploading image.";
                $oResponse["RespData"]      = null;
                $oResponse["ErDomain"]      = $this->oDomain;
                $oResponse["ErReason"]      = "Error uploading image.";
                $oResponse["ErMessage"]     = "";
            }
        } else {
            $oResponse["RespCode"]      = 200;
            $oResponse["Image_Name"]    = $oData[0]->UserCountry_Img;
            $oResponse["RespMessage"]   = null;
            $oResponse["RespData"]      = null;
            $oResponse["ErDomain"]      = null;
            $oResponse["ErReason"]      = null;
            $oResponse["ErMessage"]     = null;
        }

        return $oResponse;
    }
    public function Remove($Image_Name)
    {
        $Path_Thumb     = config("var.PATH_PRIVATE") . config("var.USER_COUNTRY_THUMB");

        if ($Image_Name != "") {
            if (unlink($Path_Thumb . $Image_Name)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
