<?php

function show_file($filename)
{
    helper('filesystem');
    $path = WRITEPATH . 'uploads/';

    $fullpath = $path . $filename;
    $file     = new CodeIgniter\Files\File($fullpath, true);
    $binary   = readfile($fullpath);

    return $this->response
        ->setHeader('Content-Type', $file->getMimeType())
        ->setHeader('Content-disposition', 'inline; filename="' . $file->getBasename() . '"')
        ->setStatusCode(200)
        ->setBody($binary);
}

function encrypt_url($string)
{
    $output         = false;
    $secret_key     = 'O6b3EnwFkhWdFvKu'; // 16 digits
    $secret_iv      = 'xyvTC84fm8JCgfge'; // 16 digits
    $encrypt_method = 'aes-256-cbc';
    $key            = hash('sha256', $secret_key);
    $iv             = substr(hash('sha256', $secret_iv), 0, 16);
    $result         = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);

    return base64_encode($result);
}

function decrypt_url($string)
{
    $output         = false;
    $secret_key     = 'O6b3EnwFkhWdFvKu'; // 16 digits
    $secret_iv      = 'xyvTC84fm8JCgfge'; // 16 digits
    $encrypt_method = 'aes-256-cbc';
    $key            = hash('sha256', $secret_key);
    $iv             = substr(hash('sha256', $secret_iv), 0, 16);

    return openssl_decrypt(base64_decode($string, true), $encrypt_method, $key, 0, $iv);
}

function multi_sort($sort, $order)
{
    $sorts  = explode(',', $sort);
    $orders = explode(',', $order);
    $aa     = [];

    foreach ($sorts as $index => $s) {
        $o    = $orders[$index];
        $aa[] = "{$s} {$o}";
    }

    return implode(',', $aa);
}

function delete_older_than($dir, $max_age)
{
    $list = [];

    $limit = time() - $max_age;

    $dir = realpath($dir);

    if (! is_dir($dir)) {
        return;
    }

    $dh = opendir($dir);
    if ($dh === false) {
        return;
    }

    while (($file = readdir($dh)) !== false) {
        $file = $dir . '/' . $file;
        if (! is_file($file)) {
            continue;
        }

        if (filemtime($file) < $limit) {
            $list[] = $file;
            if (basename($file) !== 'index.html') {
                unlink($file);
            }
        }
    }
    closedir($dh);

    return $list;
}

function tgl_sql($tgl)
{
    // dd-mm-yyyy menjadi yyyy-mm-dd
    if ($tgl === '00-00-0000') {
        return '';
    }
    if ($tgl === '') {
        return '';
    }

    return substr($tgl, 6, 4) . '-' . substr($tgl, 3, 2) . '-' . substr($tgl, 0, 2);
}

function tgl_view($tgl)
{
    // yyyy-mm-dd menjadi dd-mm-yyyy
    if ($tgl === '0000-00-00') {
        return '';
    }
    if ($tgl === '') {
        return '';
    }

    return substr($tgl, 8, 2) . '-' . substr($tgl, 5, 2) . '-' . substr($tgl, 0, 4);
}

function timestamp()
{
    return date('Y-m-d H:i:s');
}

function dtm_indo($dtm)
{
    $x1 = explode(' ', $dtm);
    $x2 = explode('-', $x1[0]);
    $x3 = $x2[2].'-'.$x2[1].'-'.$x2[0].' '.$x1[1];

    return $x3;
}

function sensor_phone($target)
{
    $count = strlen($target) - 4;
    $output = substr_replace($target, str_repeat('*', $count), 0, $count);
    return $output;
}

function send_wax($nomor, $pesan)
{
    $client = \Config\Services::curlrequest();
    
    // Mengambil data dari .env file
    $url = env('wa.send', 'https://app.saungwa.com/api/create-message');
    $appkey = env('app.key', '');
    $authkey = env('wa.key', '');
    
    // Memastikan nomor diawali dengan kode negara dan tidak mengandung karakter khusus
    $nomor = preg_replace('/[^0-9]/', '', $nomor);
    if (substr($nomor, 0, 1) == '0') {
        $nomor = '62' . substr($nomor, 1);
    }
    
    // Menggunakan form_params alih-alih multipart
    $res = $client->request('POST', $url, [
        'verify' => false,
        'form_params' => [
            'appkey' => $appkey,
            'authkey' => $authkey,
            'to' => $nomor,
            'message' => $pesan,
            'sandbox' => 'false'
        ]
    ]);
    
    return json_decode($res->getBody(), true);
}

//13-11-2024
//fungsi generate link utk privilege modul
function genlinks($modul, $menu) {
    // Deklarasi array untuk menyimpan link dan status rekam, ubah, hapus
    $result = [
        'rekam' => ['status' => 0, 'link' => ''],
        'ubah' => ['status' => 0, 'link' => ''],
        'hapus' => ['status' => 0, 'link' => ''],
    ];

    // Logika untuk rekam
    if (priv_menu($menu, 'rekam')) {
        $result['rekam']['status'] = 1;
        $result['rekam']['link'] = base_url("{$modul}/{$menu}/new");
    }

    // Logika untuk ubah
    if (priv_menu($menu, 'ubah')) {
        $result['ubah']['status'] = 1;
        $result['ubah']['link'] = base_url("{$modul}/{$menu}/edit/");
    }

    // Logika untuk hapus
    if (priv_menu($menu, 'hapus')) {
        $result['hapus']['status'] = 1;
        $result['hapus']['link'] = base_url("{$modul}/{$menu}/delete");
    }

    return $result;
}

function generateFilename($jenis, $judul)
    {
        // Mengubah judul menjadi huruf kecil
        $judul = strtolower($judul);
        
        // Menghapus karakter khusus dan mengganti spasi dengan underscore
        $judul = preg_replace('/[^a-z0-9\s-]/', '', $judul); // Hapus karakter khusus
        $judul = preg_replace('/[\s-]+/', '_', $judul);      // Ganti spasi dan dash dengan underscore
        $judul = trim($judul, '_');                          // Hapus underscore di awal dan akhir
        
        // Batasi panjang judul (opsional)
        $judul = substr($judul, 0, 50);
        
        // Tambahkan timestamp untuk memastikan keunikan
        $ts = str_replace(['-', ':', ' '], '', date('Y-m-d H:i:s'));
        
        // Gabungkan judul dan timestamp
        $filename = $jenis.$judul . '_' . $ts;
        
        return $filename;
    }