<?php

// custom konstanta aplikasi, prefix API_
define("API_DATA_NOT_FOUND", "Data tidak ditemukan");
define("API_DATA_CREATE_FAILED", "Gagal membuat data");
define("API_DATA_UPDATE_FAILED", "Gagal merubah data");
define("API_DATA_DELETE_FAILED", "Gagal menghapus data");
define("API_DATA_DELETE_REF_FAILED", "Tidak dapat menghapus referensi");
define("API_DATA_UPDATE_REF_FAILED", "Tidak dapat memperbaharui referensi");
define("API_DATA_NO_AUTH", "Authorisasi data ditolak");
define("API_DATA_APPROVE_FAILED", "Gagal Approve Order");

/**
 * Status True if reference exist
 */
function check_exist_reference($tables, $field_name, $id)
{
    $status = false;
    $tbl_name = "";
    $item_id = 0;

    foreach ($tables as $tbl) {
        $ref_exist = \Illuminate\Support\Facades\DB::table($tbl)->where($field_name, $id)->first();
        if ($ref_exist) {
            $status = true;
            $tbl_name = $tbl;
            $item_id = $ref_exist->id;
            break;
        }
    }

    return [
        'status' => $status,
        'tbl_name' => $tbl_name,
        'item_id' => $item_id
    ];
}

function cascade_delete($tables, $field_name, $id)
{
    foreach ($tables as $tbl) {
        \Illuminate\Support\Facades\DB::table($tbl)->where($field_name, $id)->delete();
    }
}

if (!function_exists('ddh')) {
    function ddh($var){
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: *');
        header('Access-Control-Allow-Headers: *');
        dd($var);
    }
}

/**
 * 
 * @param number $length
 * @param string $chars : 'alphanum', 'num' 
 * @return string
 */
function generateRandomString($length = 10, $chars = 'alphanum') {
    if ($chars == 'alphanum') {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    } else if ($chars == 'num') {
        $characters = '0123456789';
    } else {
        return "";
    }
    
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function createSlug($str, $delimiter = '-'){
    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    return $slug;
}

function adminKujangRequest($method, $requestUrl, $queryParams = [], $formParams = [], $hasFile = false)
{
    $client = new \GuzzleHttp\Client(['base_uri' => config('settings.admin_base_url')]);

    $credentials = base64_encode(config('settings.username').':'.config('settings.password'));
    $headersBasic = [
        'Authorization' => ['Basic '.$credentials]
    ];
    
    $bodyType = 'form_params';
    if ($hasFile) {
        $bodyType = 'multipart';
        $multipart = [];

        foreach ($formParams as $name => $contents) {
            $multipart[] = [
                'name' => $name,
                'contents' => $contents
            ];
        }
    }

    $response = $client->request($method, $requestUrl, [
            'headers' => $headersBasic,
            'query' => $queryParams,
            $bodyType => $hasFile ? $multipart : $formParams,
        ]);

    $response = $response->getBody();

    echo $response;    
}
