<?php

use App\Models\AppSetting;
use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

function auth_upload_image($file, $field, $id)
{
    $destinationPath = './uploads';
    $extension = $file->getClientOriginalExtension();
    $fileName = Str::uuid() . '.' . $extension;
    $file->move($destinationPath, $fileName);

    $image = User::find($id);
    $image->$field = $fileName;
    $image->save();
}

function successResponse($code, $data = [], $message = '', $httpCode = 200)
{
    $response = json_encode([
        'statusCode' => $code,
        'status' => $code == 200 ? true : false,
        'data' => (!empty($data)) ? $data  : (object)$data,
        'message' => $message
    ]);

    return response($response, $httpCode);
}

function pre($data)
{
    echo "<pre>";
    print_r($data);
    exit;
}

function mailTo($useremail)
{
    $to = $useremail;
    $subject = 'Please verify your email with OTP given below';

    $otp = rand(1000, 9999);
    try {
        $status = Mail::send('mailformate', ['otp' => $otp], function ($email) use ($to, $subject) {
            $email->to($to)
                ->subject($subject);
        });
        return ['otp' => $otp, 'status' => $status];
    } catch (\Exception $e) {
        return ['otp' => $otp, 'status' => true];
    }
}

function from_camel_case($str)
{
    $i = array("-", "_");
    $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
    $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
    $str = str_replace($i, ' ', $str);
    $str = str_replace(' ', '', ucwords(strtolower($str)));
    $str = strtolower(substr($str, 0, 1)) . substr($str, 1);
    return $str;
}

function checkIfAuthorized($request)
{

    Log::info("------- authHeader ----------" . json_encode($request->bearerToken()));

    $jwtToken = $request->bearerToken();

    try {
        if (!empty($jwtToken)) {
            $decoded = JWT::decode($jwtToken, new Key(JWT_KEY, JWT_ALGO));
            $userData = (array) $decoded;
            return $userData;
        }
    } catch (Exception $e) {
        return false;
    }
}

function background_process($param)
{
    $getApiKey = AppSetting::getAppSetting('api_key');

    $url = url('/') . "/$getApiKey/send_email_notification";

    $post_string = http_build_query($param);
    $parts = parse_url($url);

    $errno = 0;
    $errstr = "";
    $IS_LIVE = 0;
    $fp = null;

    $host = $parts['host'];
    $path = $parts['path'];

    if (env('APP_ENV') != "local") {
        //Use SSL & port 443 for secure servers
        //Use otherwise for localhost and non-secure servers
        //For secure server
        $fp = fsockopen('ssl://' . $host, isset($parts['port']) ? $parts['port'] : 443, $errno, $errstr, 30);
    } else {
        //For localhost and un-secure server
        $fp = fsockopen($host, isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30);
    }
    $out = "POST " . $path . " HTTP/1.1\r\n";
    $out .= "Host: " . $host . "\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= "Content-Length: " . strlen($post_string) . "\r\n";
    $out .= "Connection: Close\r\n\r\n";
    if (isset($post_string)) {
        $out .= $post_string;
    }
    fwrite($fp, $out);
    fclose($fp);
}

function compressImage($source, $destination, $max_size, $quality)
{
    $imageInfo = getimagesize($source);
    $mime = $imageInfo['mime'];

    switch ($mime) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($source);
            break;
        case 'image/png':
            $image = imagecreatefrompng($source);
            imagealphablending($image, true);
            imagesavealpha($image, true);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($source);
            break;
        default:
            die('Unsupported image type');
    }

    do {
        ob_start();
        imagejpeg($image, null, $quality);
        $imageData = ob_get_clean();
        $fileSize = strlen($imageData);

        if ($fileSize <= $max_size || $quality <= 10) {
            file_put_contents($destination, $imageData);
            break;
        }

        $quality -= 5;
    } while ($fileSize > $max_size);

    imagedestroy($image);
}
