<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use App\Http\Controllers\EncController;

use PDOException;

class MCOMDFController extends Controller{
    public function create(Request $request){
        $validator = Validator::make($request->all(), [
            'dia' => 'required|integer|max:31',
            'mes' => 'required|integer|max:12',
            'anio' => 'required|integer|max:2100',
            'rfc_empresa' => 'required|string',
            'motivo' => 'required|string|max:100',
            'id_usuario_registra' => 'required|string|max:50'
        ]);

        if ($validator->fails()) {
            return $this->makeResponse(
                true,
                "ERR_MCOMDF_USU_CRE000: Se encontraron uno o más errores.",
                $this->makeErrors($validator->errors()->messages()),
                400
            );
        }

        $diaFeriado = $request->all();
        $pdo = DB::connection()->getPdo();

        $hoy = Carbon::now()->timezone('America/Mexico_City');
        $diaStr  = $diaFeriado['anio'] . "-";
        $diaStr .= (intval($diaFeriado['mes']) < 10 ? "0$diaFeriado[mes]" : $diaFeriado['mes']) . "-";
        $diaStr .= (intval($diaFeriado['dia']) < 10 ? "0$diaFeriado[dia]" : $diaFeriado['dia']);
        $dia = new Carbon($diaStr);

        if ($hoy->gt($dia)) {
            return $this->makeResponse(true, "ERR_MCOMDF_USU_CRE001: El día insertado debe ser mayor a la fecha actual.", [], 400);
        }

        $qry = 'INSERT INTO S001V01TDIFE (DIFE_DIAX, DIFE_MESX, DIFE_ANIO, DIFE_RFCE, DIFE_ESTA, DIFE_MOTI, DIFE_USRE, DIFE_FERE, DIFE_FEAR) 
                VALUES (:diax, :msec, :anio, :rfce, "Activo", :moti, :usre, :fere, CURRENT_TIMESTAMP)';
        $gst = $pdo->prepare($qry);

        $hoyStr = $hoy->toDateTimeString();
        $encriptacion = new EncController();
        $rfce = $encriptacion->desencriptar($diaFeriado['rfc_empresa']);

        $gst->bindParam(":diax", $diaFeriado['dia']);
        $gst->bindParam(":msec", $diaFeriado['mes']);
        $gst->bindParam(":anio", $diaFeriado['anio']);
        $gst->bindParam(":rfce", $rfce);
        $gst->bindParam(":moti", $diaFeriado['motivo']);
        $gst->bindParam(":usre", $diaFeriado['id_usuario_registra']);
        $gst->bindParam(":fere", $hoyStr);

        try{
            if (!$gst->execute()) {
                return $this->makeResponse(true, "ERR_MCOMDF_SER_CRE002: No se pudo insertar el registro.", [], 500);
            }
        }catch(PDOException $e){
            return $this->makeResponse(true, "ERR_MCOMDF_SER_CRE003: El día feriado ya existe.", [], 500);
        }

        return $this->makeResponse(false, "EXITO: Día feriado insertado");
    }

    public function delete(Request $request){
        $validator = Validator::make($request->all(), [
            'dia' => 'required|integer|max:31',
            'mes' => 'required|integer|max:12',
            'anio' => 'required|integer|max:2100',
            'id_usuario_elimina' => 'required|string|max:50'
        ]);

        if ($validator->fails()) {
            return $this->makeResponse(
                true,
                "ERR_MCOMDF_USU_DEL000: Se encontraron uno o más errores.",
                $this->makeErrors($validator->errors()->messages()),
                400
            );
        }

        $diaFeriado = $request->all();
        $pdo = DB::connection()->getPdo();

        $qryRFCE = "SELECT USUA_RFCE FROM S001V01TUSUA WHERE USUA_IDUS = :idus";
        $gstRFCE = $pdo->prepare($qryRFCE);
        $gstRFCE->bindParam(":idus", $diaFeriado['id_usuario_elimina']);

        $gstRFCE->execute();
        $rfce = $gstRFCE->fetchObject()->USUA_RFCE;

        $qry = 'UPDATE S001V01TDIFE SET DIFE_ESTA = "Eliminado", DIFE_USMO = :usmo, DIFE_FEMO = :femo 
                WHERE DIFE_DIAX = :diax AND DIFE_MESX = :mesc AND DIFE_ANIO = :anio AND DIFE_RFCE = :rfce';
        $gst = $pdo->prepare($qry);

        $hoy = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();

        $gst->bindParam(":usmo", $diaFeriado['id_usuario_elimina']);
        $gst->bindParam(":femo", $hoy);
        $gst->bindParam(":diax", $diaFeriado['dia']);
        $gst->bindParam(":mesc", $diaFeriado['mes']);
        $gst->bindParam(":anio", $diaFeriado['anio']);
        $gst->bindParam(":rfce", $rfce);
        
        if (!$gst->execute()) {
            return $this->makeResponse(true, "ERR_MCOMDF_SER_DEL001: No se pudo eliminar el registro.", [], 500);
        }
        
        return $this->makeResponse(false, "EXITO: Dia feriado eliminado");
    }

    public function habilitar(Request $request){
        $validator = Validator::make($request->all(), [
            'dia' => 'required|integer|max:31',
            'mes' => 'required|integer|max:12',
            'anio' => 'required|integer|max:2100',
            'id_usuario_habilita' => 'required|string|max:50'
        ]);

        if ($validator->fails()) {
            return $this->makeResponse(
                true,
                "ERR_MCOMDF_USU_HAB000: Se encontraron uno o más errores.",
                $this->makeErrors($validator->errors()->messages()),
                400
            );
        }

        $diaFeriado = $request->all();
        $pdo = DB::connection()->getPdo();

        $qryRFCE = "SELECT USUA_RFCE FROM S001V01TUSUA WHERE USUA_IDUS = :idus";
        $gstRFCE = $pdo->prepare($qryRFCE);
        $gstRFCE->bindParam(":idus", $diaFeriado['id_usuario_habilita']);

        $gstRFCE->execute();
        $rfce = $gstRFCE->fetchObject()->USUA_RFCE;

        $qry = 'UPDATE S001V01TDIFE SET DIFE_ESTA = "Activo", DIFE_USMO = :usmo, DIFE_FEMO = :femo 
                WHERE DIFE_DIAX = :diax AND DIFE_MESX = :mesc AND DIFE_ANIO = :anio AND DIFE_RFCE = :rfce';
        $gst = $pdo->prepare($qry);
        
        $hoy = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();

        $gst->bindParam(":usmo", $diaFeriado['id_usuario_habilita']);
        $gst->bindParam(":femo", $hoy);
        $gst->bindParam(":diax", $diaFeriado['dia']);
        $gst->bindParam(":mesc", $diaFeriado['mes']);
        $gst->bindParam(":anio", $diaFeriado['anio']);
        $gst->bindParam(":rfce", $rfce);
        
        if (!$gst->execute()) {
            return $this->makeResponse(true, "ERR_MCOMDF_SER_HAB001: No se pudo activar el registro.", [], 500);
        }
        
        return $this->makeResponse(false, "EXITO: Dia feriado habilitado");
    }

    public function getDiasFeriados($rfce, $nonce){
        $pdo = DB::connection()->getPdo();
        $encController = new EncController();
        $rfce = $encController->desencriptar(base64_encode($rfce . "|" . $nonce));
        $qry = 'SELECT DIFE_DIAX AS DIA, DIFE_MESX AS MES, DIFE_ANIO AS ANIO, DIFE_MOTI AS MOTIVO 
                FROM S001V01TDIFE WHERE DIFE_ESTA != "Eliminado" AND DIFE_RFCE = :rfce';
        $gst = $pdo->prepare($qry);
        $gst->bindParam(":rfce", $rfce);
        
        if (!$gst->execute()) {
            return $this->makeResponse(true, "ERR_MCOMDF_SER_GDF000: No se pudo consultar la información.", [], 500);
        }

        //return response()->json(['dias_feriados' => $gst->fetchAll($pdo::FETCH_ASSOC)], 200);
        return $this->makeResponse(false, "EXITO", $gst->fetchAll($pdo::FETCH_ASSOC));
    }

    private function makeResponse($error, $msg, $response = [], $code = 200){
        $respuesta = json_encode([
            "error" => $error,
            "msg" => $msg,
            "response" => $response
        ]);

        return response($respuesta, $code)->header('Content-Type', 'application/json');
    }

    private function makeErrors($erroresObj){
        $erroresArr = array();

        foreach ($erroresObj as $key => $value) {
            foreach ($value as $key0 => $value0) {
                if(array_key_exists($key, $erroresArr)){
                    $val = $erroresArr[$key] . "|" . $value0;
                    $erroresArr[$key] = $val;
                }else{
                    $erroresArr[$key] = $value0;
                }
            }
        }

        return $erroresArr;
    }
}
