<?php

use App\Core\Helper\LanguageService;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\App;
use Laravel\Lumen\Bus\PendingDispatch;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Laravel\Lumen\Http\ResponseFactory;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Illuminate\Contracts\Broadcasting\Factory as BroadcastFactory;
use Illuminate\Support\Str;


function output($param)
{

    $statusArr = [1 => "success", -1 => "exception", 0 => "error"];
    $exceptionClassArr = ["exception" => "\Exception", "error" => "App\Exceptions\ApiErrorException"];
    $statusCodeArr = [1 => 200, -1 => 500, 0 => 400];
    $param["status"] = isset($param["status"]) ? $param["status"] : 1;
    $status = isset($statusArr[$param["status"]]) ? $statusArr[$param["status"]] : "success";
    $statusCode = isset($statusCodeArr[$param["status"]]) ? $statusCodeArr[$param["status"]] : 200;
    $message = (isset($param['message']) ? $param['message'] : '');
    $data = (isset($param['data']) ? $param['data'] : '');
    $exceptionClass = isset($exceptionClassArr[$status]) ? new $exceptionClassArr[$status]($message) : null;

    return ['status' => $status, 'message' => $message, 'data' => $data, 'statusCode' => $statusCode, "exceptionClass" => $exceptionClass];
}

function apiResponse($status = -1, $message = "", $data = [], $statusCode = null, $errorCode = null)
{
    $genericMessage = "Bilinmeyen Bir Hata Oluştu";
    $error = $status <= 0 ? true : false;
    $statusCode = $statusCode ? $statusCode : 200;
    $errorCode = $errorCode ? $errorCode : null;
    //$statusCode = $error ? 500 : $statusCode;
    $message = $status != -1 ? $message : $genericMessage;
    $message = $message ? $message : null;
    $data = $data && is_array($data) ? $data : [];

    $responseData = [
        "status" => $statusCode,
        "error" => $error,
        "errorCode" => $errorCode,
        "message" => $message,
        "data" => $data
    ];

    /** ServiceLog **/
    $serviceLogId = app('request')->serviceLogId;
    $serviceLogRequestTime = app('request')->serviceLogRequestTime;
    if (!empty($serviceLogId)) {
        $updateServiceLog = [
            'response' => json_encode($responseData),
            'response_time' => microtime(true) - $serviceLogRequestTime,
            'status' => 1
        ];
        $serviceLog = App::make("App\Core\Service\ServiceLogService");
        $serviceLog->update($serviceLogId, $updateServiceLog);
    }
    /** ServiceLog **/

    return response()->json($responseData, $statusCode);
}

function fillOnUndefined($variable, $index = null, $fillWith = null, $arrayDelimiter = ".")
{
    if (!$arrayDelimiter) {
        return null;
    }


    if (!$index && $index !== '0' && $index !== 0) {
        return false;
    }

    $indexes = explode($arrayDelimiter, $index);

    $arrayDeep = $variable;

    foreach ($indexes as $perIndex) {
        if (!isset($arrayDeep[$perIndex])) {
            return $fillWith;
        }

        $arrayDeep = $arrayDeep[$perIndex];
    }


    return $arrayDeep;

}

function fillOnUndefinedAndEmpty($variable, $index = null, $fillWith = null, $arrayDelimiter = ".")
{
    if (!$arrayDelimiter) {
        return null;
    }


    if (!$index && $index !== '' && $index !== '0' && $index !== 0) {
        return false;
    }

    $indexes = explode($arrayDelimiter, $index);

    $arrayDeep = $variable;

    foreach ($indexes as $perIndex) {
        if (!isset($arrayDeep[$perIndex]) || empty($arrayDeep[$perIndex])) {
            return $fillWith;
        }

        $arrayDeep = $arrayDeep[$perIndex];
    }


    return $arrayDeep;

}

function createFolderAndSubFolder($structure, $path = __DIR__, &$createdPaths, $mode = 0777)
{

    foreach ($structure as $folder => $subFolder) {
        if (is_array($subFolder)) {
            $newPath = "{$path}/{$folder}";
            //$createdPaths[$newPath] = $newPath;
            $createdPaths[] = $newPath;

            if (!is_dir($newPath)) mkdir($newPath, $mode);

            createFolderAndSubFolder($subFolder, $newPath, $createdPaths);
        } else {
            $newPath = "{$path}/{$subFolder}";
            //$createdPaths[$newPath] = $newPath;
            $createdPaths[] = $newPath;
            if (!is_dir($newPath)) mkdir($newPath, $mode);
        }
    }

    return $createdPaths;
}

function smartyModifierFileSize($size)
{
    $size = max(0, (int)$size);
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $power = $size > 0 ? floor(log($size, 1024)) : 0;
    $convertSize = number_format($size / pow(1024, $power), 2, '.', ',');
    $convertType = $units[$power];
    return [$convertSize, $convertType];
}

function pickItemFromArray($index, array $targetArray)
{
    try {
        $result = [];
        foreach ($targetArray as $perIndex => $perValue) {
            if (isset($perValue[$index])) {
                $result[] = $perValue[$index];
            }

        }
        return $result;
    } catch (Exception $e) {
        return [];
    }
}

function lang($word, array $parameters = [], $lang = null)
{
    return LanguageService::lang($word, $parameters, $lang);
}

function getSystemLang()
{
    return LanguageService::getCurrentLang();
}

function getSystemLangSession()
{
    return session("sysLang");
}

function setSystemLangSession($language)
{
    $validLanguages = LanguageService::getValidLanguages();
    if (!in_array($language, $validLanguages)) {
        throw new Exception("Invalid Language Selected language parameter : " . json_encode($language));
    }
    session()->set("sysLang", $language);
    return $language;
}

function getSystemDefaultLang()
{
    return LanguageService::getDefaultLang();
}

function getLanguageSupportList()
{
    return LanguageService::getLanguageSupportList();
}

function upperCase($word, $charset = "UTF-8")
{
    $word = str_replace("i", "İ", $word);
    return mb_strtoupper($word, $charset);
}

function lowerCase($word, $charset = "UTF-8")
{
    $word = str_replace("I", "ı", $word);
    return mb_strtolower($word, $charset);
}

function uCase($word, $charset = "UTF-8")
{
    $word = preg_replace("#(^\i)#", "İ", $word);
    $word = preg_replace("#(^\ı)#", "I", $word);
    return mb_convert_case($word, MB_CASE_TITLE, $charset);
}

function reIndexArrayKeys(array $targetArray, $startNo = 0)
{
    if (!$targetArray) {
        return [];
    }
    return array_combine(range($startNo, ($startNo - 1) + count($targetArray)), $targetArray);
}

function singleElementXMLArray($array = [])
{

    return fillOnUndefined($array, 0) && is_array($array) ? $array : [$array];
}

function toArray($value): array
{
    return is_array($value) ? $value : ($value !== null ? [$value] : []);
}


function singleElementArray($arrayElement, array $extraParams = null)
{

    $isMultiArray = true;

    if (!is_array($arrayElement)) {
        return [];
    }

    foreach ($arrayElement as $perItem) {
        if (gettype($perItem) != "array") {
            $isMultiArray = false;
            break;
        }
    }

    if (!$isMultiArray) {
        $isMultiArray = true;
        foreach (array_keys($arrayElement) as $perKey) {
            if (!is_numeric($perKey)) {
                $isMultiArray = false;
                break;
            }
        }
    }


    return $isMultiArray ? $arrayElement : array($arrayElement);

}

function generateRandomString($length = 5)
{
    return \App\Core\Helper\PhpHelper::generateRandomString($length);
}

function humanReadableDate($date)
{
    return date('d/m/Y', strtotime($date));
}

function language_key($title)
{
    return Str::slug($title, $separator = '_', $language = 'en');
}

function getGuid()
{
    $hash = md5(uniqid());
    $guid = substr($hash, 0, 8) .
        '-' .
        substr($hash, 8, 4) .
        '-' .
        substr($hash, 12, 4) .
        '-' .
        substr($hash, 16, 4) .
        '-' .
        substr($hash, 20, 12);

    return $guid;
}

function moneyDoubleFormat($money)
{
    return number_format($money, 2, ',', '');
}


function moneyDoubleFormatDecimal($money)
{
    return floatval(number_format($money, 2, '.', ''));
}

function moneyFourFormatDecimal($money)
{
    return floatval(number_format($money, 4, '.', ''));
}


function getCodeGenerate($prefix = 'ENW')
{
    return $prefix . date('ymd') . '-' . upperCase(generateRandomString(8));
}

function getPaymentGenerate($prefix = 'PYM')
{
    $prefix = is_null($prefix) ? 'PYM' : $prefix;
    return 'ENW' . $prefix . date('ymd') . '_' . upperCase(generateRandomString(8));
}

function getTicketCodeGenerate($prefix = 'TCK')
{
    return $prefix . upperCase(generateRandomString(8));
}

function creditCardMask($cardNumber)
{
    return substr($cardNumber, 0, 6) . '******' . substr($cardNumber, -4);
}

function occupancyCodeFormatted($occupancyCode)
{

    $occupancyFormatted = [];

    $adultCount = substr_count($occupancyCode, 'A');
    if ($adultCount > 0) {
        $occupancyFormatted[] = $adultCount . ' Adult';
    }

    $childCount = substr_count($occupancyCode, 'C');
    if ($childCount > 0) {

        $childAges = [];
        $roomsChildArray = explode('C', $occupancyCode);
        for ($i = 1; $i < count($roomsChildArray); $i++) {
            if (!empty($roomsChildArray[$i]) || $roomsChildArray[$i] == 0) {
                $childAges[] = $roomsChildArray[$i];
            }
        }

        if (!empty($childAges)) {
            $childAges = implode(', ', $childAges);
        }

        $occupancyFormatted[] = $childCount . ' Child' . (!empty($childAges) ? ' (' . $childAges . ')' : null);
    }

    if (!empty($occupancyFormatted)) {
        $occupancyFormatted = implode(', ', $occupancyFormatted);
    }

    return $occupancyFormatted;
}

function occupancyCodeParser($occupancyCode)
{

    $occupancy = [];
    $occupancy['ADT'] = 0;
    $occupancy['CHD'] = 0;
    $occupancy['AGE'] = [];

    $adultCount = substr_count($occupancyCode, 'A');
    if ($adultCount > 0) {
        $occupancy['ADT'] = $adultCount;
    }

    $childCount = substr_count($occupancyCode, 'C');
    if ($childCount > 0) {

        $childAges = [];
        $roomsChildArray = explode('C', $occupancyCode);
        for ($i = 1; $i < count($roomsChildArray); $i++) {
            if (!empty($roomsChildArray[$i])) {
                $childAges[] = $roomsChildArray[$i];
            }
        }

        $occupancy['CHD'] = $childCount;
        $occupancy['AGE'] = $childAges;

        //$occupancyFormatted[] = $childCount . ' Child' . (!empty($childAges) ? ' (' . $childAges . ')' : null);
    }

    return $occupancy;
}


function occupancyGroup($maxAdult, $maxChild, $maxOccupancy, $excludeOccupancy = [])
{

    $occupancyGroup = [];
    //TODO: $excludeOccupancy
    for ($i = 0; $i < $maxAdult; $i++) {
        $occupancyCodeAdult = str_repeat('A', ($i + 1));
        if (strlen($occupancyCodeAdult) > $maxOccupancy) {
            break;
        }
        $occupancyGroup[] = $occupancyCodeAdult;

        for ($j = 0; $j < $maxChild; $j++) {
            $occupancyCodeChild = str_repeat('C', ($j + 1));

            if (strlen($occupancyCodeChild) > $maxOccupancy) {
                continue;
            }

            if (strlen($occupancyCodeAdult . $occupancyCodeChild) > $maxOccupancy) {
                break;
            }

            $occupancyGroup[] = $occupancyCodeAdult . $occupancyCodeChild;
        }
    }

    return $occupancyGroup;
}


function cancellationPolicyTextFormatted($isNonRefundable, $isFreeCancellation, $beforeArrivalDay, $type, $value, $currency, $languageCode = 'en')
{

    $formattedText = null;
    if (!$isFreeCancellation) {
        if ($isNonRefundable) {
            $formattedText = __('btn-irrevocable', [], $languageCode);
        } else {

            $formattedText = __('be-if_canceled_up_to_days', ['day' => $beforeArrivalDay], $languageCode) . ', ' . $value . ($type == 'PER' ? '%' : $currency) . ' ' . __('be-search-impose_penalty', [], $languageCode);
        }
    } else {
        $formattedText = ($beforeArrivalDay > 0 ? __('be-up_to_days', ['day' => $beforeArrivalDay], $languageCode) : '') . ' ' . __('btn-free_cancellation', [], $languageCode);
    }

    return $formattedText;

}
