<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Carbon;

class FunctionsController extends Controller{
    public function __construct(){}

    public static function uuidv5($namespace, $name) {
        if(!self::is_valid($namespace)) return false;

        // Get hexadecimal components of namespace
        $nhex = str_replace(array('-','{','}'), '', $namespace);

        // Binary Value
        $nstr = '';

        // Convert Namespace UUID to bits
        for($i = 0; $i < strlen($nhex); $i+=2) {
            $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
        }

        // Calculate hash value
        $hash = sha1($nstr . $name);

        return sprintf('%08s-%04s-%04x-%04x-%12s',

            // 32 bits for "time_low"
            substr($hash, 0, 8),

            // 16 bits for "time_mid"
            substr($hash, 8, 4),

            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 5
            (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,

            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

            // 48 bits for "node"
            substr($hash, 20, 12)
        );
    }

    public static function is_valid($uuid) {
        return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'.
                        '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1;
    }

    public function generateID($seed, $timestamp){
        $string = str_replace(" ", "", $seed) . $timestamp;
        $array = [];
        for($i = 0; $i < strlen($string); $i++){
            $array[] = $string[$i];
        }

        shuffle($array);
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        
        $ID = '';
        foreach($array as $char){
            $ascii = ord($char);

            $s = $ascii / 100;
            if($s >= 1) continue;

            $s = $s * strlen($chars);
            $s = intval($s);

            $l = $chars[$s];
            if(strlen($ID) < 20) $ID .= $l;
        }

        if(strlen($ID) < 20){
            for($i = strlen($ID); $i < 20; $i++){
                $s = rand(0, strlen($chars) - 1);
                $l = $chars[$s];
                $ID .= $l;
            }
        }
        
        return $ID;
    }

    public function getType($type){
        switch($type){
            case "insert":
                return "CREATE";
            break;
            case "update":
                return strtoupper($type);
            break;
            case "select":
                return "READ";
            break;
            case "delete":
                return strtoupper($type);
            break;
            default:
                return "UNKNOWN";
            break;
        }
    }

    public function registerLog($querys, $user, $date, $idac, $line){
        foreach($querys as $query){
            $script = $query['query'];
            $params = json_encode($query['bindings']);

            DB::table('S002V01TLOMY')->insert([
                'LOMY_NULI' => $line,
                'LOMY_IDAC' => $idac,
                'LOMY_QUER' => $script,
                'LOMY_PARA' => $params,
                'LOMY_FECH' => $date,
                'LOMY_IDUS' => $user,
            ]);
        }
    }

    public function registerActivity($line, $module, $function, $screen, $action, $description, $user, $date, $submodule = null){
        $id = DB::table('S002V01TACCI')->insertGetId([
            'ACCI_NULI' => $line,
            'ACCI_IDMO' => $module,
            'ACCI_IDSM' => $submodule,
            'ACCI_IDFU' => $function,
            'ACCI_IDPA' => $screen,
            'ACCI_TIAC' => $action,
            'ACCI_DESC' => $description,
            'ACCI_IDUS' => $user,
            'ACCI_FEAC' => $date
        ]);

        DB::table('S002V01TUSUA')->where('USUA_IDUS', '=', $user)->update([
            'USUA_ULAC' => $id
        ]);

        return $id;
    }

    public function joinName($name, $fApe, $sApe = null){
        $fullName = "$name $fApe";
        if(!is_null($sApe)){
            $fullName = "$fullName $sApe";
        }

        return $fullName;
    }

    public function checkFileSize($ext, $size){
        $availableFiles = [
            250=> ["zip", "tar", "rar", "7z", "mp3", "mpeg", "wav", "ogg", "opus", "jpg", "png", "gif", "bmp", "tiff", "svg",
            "txt", "webm", "mp4", "3gp", "mov", "avi", "wmv", "flv", "dwg", "dxf", "3ds", "ai", "psd", "xml"],
            50 => ["doc", "docx", "vsd", "vsdx", "pdf"],
            75 => ["xls", "xlsx"],
            100=> ["ppt", "pptx"],
        ];

        $maxFileSizeMB = 0;
        foreach($availableFiles as $k=>$v){
            if(in_array($ext, $v)) $maxFileSizeMB = $k;
        }

        if($maxFileSizeMB == 0) return false;

        $maxFileSize = $maxFileSizeMB * 1048576;
        return $size < $maxFileSize;
    }

    public function checkInvoice($file) {

        try {
            $xml = simplexml_load_string($file, 'SimpleXMLElement', LIBXML_NOCDATA);
            $ns = $xml->getNamespaces(true);
            $xml->registerXPathNamespace('c', $ns['cfdi']);
            $xml->registerXPathNamespace('t', $ns['tfd']);
        } catch (\Throwable $th) {
            return $this->responseController->makeResponse(
                true,
                "ERR_INVOICE_COMPARE006: Ocurrió un error al obtener la información del documento.",
                $th->getMessage(),
                500
            );
        }
        $arrInfoInvoice = ((array) $xml)['@attributes'];
        if (
            array_key_exists('Version', $arrInfoInvoice) &&
            array_key_exists('Serie', $arrInfoInvoice) &&
            array_key_exists('Folio', $arrInfoInvoice) &&
            array_key_exists('TipoDeComprobante', $arrInfoInvoice) &&
            array_key_exists('NoCertificado', $arrInfoInvoice) &&
            array_key_exists('Certificado', $arrInfoInvoice) &&
            array_key_exists('Sello', $arrInfoInvoice) &&
            array_key_exists('FormaPago', $arrInfoInvoice) &&
            array_key_exists('MetodoPago', $arrInfoInvoice) &&
            array_key_exists('SubTotal', $arrInfoInvoice) &&
            array_key_exists('Moneda', $arrInfoInvoice) &&
            array_key_exists('TipoCambio', $arrInfoInvoice) &&
            array_key_exists('Total', $arrInfoInvoice) &&
            array_key_exists('LugarExpedicion', $arrInfoInvoice) &&
            array_key_exists('CondicionesDePago', $arrInfoInvoice) &&
            array_key_exists('Fecha', $arrInfoInvoice) &&
            array_key_exists('Exportacion', $arrInfoInvoice)
        ) {
            return true;
        }
        return false;
    }

    public function now(){
        $completeDate = shell_exec('echo %date%');
        $completeDate = trim($completeDate);
        
        $serverDateTime = "";
        if(strlen($completeDate) == 14){
            $serverDateTime = shell_exec('echo %date:~10,4%-%date:~4,2%-%date:~7,2% %time:~0,2%:%time:~3,2%:%time:~6,2%');
            $serverDateTime = trim($serverDateTime);
        }else{
            $serverDateTime = shell_exec('echo %date:~6,4%-%date:~3,2%-%date:~0,2% %time:~0,2%:%time:~3,2%:%time:~6,2%');
            $serverDateTime = trim($serverDateTime);
        }

        return new Carbon($serverDateTime);
    }

    public function validDate($date){
        if(preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)){
            return true;
        }else{
            return false;
        }
    }

    public function floatAdd(...$numbers) : float{
        $result = "0.0";
        foreach($numbers as $n){
            $result = bcadd("$result", "$n", 18);
        }
        return floatval($result);
    }

    public function floatSub($fn, $sn) : float{
        $result = bcsub("$fn", "$sn", 18);
        return floatval($result);
    }

    public function floatDiv($fn, $sn) : float{
        $result = bcdiv("$fn", "$sn", 18);
        return floatval($result);
    }

    public function floatMul($n1, $n2) : float {
        $result = bcmul("$n1", "$n2", 18);
        return floatval($result);
    }

    public function formatDateTime(string $dateTime) : string {
        if(str_contains($dateTime, '0001-01-01')){
            return "-";
        }

        $MONTHS = ["01" => "Enero", "02" => "Febrero", "03" => "Marzo", "04" => "Abril", "05" => "Mayo", "06" => "Junio", "07" => "Julio", 
        "08" => "Agosto", "09" => "Septiembre", "10" => "Octubre", "11" => "Noviembre", "12" => "Diciembre"];
        $dateTimeArr = explode(" ", $dateTime);
        $dateArr = explode("-", $dateTimeArr[0]);
        $month = $MONTHS[$dateArr[1]];
        $day = intval($dateArr[2]);

        $dateTimeStr = $day . " de " . $month . " del " . $dateArr[0];
        $timeArr = explode(":", $dateTimeArr[1]);
        $hour = intval($timeArr[0]);
        $period = $hour < 12 ? 'AM' : 'PM';
        $hour = $hour > 12 ? $hour - 12 : $hour;

        $dateTimeStr .= " a las " . $hour . ":" . $timeArr[1] . " " . $period;
        return $dateTimeStr;
    }

    public function buildHumanCurrentDate(string $dateTime) : string {
        $DAYS = ["Mo" => "Lunes", "Tu" => "Martes", "We" => "Miércoles", "Th" => "Jueves", 
        "Fr" => "Viernes", "Sa" => "Sábado", "Su" => "Domingo"];
        $MONTHS = ["01" => "Enero", "02" => "Febrero", "03" => "Marzo", "04" => "Abril", "05" => "Mayo", "06" => "Junio", "07" => "Julio", 
        "08" => "Agosto", "09" => "Septiembre", "10" => "Octubre", "11" => "Noviembre", "12" => "Diciembre"];
        
        $dateTimeArr = explode(" ", $dateTime);
        $dateArr = explode("-", $dateTimeArr[0]);
        $dateObj = new Carbon($dateTime);
        $dayName = $dateObj->format('l');
        $dayInd = substr($dayName, 0, 2);
        
        return $DAYS[$dayInd] . ", " . $dateArr[2] . " de " . $MONTHS[$dateArr[1]] . " del " . $dateArr[0];
    }

    public function buildProjectDate($dateStr): string {
        $MONTHS = ["01" => "enero", "02" => "febrero", "03" => "marzo", "04" => "abril", "05" => "mayo", "06" => "junio", "07" => "julio", 
        "08" => "agosto", "09" => "septiembre", "10" => "octubre", "11" => "noviembre", "12" => "diciembre"];

        $dateObj = new Carbon($dateStr);
        $dateFormatted = $dateObj->toDateTimeString();
        $dateTimeArr = explode(" ", $dateFormatted);

        $dateArr = explode('-', $dateTimeArr[0]);
        $monthName = $MONTHS[$dateArr[1]];

        $timeArr = explode(':', $dateTimeArr[1]);
        $hour = intval($timeArr[0]);
        $period = $hour < 12 ? 'a. m.' : 'p. m.';
        $hour = $hour > 12 ? $hour - 12 : $hour;
        $hourStr = $hour < 10 ? "0$hour" : "$hour";
        
        return "$dateArr[2] de $monthName $dateArr[0] $hourStr:$timeArr[1] $period";
    }
}