<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Http;

trait FileHelper
{

    /**
     * @return void
     * THIS USES SPATIE MEDIA-LIBRARY
     * THE MODEL MUST HAVE USED
     * 1. InteractsWithMedia
     *
     * THE MODEL MUST HAVE IMPLEMENTED
     * 2. HasMedia
     */
    public static function addMultipleFilesBase64(array $base64_files, Model $model,string $collection_name,string $disk = 'tenant'): void
    {
        if (is_array($base64_files) && !empty($base64_files)) {
            foreach ($base64_files as $key => $data) {
                $media = $model->addMediaFromBase64($data)->toMediaCollection($collection_name, $disk);

                $media->uploaded_by = tenant_user()->id;
                $media->save();
            }
        }
    }

    public static function formatFileSize($sizeInBytes): string
    {
        if ($sizeInBytes < 1024) {
            return $sizeInBytes . ' B';
        } elseif ($sizeInBytes < 1024 * 1024) {
            return round($sizeInBytes / 1024, 2) . ' KB';
        } elseif ($sizeInBytes < 1024 * 1024 * 1024) {
            return round($sizeInBytes / (1024 * 1024), 2) . ' MB';
        } elseif ($sizeInBytes < 1024 * 1024 * 1024 * 1024) {
            return round($sizeInBytes / (1024 * 1024 * 1024), 2) . ' GB';
        } elseif ($sizeInBytes < 1024 * 1024 * 1024 * 1024 * 1024) {
            return round($sizeInBytes / (1024 * 1024 * 1024 * 1024), 2) . ' TB';
        } else {
            return round($sizeInBytes / (1024 * 1024 * 1024 * 1024 * 1024), 2) . ' PB';
        }
    }



    public static function numOnly($input) {
        return preg_replace('/[^0-9]/','', $input);
    }

    public static function generateIdNumber($input, $pad_len = 5, $prefix = null) {
        if(strlen($input) > $pad_len)
            $pad_len = strlen($input);

        if (is_string($prefix))
            return sprintf("%s%s", $prefix, str_pad($input, $pad_len, "0", STR_PAD_LEFT));

        return str_pad($input, $pad_len, "0", STR_PAD_LEFT);
    }

    public static function clean($string) {
        $string = str_replace(' ', '_', $string); // Replaces all spaces with hyphens.

        return preg_replace('/[^A-Za-z0-9_\-]/', '', strtolower($string)); // Removes special chars.
    }

    public static function validEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    }

    public static function getVendorByPrefix($number) {

        if(str_starts_with($number, "233")){

            $number = '0'.substr($number, 3);

            if(str_starts_with($number, "020") || str_starts_with($number, "050"))
                return "vodafone";

            if(str_starts_with($number, "024") || str_starts_with($number, "054") || str_starts_with($number, "055") || str_starts_with($number, "059"))
                return "mtn";

            if(str_starts_with($number, "027") || str_starts_with($number, "057") || str_starts_with($number, "026"))
                return "airteltigo";
        }

        if(str_starts_with($number, "020") || str_starts_with($number, "050"))
            return "vodafone";

        if(str_starts_with($number, "024") || str_starts_with($number, "054") || str_starts_with($number, "055") || str_starts_with($number, "059"))
            return "mtn";

        if(str_starts_with($number, "027") || str_starts_with($number, "057") || str_starts_with($number, "026"))
            return "airteltigo";

        return "na";
    }

    public static function sendSMS($msisdn, $message)
    {
        return [];
    }

    public static function sendEmail($msisdn, $message)
    {
        $username = env('SMS_USERNAME');
        $password = env('SMS_PASSWORD');
        $source = env('SMS_SOURCE');
        $msisdn = '233'.substr($msisdn, -9);

        $data = [
            'username' => $username,
            'password' => $password,
            'source' => $source,
            'destination' => $msisdn,
            'message' => $message,
            'ol' => 'false',
        ];

        return Http::withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ])->post('https://deywuro.com/api/sms', $data);
    }

    public static function sendOTP($type, $msisdn, $message)
    {
        if($type == 'sms') return self::sendSMS($msisdn, $message);

        return self::sendEmail($msisdn, $message);
    }

    public static function fileToDataUrl($file){
        // Specify the path to the file
        $file_path = $file->getRealPath();

        // Read the file contents
        $file_data = file_get_contents($file_path);

        // Encode the file contents
        $base64_data = base64_encode($file_data);

        // Determine the MIME type of the file
        $file_info = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($file_info, $file_path);

        // Create the data URL
        return 'data:' . $mime_type . ';base64,' . $base64_data;
    }

    public static function dataUrlToFile($data){
        // Extract the file extension and data from the data URL
        $data = explode(',', $data);
        $fileExtension = '';

        if (count($data) === 2) {
            $mimeData = explode(';', $data[0]);
            $fileMimeType = isset($mimeData[0]) ? $mimeData[0] : '';
            $fileExtension = explode('/', $fileMimeType)[1];
        }

        // Decode the base64-encoded data
        return base64_decode($data[1]);
    }

    public static function fileIsExtension($fileName, $ext){
        $extension = pathinfo($fileName, PATHINFO_EXTENSION);
        return strtolower($extension) === $ext;
    }
}
