<?php

namespace App\Models;

use DateTime;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Mail;
use Exception;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;

use function PHPSTORM_META\type;

class Common extends Model
{
    public $folder_story = "story";

    // Image Functions
    public function saveImage($org_name, $folder, $prefix = "")
    {
        try {

            $img_ext = $org_name->getClientOriginalExtension();
            $filename = $prefix . date('d_m_Y_') . rand(1111, 9999) . '.' . $img_ext;
            $org_name->move(base_path('storage/app/public/' . $folder), $filename);
            return $filename;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function imageNameToUrl($array, $column, $folder)
    {
        try {

            foreach ($array as $key => $value) {

                $appName = Config::get('app.image_url');

                if (isset($value[$column]) && $value[$column] != "") {

                    if ($folder == "user") {

                        if (Storage::disk('public')->exists($folder . '/' . $value[$column])) {
                            $value[$column] = $appName . $folder . '/' . $value[$column];
                        } else {
                            $value[$column] = asset('assets/imgs/default.png');
                        }
                    } else {

                        if (Storage::disk('public')->exists($folder . '/' . $value[$column])) {
                            $value[$column] = $appName . $folder . '/' . $value[$column];
                        } else {
                            $value[$column] = asset('assets/imgs/no_img.png');
                        }
                    }
                } else {
                    if ($folder == "user") {
                        $value[$column] = asset('assets/imgs/default.png');
                    } else {
                        $value[$column] = asset('assets/imgs/no_img.png');
                    }
                }
            }
            return $array;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function videoNameToUrl($array, $column, $folder)
    {
        try {

            foreach ($array as $key => $value) {

                $appName = Config::get('app.image_url');

                if (isset($value[$column]) && $value[$column] != "") {

                    if (Storage::disk('public')->exists($folder . '/' . $value[$column])) {
                        $value[$column] = $appName . $folder . '/' . $value[$column];
                    } else {
                        $value[$column] = "";
                    }
                } else {

                    $value[$column] = "";
                }
            }
            return $array;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function getImage($folder = "", $name = "")
    {
        try {

            $appName = Config::get('app.image_url');

            if ($folder != "" && $name != "") {
                if ($folder == "user") {

                    if (Storage::disk('public')->exists($folder . '/' . $name)) {
                        $name = $appName . $folder . '/' . $name;
                    } else {
                        $name = asset('assets/imgs/default.png');
                    }
                } else {

                    if (Storage::disk('public')->exists($folder . '/' . $name)) {
                        $name = $appName . $folder . '/' . $name;
                    } else {
                        $name = asset('assets/imgs/no_img.png');
                    }
                }
            } else {
                if ($folder == "user") {
                    $name = asset('assets/imgs/default.png');
                } else {
                    $name = asset('assets/imgs/no_img.png');
                }
            }
            return $name;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function getVideo($folder = "", $name = "")
    {
        try {

            $appName = Config::get('app.image_url');

            if ($folder != "" && $name != "") {
                if (Storage::disk('public')->exists($folder . '/' . $name)) {
                    $name = $appName . $folder . '/' . $name;
                } else {
                    $name = "";
                }
            } else {
                $name = "";
            }
            return $name;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function deleteImageToFolder($folder, $name)
    {
        try {

            Storage::disk('public')->delete($folder . '/' . $name);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    // Common Functions
    public function user_name($string)
    {
        $rand_number = rand(0, 1000);
        $user_name = '@' . $string . $rand_number;

        $check = User::where('user_name', $user_name)->first();
        if (isset($check) && $check != null) {
            $this->user_name($string);
        }
        return $user_name;
    }
    public function user_tag_line()
    {
        $setting = $this->Setting_Data();

        if (isset($setting) && $setting['app_name'] == "") {
            $bio_data = "Hey I am using the " . env('APP_NAME') . " App.";
        } else {
            $bio_data = "Hey I am using the " . $setting['app_name'] . " App.";
        }
        return $bio_data;
    }
    public function is_any_package_buy($user_id, $to_user_id)
    {
        $this->package_expiry();

        $is_buy = Creator_Package_Transaction::where('user_id', $user_id)->where('to_user_id', $to_user_id)->where('status', 1)->first();
        if (!empty($is_buy)) {
            return 1;
        } else {
            return 0;
        }
    }
    // public function subscription_expiry()
    // {
    //     $expiry = Wallet_Transaction::where('type', 3)->where('status', 1)->get();

    //     for ($i = 0; $i < count($expiry); $i++) {
    //         if ($expiry[$i]['expiry_date'] < date('Y-m-d')) {
    //             $expiry[$i]['status'] = 0;
    //             $expiry[$i]->save();
    //         }
    //     }

    //     return true;
    // }
    // public function is_subscribe($user_id, $to_user_id)
    // {
    //     $this->subscription_expiry();

    //     $is_buy = Wallet_Transaction::where('type', 3)->where('user_id', $user_id)->where('to_user_id', $to_user_id)->where('status', 1)->first();
    //     if (!empty($is_buy)) {
    //         return 1;
    //     } else {
    //         return 0;
    //     }
    // }
    public function Setting_Data()
    {
        $setting = General_Setting::get();
        $data = [];
        foreach ($setting as $value) {
            $data[$value->key] = $value->value;
        }
        return $data;
    }
    // public function getFollowingUserList($user_id)
    // {
    //     $data = Follow::where('user_id', $user_id)->latest()->get();
    //     $user_data = array();
    //     foreach ($data as $key => $value) {
    //         $user_data[] = $value->to_user_id;
    //     }
    //     return $user_data;
    // }
    public function get_all_count_for_post($array, $user_id)
    {

        // Comment
        $array['total_comment'] = Comment::where('post_id', $array['id'])->count();

        // Like
        $array['total_like'] = Like::where('post_id', $array['id'])->where('status', 1)->count();

        $is_like = Like::where('post_id', $array['id'])->where('user_id', $user_id)->where('status', 1)->first();
        $array['is_like'] = 0;
        if ($is_like) {
            $array['is_like'] = 1;
        }

        // // Follow
        // $array['is_follow'] = 0;
        // if ($user_id > 0 && $array['user_id'] > 0) {

        //     $is_favorite = Follow::where('user_id', $user_id)->where('to_user_id', $array['user_id'])->first();
        //     if ($is_favorite) {
        //         $array['is_follow'] = 1;
        //     }
        // }

        return $array;
    }
    // public function is_follow($user_id, $to_user_id)
    // {
    //     try {
    //         $is_follow = Follow::where('user_id', $user_id)->where('to_user_id', $to_user_id)->where('status', 1)->first();

    //         if (isset($is_follow['id'])) {
    //             return 1;
    //         } else {
    //             return 0;
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    // public function follow($user_id, $to_user_id)
    // {
    //     try {

    //         if ($user_id != $to_user_id) {
    //             $where = [
    //                 ['user_id', $to_user_id],
    //             ];
    //         } else {
    //             $where = [
    //                 ['user_id', $user_id],
    //             ];
    //         }

    //         $is_follow = Follow::where($where)->count();
    //         return (int) $is_follow;
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    // public function following($user_id, $to_user_id)
    // {
    //     try {
    //         if ($user_id != $to_user_id) {
    //             $where = [
    //                 ['to_user_id', $to_user_id],
    //             ];
    //         } else {
    //             $where = [
    //                 ['to_user_id', $user_id],
    //             ];
    //         }

    //         $following = Follow::where($where)->count();
    //         return (int) $following;
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    public function is_package_buy($user_id, $package_id)
    {
        $is_buy = Creator_Package_Transaction::where('user_id', $user_id)->where('creator_package_id', $package_id)->where('status', 1)->first();
        if (!empty($is_buy)) {
            return 1;
        } else {
            return 0;
        }
    }
    public function get_block_user($user_id)
    {
        $data = User_Block::where('user_id', $user_id)->where('status', 1)->get();

        $user_data = array();
        foreach ($data as $key => $value) {
            $user_data[] = $value->block_user_id;
        }
        return $user_data;
    }
    public function package_expiry()
    {

        $all_data = Creator_Package_Transaction::where('status', 1)->get();

        for ($i = 0; $i < count($all_data); $i++) {

            if ($all_data[$i]['expiry_date'] <= date("Y-m-d")) {
                $all_data[$i]->status = 0;
                $all_data[$i]->save();
            }
        }

        return true;
    }
    public function checkHashTag($hashTag)
    {
        try {

            if (strpos($hashTag, '#') !== false) {

                $remove = substr($hashTag, strpos($hashTag, '#'));
                $tag = explode('#', $remove);

                $id = [];
                if (count($tag) > 0) {
                    foreach ($tag as $key => $value) {

                        if ($value && $value != "") {

                            $value = ltrim($value);
                            $tag = explode(' ', $value)[0];

                            $row = Hashtag::where('name', 'like', '%' . $tag . '%')->first();
                            if (isset($row->id)) {
                                $id[] = $row->id;

                                $row->increment('total_used_hashtag', 1);
                            } else {
                                $data['name'] = $tag;
                                $data['image'] = '';
                                $data['total_used_hashtag'] = 1;

                                $hashtag_id = Hashtag::insertGetId($data);
                                $id[] = $hashtag_id;
                            }
                        }
                    }
                    return $id;
                }
            } else {
                return array();
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    // public function Update_Earning_Point($user_id, $type)
    // {
    //     try {

    //         $user = User::where('id', $user_id)->first();
    //         $earn_point_setting = Earn_Point_Setting::where('type', $type)->first();
    //         $user_point = 0;

    //         if (isset($user) && $user != null && $earn_point_setting != null && isset($earn_point_setting)) {

    //             $inset['user_id'] = $user_id;
    //             $inset['point'] = $earn_point_setting->value;
    //             $inset['type'] = $type;
    //             if ($type == 1) {
    //                 $inset['reason'] = 'Registration Point';
    //             } elseif ($type == 2) {
    //                 $inset['reason'] = 'Comment Point';
    //             } elseif ($type == 3) {
    //                 $inset['reason'] = 'Like Point';
    //             } elseif ($type == 4) {
    //                 $inset['reason'] = 'Follow Point';
    //             } elseif ($type == 5) {
    //                 $inset['reason'] = 'Following Point';
    //             } elseif ($type == 6) {
    //                 $inset['reason'] = 'Post Upload Point';
    //             } elseif ($type == 7) {
    //                 $inset['reason'] = 'Package Buy Point';
    //             } elseif ($type == 8) {
    //                 $inset['reason'] = 'Become Creator Point';
    //             } else {
    //                 $inset['reason'] = "";
    //             }
    //             $inset['status'] = 0;

    //             Earn_Point::insert($inset);
    //             User::where('id', $user_id)->increment('total_points', $earn_point_setting->value);

    //             $user_point = $user->total_points + $earn_point_setting->value;
    //         }
    //         return $user_point;
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    public function setemailconfig()
    {
        $smtp = Smtp::first();
        if (isset($smtp) && $smtp != null && $smtp != false) {
            $data = [
                'driver' => 'smtp',
                'host' => $smtp->host,
                'port' => $smtp->port,
                'encryption' => 'tls',
                'username' => $smtp->user,
                'password' => $smtp->pass,
                'from' => [
                    'address' => $smtp->from_email,
                    'name' => env('APP_NAME'),
                ]
            ];
            Config::set('mail', $data);
        }
    }
    function Send_Mail($type, $email, $creator = []) // Type = 1- Register Mail, 2 Transaction Mail
    {
        try {
            $this->setemailconfig();

            $smtp = Smtp_Data();
            if (isset($smtp) && $smtp != false && $smtp['status'] == 1) {

                if ($type == 1) {
                    $title = App_Name() . " - Register";
                    $body = "Welcome to " . App_Name() . " App & Enjoy this app.";
                } else if ($type == 2) {
                    $title = App_Name() . " - Transaction";
                    $body = "Welcome to " . App_Name() . " App & Enjoy this app. You have Successfully Transaction.";
                } else if ($type == 3) {
                    $title = App_Name() . " - Login";
                    $body = "Welcome to " . App_Name() . " App & Enjoy this app.";
                } else if ($type == 4) {
                    $title = app_name() . " - Thank You for Requesting! Approval Pending";
                    $body = "Thanks for Request to Become on " . app_name() . " Your application is under review. We’ll notify you once it's approved, Thanks for your patience!";
                } else if ($type == 5) {
                    $title = app_name() . " - Congratulations Your Creator Request is Approved!";
                    $body = "Great news! Your application to join the Creator community on " . app_name() . " has been accepted. We can't wait to see the amazing content you'll create. Log in now and start your journey with us!";
                } else if ($type == 6) {
                    $title = app_name() . " - Creator Request Update";
                    $body = "We're sorry to inform you that your application to become an Creator on " . app_name() . " has not been Rejected.";
                } else if ($type == 7) {
                    $title = app_name() . " - Profile Changes Saved!";
                    $body = "Profile update successful! Your changes have been saved.";
                } else if ($type == 8) {
                    $title = app_name() . " - New Package Purchase - User Has Bought Your Creator Package!";
                    $body = "Great news! A user has successfully bought your creator package and can now view your exclusive content!.";
                } else if ($type == 9) {
                    $title = app_name() . " - Reminder: Your Subscription Expires Tomorrow";
                    $body = "Hey, just a reminder that your subscription to " . $creator['full_name'] . " package will expire in 1 day. Renew now to continue enjoying exclusive content!";
                } else {
                    return true;
                }
                $details = [
                    'title' => $title,
                    'body' => $body
                ];

                // Send Mail
                Mail::to($email)->send(new \App\Mail\mail($details));
            } else {
                return true;
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function is_creator_request($user_id)
    {
        $is_request = Creator_Request::where('user_id', $user_id)->where('status', 1)->first();
        if (!empty($is_request)) {
            return 1;
        } else {
            return 0;
        }
    }
    public function save_notification($type = 0, $user_id = 0, $to_user_id = 0, $post_id = 0, $title = null) // 1 - Admin, 2 - Subscribe Creator, 3 - Subscription user, 4 - Like, , 5- Commant, 6- Live, 7- Upload Post, 8 -Coin Package Buy, 9- User(login,register,update Profile, becom-creator)
    {
        try {

            $data['type'] = $type;
            $data['post_id'] = $post_id;
            $data['user_id'] = $user_id;
            $data['to_user_id'] = $to_user_id;
            $data['title'] = $title;
            $data['message'] = "";
            $data['image'] = "";
            Notification::insertGetId($data);

            $toUser = [];
            $user = User::where('id', $to_user_id)->first();

            if (isset($user['device_token'])) {

                $toUser[] = $user['device_token'];

                $setting = $this->Setting_Data();
                $ONESIGNAL_APP_ID = $setting['onesignal_apid'];
                $ONESIGNAL_REST_KEY = $setting['onesignal_rest_key'];

                // Device type (1 = Android, 2 = IOS)
                $fields = array();
                if ($user['device_type'] == 1) {
                    $fields = array(
                        'app_id' => $ONESIGNAL_APP_ID,
                        'include_android_reg_ids' => $toUser,
                        "isAndroid" => true,
                        "channel_for_external_user_ids" => "push",
                        'headings' => App_Name(),
                        'contents' => array("en" => $title),
                    );
                } elseif ($user['device_type'] == 2) {
                    $fields = array(
                        'app_id' => $ONESIGNAL_APP_ID,
                        'include_player_ids' => $toUser,
                        "isIos" => true,
                        "channel_for_external_user_ids" => "push",
                        'headings' => App_Name(),
                        'contents' => array("en" => $title),
                    );
                }

                $fields = json_encode($fields);

                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'Authorization: Basic ' . $ONESIGNAL_REST_KEY
                ));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_HEADER, FALSE);
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

                $response = curl_exec($ch);

                curl_close($ch);
                return true;
            }
            return true;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    // public function Add_Interests($user_id, $array)
    // {
    //     if (sizeof($array) > 0) {

    //         foreach ($array as $key => $value) {

    //             $check_tag_id = Interests::where('user_id', $user_id)->where('hashtag_id', $key)->first();
    //             if (isset($check_tag_id) && $check_tag_id != null) {

    //                 Interests::where('user_id', $user_id)->where('hashtag_id', $key)->update(['count' => $value]);
    //             } else {

    //                 $inset = new Interests();
    //                 $inset['user_id'] = $user_id;
    //                 $inset['hashtag_id'] = $key;
    //                 $inset['count'] = $value;
    //                 $inset->save();
    //             }
    //         }

    //         // Delete Interests
    //         $data = Interests::where('user_id', $user_id)->orderBy('count', 'desc')->orderBy('id', 'desc')->limit(5)->get();
    //         $interestes_ids = array();
    //         foreach ($data as $key => $value) {
    //             $interestes_ids[] = $value['id'];
    //         }
    //         Interests::where('user_id', $user_id)->whereNotIn('id', $interestes_ids)->delete();
    //     }
    //     return true;
    // }
    // public function gift_buy($user_id, $gift_id)
    // {
    //     $is_buy = Wallet_Transaction::where('user_id', $user_id)->where('gift_id', $gift_id)->where('type', 2)->first();
    //     if (!empty($is_buy)) {
    //         return 1;
    //     } else {
    //         return 0;
    //     }
    // }
    public function remove_story()
    {
        try {

            $data = Story::get();

            for ($i = 0; $i < count($data); $i++) {

                $now = date("Y-m-d H:i:s");
                $EndDate = date("Y-m-d H:i:s", strtotime('+24 hours', strtotime($data[$i]['created_at'])));

                if ($now >= $EndDate) {

                    if ($data[$i] != null) {

                        $this->deleteImageToFolder($this->folder_story, $data[$i]['url']);
                        Story_View::where('story_id', $data[$i]['id'])->delete();
                        $data[$i]->delete();
                    }
                }
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function auto_withdrawal()
    {
        try {
            $today = date('Y-m-d');
            $month_end_date = date('Y-m-t');
            if ($today === $month_end_date) {

                $creator = User::where('is_creator', 1)->where('wallet_amount', '>', 0)->get();
                if (count($creator) > 0) {

                    foreach ($creator as $value) {
                        $setting = Setting_Data();
                        $admin_comission = $setting['commission'];
                        $comission =  ((int)$value['wallet_amount'] * (int)$admin_comission) / 100;
                        $price = (int)$value['wallet_amount'] - $comission;

                        $insert = new Withdrawal_Request();
                        $insert->user_id = $value['id'];
                        $insert->total_earning = $value['wallet_amount'];
                        $insert->price = $price;
                        $insert->commission = $comission;
                        $insert->payment_type = "";
                        $insert->payment_detail = "";
                        $insert->status = 0;
                        $insert->save();

                        $value->update(['wallet_amount' => 0]);
                    }
                }
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function send_reminder_before_expiry($user_id)
    {
        try {
            $this->package_expiry();
            $one_day_later = date('Y-m-d', strtotime("+1 day"));  // Date 1 day from today

            $transactions = Creator_Package_Transaction::where('user_id', $user_id)->where('status', 1)->with('user', 'creator', 'creator_package')->get();
            if ($transactions != null) {
                // Check if expiry date is exactly one day from today
                if ($transactions['expiry_date'] === $one_day_later) {

                    if ($transactions['user'] != null && $transactions['creator'] != null && $transactions['creator_package'] != null) {

                        if ($transactions['creator_package']['type'] == 'Day') {

                            if ($transactions['creator_package']['time'] != 1) {

                                $this->Send_Mail(9, $transactions['user']->email, $transactions['creator']);

                                $title = $transactions['creator']['full_name'] . " " . __('Label.subscription_ends_tomorrow_renew_now_to_keep_accessing_content');
                                $this->save_notification(3, $transactions->to_user_id, $transactions->user_id, 0, $title);
                            }
                        } else {

                            $this->Send_Mail(9, $transactions['user']->email, $transactions['creator']);

                            $title = $transactions['creator']['full_name'] . " " . __('Label.subscription_ends_tomorrow_renew_now_to_keep_accessing_content');
                            $this->save_notification(3, $transactions->to_user_id, $transactions->user_id, 0, $title);
                        }
                    }
                }
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_subscribed_creators($user_id)
    {
        $creators_ids = [];
        $data = Creator_Package_Transaction::where('user_id', $user_id)->where('status', 1)->get()->toArray();
        if (count($data) > 0) {
            $creators_ids = array_column($data, 'to_user_id');
        }
        return $creators_ids;
    }
    public function delete_all_data_user($id)
    {
        Comment::where('user_id', $id)->delete();
        Like::where('user_id', $id)->delete();
        Notification::where('user_id', $id)->delete();
        Notification::where('to_user_id', $id)->delete();
        Read_Notification::where('user_id', $id)->delete();
        Report::where('user_id', $id)->delete();
        User_Block::where('user_id', $id)->delete();
        User_Block::where('block_user_id', $id)->delete();
        Withdrawal_Request::where('user_id', $id)->where('status', 0)->delete();

        $Creator_Request = Creator_Request::where('user_id', $id)->first();
        if (isset($Creator_Request) && $Creator_Request != null) {
            $this->deleteImageToFolder('user', $Creator_Request['front_id_proof_img']);
            $this->deleteImageToFolder('user', $Creator_Request['back_id_proof_img']);
            $Creator_Request->delete();
        }

        $Post = Post::where('user_id', $id)->get();
        if (sizeof($Post) > 0) {
            foreach ($Post as $key => $value) {

                $post_content = Post_Content::where('post_id', $value['id'])->get();
                foreach ($post_content as $content) {
                    $this->deleteImageToFolder('post', $content['content_url']);
                    $content->delete();
                }
                $value->delete();
            }
        }

        $Story = Story::where('user_id', $id)->get();
        if (sizeof($Story) > 0) {
            foreach ($Story as $key => $value) {

                $this->deleteImageToFolder('story', $value['url']);
                $value->delete();
            }
        }
    }
    public static function delete_all_data_post($id)
    {
        Comment::where('post_id', $id)->delete();
        Like::where('post_id', $id)->delete();
        View::where('post_id', $id)->delete();
        Notification::where('post_id', $id)->delete();
    }
    public function setEnvironmentValue($envKey, $envValue)
    {
        $envFile = app()->environmentFilePath();
        $str = file_get_contents($envFile);

        $oldValue = env($envKey);

        if (strpos($str, $envKey) !== false) {
            $str = str_replace("{$envKey}={$oldValue}", "{$envKey}={$envValue}", $str);
        } else {
            $str .= "{$envKey}={$envValue}\n";
        }

        $fp = fopen($envFile, 'w');
        fwrite($fp, $str);
        fclose($fp);
        return $envValue;
    }

    // API's Functions
    public function API_Response($status_code, $message, $array = [], $pagination = '')
    {
        try {
            $data['status'] = $status_code;
            $data['message'] = $message;

            if ($status_code == 200) {
                $data['result'] = $array;
            }

            if ($pagination) {
                $data['total_rows'] = $pagination['total_rows'];
                $data['total_page'] = $pagination['total_page'];
                $data['current_page'] = $pagination['current_page'];
                $data['more_page'] = $pagination['more_page'];
            }
            return $data;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function more_page($current_page, $page_size)
    {
        $more_page = false;
        if ($current_page < $page_size) {
            $more_page = true;
        }
        return $more_page;
    }
    public function pagination_array($total_rows, $page_size, $current_page, $more_page)
    {
        $array['total_rows'] = $total_rows;
        $array['total_page'] = $page_size;
        $array['current_page'] = (int) $current_page;
        $array['more_page'] = $more_page;

        return $array;
    }
}
