<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Coin_Package;
use App\Models\Coin_Package_Transaction;
use App\Models\Comment;
use App\Models\Common;
use App\Models\Creator_Package;
use App\Models\Creator_Package_Transaction;
use App\Models\Follow;
use App\Models\General_Setting;
use App\Models\Package;
use App\Models\Page;
use App\Models\Gift;
use App\Models\Interests;
use App\Models\Like;
use App\Models\Notification;
use App\Models\OnboardingScreen;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Payment_Option;
use App\Models\Post;
use App\Models\Post_Content;
use App\Models\Price_List;
use App\Models\Read_Notification;
use App\Models\Report;
use App\Models\Report_Reason;
use App\Models\Social_Link;
use App\Models\Story;
use App\Models\Story_View;
use App\Models\View;
use App\Models\Wallet_Transaction;
use App\Models\Withdrawal_Request;
use CURLFile;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

// content Type 1- image, 2- Video	
class HomeController extends Controller
{
    private $folder_app = "app";
    private $folder_story = "story";
    private $folder_user = "user";
    private $folder_notification = "notification";
    private $folder_post = "post";
    private $folder_coin_packae = "coin_package";
    private $folder_creator_package = "creator_package";
    private $folder_gift = "gift";
    public $common;
    public $page_limit;
    public function __construct()
    {
        try {

            $this->common = new Common();
            $this->page_limit = env('PAGE_LIMIT');
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }

    public function general_setting()
    {
        try {

            $list = General_Setting::get();

            foreach ($list as $key => $value) {
                if ($value['key'] == 'app_logo') {
                    $value['value'] = $this->common->getImage($this->folder_app, $value['value']);
                }
            }
            return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $list);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_payment_option()
    {
        try {
            $Option_data = Payment_Option::get();

            $return['status'] = 200;
            $return['message'] = __('api_msg.get_record_successfully');
            $return['result'] = [];

            foreach ($Option_data as $key => $value) {
                $return['result'][$value['name']] = $value;
            }
            return $return;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_pages()
    {
        try {
            $data = Page::get();

            $return['status'] = 200;
            $return['message'] = __('api_msg.get_record_successfully');
            $return['result'] = [];

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

                $return['result'][$i]['page_name'] = $data[$i]['page_name'];
                $return['result'][$i]['title'] = $data[$i]['title'];
                $return['result'][$i]['url'] = env('APP_URL') . '/public/pages/' . $data[$i]['page_name'];
                $return['result'][$i]['icon'] = $this->common->getImage($this->folder_app, $data[$i]['icon']);
            }
            return $return;
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_social_links()
    {
        try {
            $data = Social_Link::get();
            if (sizeof($data) > 0) {

                $this->common->imageNameToUrl($data, 'image', $this->folder_app);
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_onboarding_screen()
    {
        try {
            $Data = OnboardingScreen::latest()->get();
            if (!$Data->isEmpty()) {

                $this->common->imageNameToUrl($Data, 'image', $this->folder_app);

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $Data);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_coin_package(Request $request)
    {
        try {

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $data = Coin_Package::orderBy('id', 'DESC');

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

                $this->common->imageNameToUrl($data, 'image', $this->folder_coin_packae);

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_creator_package(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'to_user_id' => 'required|numeric',
                ],
                [
                    'to_user_id.required' => __('api_msg.to_user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }
            $this->common->package_expiry();

            $to_user_id = $request->to_user_id;
            $user_id = isset($request->user_id) ? $request->user_id : 0;
            $package_id = isset($request->package_id) ? $request->package_id : 0;

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            if ($package_id != 0) {
                $data = Creator_Package::where('user_id', $to_user_id)->where('id', $package_id)->orderBy('id', 'DESC');
            } else {
                $data = Creator_Package::where('user_id', $to_user_id)->orderBy('id', 'DESC');
            }

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

                $this->common->imageNameToUrl($data, 'image', $this->folder_creator_package);
                foreach ($data as $value) {
                    $value['is_buy'] = $this->common->is_package_buy($user_id, $value['id']);
                }

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function add_coin_transaction(Request $request)
    {
        try {

            $this->common->package_expiry();

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'coin_package_id' => 'required|numeric',
                    'price' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'coin_package_id.required' => __('api_msg.coin_package_id_is_required'),
                    'price.required' => __('api_msg.price_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $data['user_id'] = $request['user_id'];
            $data['coin_package_id'] = $request['coin_package_id'];
            $data['price'] = $request['price'];
            $data['transaction_id'] = isset($request['transaction_id']) ? $request['transaction_id'] : "";
            $data['description'] = isset($request['description']) ? $request['description'] : "";

            $package_data = Coin_Package::where('id', $request['coin_package_id'])->where('status', '1')->first();
            if (!empty($package_data)) {
                $data['coin'] = $package_data['coin'];
            } else {
                return $this->common->API_Response(400, __('api_msg.please_enter_right_package_id'));
            }

            $result = Coin_Package_Transaction::insertGetId($data);

            if (isset($result) && $result > 0) {

                // Send Mail (Type = 1- Register Mail, 2 Transaction Mail)
                $user = User::where('id', $request['user_id'])->first();
                if (isset($user) && $user != null) {

                    $user->increment('coin_wallet', $data['coin']);
                    $this->common->Send_Mail(2, $user->email);

                    $title =  __('Label.purchase_successful_coins_added_to_your_account');
                    $this->common->save_notification(3, 0, $request->user_id, 0, $title);
                }

                return $this->common->API_Response(200, __('api_msg.you_transaction_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_coin_transaction_list(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $userId = $request['user_id'];

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $data = Coin_Package_Transaction::where('user_id', $userId)->with('coin_package')->latest();

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

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

                    $value['coin_package_name'] = "";
                    if ($value['coin_package'] != null && isset($value['coin_package'])) {
                        $value['coin_package_name'] = $value['coin_package']->name;
                    }
                    unset($value['coin_package']);
                }

                return $this->common->API_Response(200, __('api_msg.get_transaction_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_gift(Request $request)
    {
        try {

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $data = Gift::orderBy('id', 'DESC');

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->latest()->get();

            if (count($data) > 0) {

                $this->common->imageNameToUrl($data, 'image', $this->folder_gift);

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    // public function get_user_gift(Request $request)
    // {
    //     try {

    //         $validation = Validator::make(
    //             $request->all(),
    //             [
    //                 'user_id' => 'required|numeric',
    //             ],
    //             [
    //                 'user_id.required' => __('api_msg.user_id_is_required'),
    //             ]
    //         );
    //         if ($validation->fails()) {
    //             $data['status'] = 400;
    //             $data['message'] = $validation->errors()->first();
    //             return $data;
    //         }

    //         $user_id = $request->user_id;

    //         $page_size = 0;
    //         $current_page = 0;
    //         $more_page = false;

    //         $get_gift = Wallet_Transaction::where('user_id', $user_id)->where('type', 2)->latest()->get();
    //         $gift_ids = [];
    //         foreach ($get_gift as $key => $value) {
    //             $gift_ids[] = $value['gift_id'];
    //         }

    //         $data = Gift::whereIn('id', $gift_ids)->orderBy('id', 'DESC');

    //         $total_rows = $data->count();
    //         $total_page = $this->page_limit;
    //         $page_size = ceil($total_rows / $total_page);
    //         $current_page = $request->page_no ?? 1;
    //         $offset = $current_page * $total_page - $total_page;

    //         $more_page = $this->common->more_page($current_page, $page_size);
    //         $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

    //         $data->take($total_page)->offset($offset);
    //         $data = $data->latest()->get();

    //         if (count($data) > 0) {

    //             $this->common->imageNameToUrl($data, 'image', $this->folder_gift);
    //             for ($i = 0; $i < count($data); $i++) {
    //                 $data[$i]['is_buy'] = $this->common->gift_buy($user_id, $data[$i]['id']);
    //             }

    //             return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
    //         } else {
    //             return $this->common->API_Response(400, __('api_msg.data_not_found'));
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    // public function add_amount_wallet(Request $request) // 1- Amount Add, 2- Buy Gift, 3- Creator Follw	
    // {
    //     try {
    //         $validation = Validator::make(
    //             $request->all(),
    //             [
    //                 'user_id' => 'required|numeric',
    //                 'amount' => 'required|numeric|min:1',
    //             ],
    //             [
    //                 'user_id.required' => __('api_msg.user_id_is_required'),
    //                 'amount.required' => 'Amount is Required.',
    //             ]
    //         );
    //         if ($validation->fails()) {
    //             $data['status'] = 400;
    //             $data['message'] = $validation->errors()->first();
    //             return $data;
    //         }

    //         $data['type'] = 1;
    //         $data['user_id'] = $request['user_id'];
    //         $data['to_user_id'] = 0;
    //         $data['gift_id'] = 0;
    //         $data['amount'] = $request['amount'];
    //         $data['transaction_id'] = "";
    //         $data['description'] = "";
    //         $data['expiry_date'] = "";
    //         if (isset($request['transaction_id'])) {
    //             $data['transaction_id'] = $request['transaction_id'];
    //         }
    //         if (isset($request['description'])) {
    //             $data['description'] = $request['description'];
    //         }
    //         $data['status'] = 1;

    //         $result = Wallet_Transaction::insertGetId($data);

    //         if (isset($result) && $result > 0) {

    //             User::where('id', $request['user_id'])->increment('wallet_amount', $request['amount']);

    //             return $this->common->API_Response(200, __('api_msg.you_transaction_successfully'));
    //         } else {
    //             return $this->common->API_Response(400, __('api_msg.data_not_save'));
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    // public function buy_gift(Request $request)
    // {
    //     try {
    //         $validation = Validator::make(
    //             $request->all(),
    //             [
    //                 'user_id' => 'required|numeric',
    //                 'gift_id' => 'required|numeric',
    //                 'amount' => 'required|numeric',
    //             ],
    //             [
    //                 'user_id.required' => __('api_msg.user_id_is_required'),
    //                 'gift_id.required' => 'Gift Id is Required.',
    //                 'amount.required' => 'Amount is Required.',
    //             ]
    //         );
    //         if ($validation->fails()) {
    //             $data['status'] = 400;
    //             $data['message'] = $validation->errors()->first();
    //             return $data;
    //         }

    //         $data['type'] = 2;
    //         $data['user_id'] = $request['user_id'];
    //         $data['to_user_id'] = 0;
    //         $data['gift_id'] = $request['gift_id'];
    //         $data['amount'] = $request['amount'];
    //         $data['transaction_id'] = "";
    //         $data['description'] = "";
    //         $data['expiry_date'] = "";
    //         $data['status'] = 1;

    //         $user_wallet = User::where('id', $request['user_id'])->first();
    //         if (isset($user_wallet) && $user_wallet['wallet_amount'] >= $request['amount']) {

    //             $result = Wallet_Transaction::insertGetId($data);

    //             if (isset($result) && $result > 0) {

    //                 User::where('id', $request['user_id'])->decrement('wallet_amount', $request['amount']);

    //                 return $this->common->API_Response(200, 'Congratulations!!! gift is bought successfully.');
    //             } else {
    //                 return $this->common->API_Response(400, __('api_msg.data_not_save'));
    //             }
    //         } else {
    //             return $this->common->API_Response(400, 'Opps, Add Amount in Your Wallet.');
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    public function add_creator_package_transaction(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'to_user_id' => 'required|numeric',
                    'creator_package_id' => 'required|numeric',
                    'price' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'to_user_id.required' => __('api_msg.to_user_id_is_required'),
                    'creator_package_id.required' => __('api_msg.creator_package_id_is_required'),
                    'price.required' =>  __('api_msg.price_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $data['user_id'] = $request['user_id'];
            $data['to_user_id'] = $request['to_user_id'];
            $data['creator_package_id'] = $request['creator_package_id'];
            $data['price'] = $request['price'];
            $data['transaction_id'] = isset($request['transaction_id']) ? $request['transaction_id'] : "";
            $data['description'] = isset($request['description']) ? $request['description'] : "";

            $package_data = Creator_Package::where('id', $request['creator_package_id'])->where('status', 1)->first();
            if (!empty($package_data)) {
                $data['expiry_date'] = date('Y-m-d', strtotime('+' . $package_data['time'] . ' ' . strtolower($package_data['type'])));
            } else {
                return $this->common->API_Response(400, __('api_msg.please_enter_right_package_id'));
            }

            $result = Creator_Package_Transaction::insertGetId($data);

            if (isset($result) && $result > 0) {


                $transactions = Creator_Package_Transaction::where('user_id', $data['user_id'])->where('to_user_id', $data['to_user_id'])->where('status', 1)->where('id', "!=", $result)->get();
                foreach ($transactions as $data) {
                    $data->update(['status' => 0]);
                }

                // Send Mail (Type = 1- Register Mail, 2 Transaction Mail)
                $user = User::where('id', $request['user_id'])->first();
                $to_user = User::where('id', $request['to_user_id'])->first();
                if (isset($user) && $user != null) {
                    $this->common->Send_Mail(2, $user->email);

                    $title =  __('Label.purchase_successful_enjoy_exclusive_creator_Content');
                    $this->common->save_notification(3, $request->to_user_id, $request->user_id, 0, $title);
                }
                if (isset($to_user) && $to_user != null) {

                    $this->common->Send_Mail(8, $to_user->email);

                    $title =  __('Label.congratulations_you_have_a_new_subscriber_a_user_purchased_your_package');
                    $this->common->save_notification(2, $request->user_id, $request->to_user_id, 0, $title);
                }

                return $this->common->API_Response(200, __('api_msg.you_transaction_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_creator_package_transaction_list(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $userId = $request['user_id'];

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $data = Creator_Package_Transaction::where('user_id', $userId)->with('creator_package', 'creator')->latest();

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

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

                    $value['creator_package_name'] = "";
                    if ($value['creator_package'] != null && isset($value['creator_package'])) {
                        $value['creator_package_name'] = $value['creator_package']->name;
                    }
                    $value['creator_name'] = "";
                    $value['creator_image'] = "";
                    if ($value['creator'] != null && isset($value['creator'])) {
                        $value['creator_name'] = $value['creator']['full_name'];
                        $value['creator_image'] = $this->common->getImage($this->folder_user, $value['creator']['image']);
                    }
                    unset($value['creator_package'], $value['creator']);
                }

                return $this->common->API_Response(200, __('api_msg.get_transaction_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_earning_list(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $userId = $request['user_id'];

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $data = Creator_Package_Transaction::where('to_user_id', $userId)->with('creator_package', 'user')->latest();

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

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

                    $value['creator_package_name'] = "";
                    if ($value['creator_package'] != null && isset($value['creator_package'])) {
                        $value['creator_package_name'] = $value['creator_package']->name;
                    }
                    $value['user_name'] = "";
                    $value['user_image'] = "";
                    if ($value['user'] != null && isset($value['user'])) {
                        $value['user_name'] = $value['user']['full_name'];
                        $value['user_image'] = $this->common->getImage($this->folder_user, $value['user']['image']);
                    }
                    unset($value['creator_package'], $value['user']);
                }

                return $this->common->API_Response(200, __('api_msg.get_transaction_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    // public function get_price_list(Request $request)
    // {
    //     try {
    //         $data = Price_List::orderBy('id', 'DESC')->get();

    //         if (count($data) > 0) {

    //             return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data);
    //         } else {
    //             return $this->common->API_Response(400, __('api_msg.data_not_found'));
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    // public function get_wallettransaction_list(Request $request) // type :- 1-add amount, 2-gift by, 3-follow transactions
    // {
    //     try {
    //         $validation = Validator::make(
    //             $request->all(),
    //             [
    //                 'user_id' => 'required|numeric',
    //             ],
    //             [
    //                 'user_id.required' => __('api_msg.user_id_is_required'),
    //             ]
    //         );
    //         if ($validation->fails()) {
    //             $data['status'] = 400;
    //             $data['message'] = $validation->errors()->first();
    //             return $data;
    //         }

    //         $userId = $request['user_id'];

    //         $page_size = 0;
    //         $current_page = 0;
    //         $more_page = false;

    //         $data = Wallet_Transaction::where('user_id', $userId)->latest();

    //         $total_rows = $data->count();
    //         $total_page = $this->page_limit;
    //         $page_size = ceil($total_rows / $total_page);
    //         $current_page = $request->page_no ?? 1;
    //         $offset = $current_page * $total_page - $total_page;

    //         $more_page = $this->common->more_page($current_page, $page_size);
    //         $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

    //         $data->take($total_page)->offset($offset);
    //         $data = $data->get();

    //         if (count($data) > 0) {

    //             return $this->common->API_Response(200, __('api_msg.get_transaction_successfully'), $data, $pagination);
    //         } else {
    //             return $this->common->API_Response(400, __('api_msg.data_not_found'));
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    public function get_user_story(Request $request)
    {
        try {
            $this->common->remove_story();

            $validation = Validator::make(
                $request->all(),
                [
                    'to_user_id' => 'required|numeric',
                ],
                [
                    'to_user_id.required' => __('api_msg.to_user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $this->common->remove_story();

            $to_user_id = $request->to_user_id;
            $user_id = isset($request->user_id) ? $request->user_id : 0;

            $story = Story::where('user_id', $to_user_id)->with('user')->where('status', 1)->orderBy('id', 'desc')->get();

            if (sizeof($story) > 0) {

                $user_array = [];
                for ($i = 0; $i < count($story); $i++) {
                    if ($story[$i]['user'] != null) {
                        $user_array[$i] = $story[$i]['user'];
                    }
                }
                $user_array = array_unique($user_array);
                $user_array = array_values($user_array);

                $return_array = [];
                $story_view = Story_View::where('user_id', $user_id)->pluck('story_id')->toArray();

                for ($i = 0; $i < count($user_array); $i++) {
                    $return_array[$i]['user_id'] = $user_array[$i]['id'];
                    $return_array[$i]['user_name'] = $user_array[$i]['user_name'];
                    $return_array[$i]['full_name'] = $user_array[$i]['full_name'];
                    $return_array[$i]['user_image'] = $this->common->getImage($this->folder_user,  $user_array[$i]['image']);

                    $story = [];
                    $get_all_story = Story::where('user_id', $user_array[$i]['id'])->where('status', 1)->orderBy('id', 'desc')->latest()->get();
                    $unview_user_story = [];
                    $view_user_story = [];
                    for ($j = 0; $j < count($get_all_story); $j++) {
                        $get_all_story[$j]['url'] = $this->common->getImage($this->folder_story,  $get_all_story[$j]['url']);

                        if (in_array($get_all_story[$j]['id'], $story_view)) {

                            $get_all_story[$j]['is_view'] = 1;
                            $view_user_story[] = $get_all_story[$j];
                        } else {
                            $get_all_story[$j]['is_view'] = 0;
                            $unview_user_story[] = $get_all_story[$j];
                        }
                    }
                    $story = array_merge($unview_user_story, $view_user_story);
                    $return_array[$i]['story'] = $story;
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $return_array);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function upload_story(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'type' => 'required',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'type.required' => __('api_msg.type_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $url = '';
            if (isset($_FILES['url'])) {
                $file = $request->file('url');
                $url = $this->common->saveImage($file, $this->folder_story, "story_");
            } else {
                $errors = __('api_msg.please_upload_file');
                $data['status'] = 400;
                $data['message'] = $errors;
                return $data;
            }

            $story = new Story();
            $story->user_id = $request->user_id;
            $story->type = $request->type;
            $story->url = $url;
            $story->description = isset($request->description) ? $request->description : "";
            $story->total_view = 0;

            if ($story->save()) {
                return $this->common->API_Response(200, __('api_msg.add_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_story(Request $request)
    {
        try {
            $this->common->remove_story();

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }


            $user_id = $request->user_id;
            $creator_ids = $this->common->get_subscribed_creators($user_id);

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $story = Story::whereIn('user_id', $creator_ids)->with('user')->where('status', 1)->orderBy('id', 'desc');

            $total_rows = $story->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $story->take($total_page)->offset($offset);
            $stories = $story->get();

            $story_view = Story_View::where('user_id', $user_id)->pluck('story_id')->toArray();
            $viewdstory = [];
            $unviewdstory = [];
            foreach ($stories as $story) {
                if (in_array($story->id, $story_view)) {
                    $viewdstory[] = $story;
                } else {
                    $unviewdstory[] = $story;
                }
            }

            $stories = array_merge($unviewdstory, $viewdstory);

            if (sizeof($stories) > 0) {

                $user_array = [];
                for ($i = 0; $i < count($stories); $i++) {
                    if ($stories[$i]['user'] != null) {
                        $user_array[$i] = $stories[$i]['user'];
                    }
                }
                $user_array = array_unique($user_array);
                $user_array = array_values($user_array);

                $return_array = [];

                for ($i = 0; $i < count($user_array); $i++) {
                    $return_array[$i]['user_id'] = $user_array[$i]['id'];
                    $return_array[$i]['user_name'] = $user_array[$i]['user_name'];
                    $return_array[$i]['full_name'] = $user_array[$i]['full_name'];
                    $return_array[$i]['user_image'] = $this->common->getImage($this->folder_user,  $user_array[$i]['image']);

                    $story = [];
                    $get_all_story = Story::where('user_id', $user_array[$i]['id'])->where('status', 1)->orderBy('id', 'desc')->latest()->get();
                    $unview_user_story = [];
                    $view_user_story = [];
                    for ($j = 0; $j < count($get_all_story); $j++) {
                        $get_all_story[$j]['url'] = $this->common->getImage($this->folder_story,  $get_all_story[$j]['url']);

                        if (in_array($get_all_story[$j]['id'], $story_view)) {

                            $get_all_story[$j]['is_view'] = 1;
                            $view_user_story[] = $get_all_story[$j];
                        } else {
                            $get_all_story[$j]['is_view'] = 0;
                            $unview_user_story[] = $get_all_story[$j];
                        }
                    }
                    $story = array_merge($unview_user_story, $view_user_story);
                    $return_array[$i]['story'] = $story;
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $return_array, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function delete_story(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'story_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'story_id.required' => __('api_msg.story_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $data = Story::where('user_id', $request->user_id)->where('id', $request->story_id)->first();
            if (isset($data)) {
                $this->common->deleteImageToFolder($this->folder_story, $data['url']);
                $data->delete();
            }

            return $this->common->API_Response(200, __('api_msg.record_delete_successfully'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function add_story_view(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'story_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'story_id.required' => __('api_msg.story_id_is_required'),
                ]
            );
            if ($validation->fails()) {

                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request['user_id'];
            $story_id = $request['story_id'];

            $viewexist = Story_View::where('user_id', $user_id)->where('story_id', $story_id)->first();

            if ($viewexist == null) {
                $insert = new Story_View();
                $insert->user_id = $user_id;
                $insert->story_id = $story_id;

                if ($insert->save()) {

                    Story::where('id', $request['story_id'])->increment('total_view', 1);
                    return $this->common->API_Response(200, __('api_msg.story_view_added_successfully'));
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_save'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.view_exists'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    // public function follow_unfollow(Request $request)
    // {
    //     try {

    //         $validation = Validator::make(
    //             $request->all(),
    //             [
    //                 'user_id' => 'required|numeric',
    //                 'to_user_id' => 'required|numeric',
    //             ],
    //             [
    //                 'user_id.required' => __('api_msg.user_id_is_required'),
    //                 'to_user_id.required' => __('api_msg.to_user_id_is_required'),
    //             ]
    //         );
    //         if ($validation->fails()) {
    //             $data['status'] = 400;
    //             $data['message'] = $validation->errors()->first();
    //             return $data;
    //         }

    //         $user_id = $request['user_id'];
    //         $to_user_id = $request['to_user_id'];

    //         $ratings_result = Follow::where('user_id', $user_id)->where('to_user_id', $to_user_id)->where('status', 1)->first();

    //         if (isset($ratings_result['id'])) {

    //             Follow::where('id', $ratings_result['id'])->delete();
    //             return $this->common->API_Response(200, __('api_msg.unfollow_successfully'));
    //         } else {

    //             $data['user_id'] = $user_id;
    //             $data['to_user_id'] = $to_user_id;

    //             $added_id = Follow::insertGetId($data);

    //             // Send Notification
    //             $user = User::where('id', $user_id)->first();
    //             $to_user = User::where('id', $to_user_id)->first();
    //             if (isset($to_user) && $to_user != null && isset($user) && $user != null && $user_id != $to_user_id) {

    //                 $title = $user['full_name'] . ' Start following you.';
    //                 $this->common->save_notification(3, $user_id, $to_user_id, 0, $title);
    //             }

    //             return $this->common->API_Response(200, __('api_msg.follow_successfully'));
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    public function like_unlike(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'post_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'post_id.required' => __('api_msg.post_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request['user_id'];
            $post_id = $request['post_id'];

            $data = Like::where('user_id', $user_id)->where('post_id', $post_id)->first();

            if (isset($data['id'])) {

                Like::where('id', $data['id'])->delete();
                return $this->common->API_Response(200, __('api_msg.unlike_successfully'));
            } else {

                $data['user_id'] = $user_id;
                $data['post_id'] = $post_id;

                $added_id = Like::insertGetId($data);

                // Send Notification
                $post = Post::where('id', $post_id)->first();
                $user = User::where('id', $user_id)->first();
                if (isset($post) && $post != null && isset($user) && $user != null && $user_id != $post['user_id']) {

                    $title = $user['full_name'] . " " .  __('Label.liked_your_video');
                    $this->common->save_notification(4, $user_id, $post['user_id'], $post['id'], $title);
                }

                return $this->common->API_Response(200, __('api_msg.like_successfully'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function add_comment(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'post_id' => 'required|numeric',
                    'comment' => 'required',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'post_id.required' => __('api_msg.post_id_is_required'),
                    'comment.required' => __('api_msg.comment_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $VideoUSer = Post::where('id', $request['post_id'])->first();

            if (isset($VideoUSer) && isset($VideoUSer['user_id']) && $VideoUSer['user_id'] != '') {

                $data['user_id'] = $request['user_id'];
                $data['post_id'] = $request['post_id'];
                $data['comment'] = $request['comment'];
                $added_id = Comment::insertGetId($data);

                if ($added_id) {

                    // Send Notification
                    $post = Post::where('id', $request['post_id'])->first();
                    $user = User::where('id', $request['user_id'])->first();
                    if (isset($post) && $post != null && isset($user) && $user != null && $request['user_id'] != $post['user_id']) {

                        $title = $user['full_name'] . " " . __('Label.commented_on_your_video');
                        $this->common->save_notification(5, $request['user_id'], $post['user_id'], $post['id'], $title);
                    }

                    return $this->common->API_Response(200, __('api_msg.comment_add_successfully'));
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_found'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.post_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function view_comment(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'post_id' => 'required|numeric',
                ],
                [
                    'post_id.required' => __('api_msg.post_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $post_id = $request['post_id'];
            $user_id = isset($request['user_id']) ? $request['user_id'] : 0;

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $data = Comment::where('post_id', $post_id)->where('status', 1)->with('user')->orderBy('id', 'desc');

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data)) {

                foreach ($data as $row) {

                    $row->user_name = "";
                    $row->full_name = "";
                    $row->email = "";
                    $row->mobile_number = "";
                    $row->profile_img = asset('/assets/imgs/default.png');
                    if (isset($row->user) && $row->user != null) {
                        $row->user_name = $row->user['user_name'];
                        $row->full_name = $row->user['full_name'];
                        $row->email = $row->user['email'];
                        $row->mobile_number = $row->user['mobile_number'];
                        $row->profile_img = $this->common->getImage($this->folder_user, $row->user['image']);
                    }
                    unset($row->user);
                }

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function edit_comment(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'comment_id' => 'required|numeric',
                    'user_id' => 'required|numeric',
                    'comment' => 'required',
                ],
                [
                    'comment_id.required' => __('api_msg.comment_id_is_required'),
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'comment.required' => __('api_msg.comment_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request['user_id'];
            $data['comment'] = $request['comment'];

            $comment = Comment::where('user_id', $user_id)->where('id', $request['comment_id'])->first();

            if (!empty($comment)) {

                $comment->update($data);
                return $this->common->API_Response(200, __('api_msg.comment_update_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.comment_not_update'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function delete_comment(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'comment_id' => 'required|numeric',
                    'user_id' => 'required|numeric',
                ],
                [
                    'comment_id.required' => __('api_msg.comment_id_is_required'),
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            Comment::where('id', $request['comment_id'])->delete();

            return $this->common->API_Response(200, __('api_msg.record_delete_successfully'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_notification(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request['user_id'];

            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $user_notification_id = Read_Notification::where('user_id', $user_id)->get();
            $NotiIds = [];
            foreach ($user_notification_id as $key => $value) {
                $NotiIds[] = $value['notification_id'];
            }

            $data = Notification::where(function ($query) use ($user_id) {
                $query->where('to_user_id', $user_id)
                    ->orWhere('type', 1);
            })->whereNotIn('id', $NotiIds)->with('user', 'to_user', 'post')->orderBy('id', 'desc');

            $total_rows = $data->count();

            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get();

            if (count($data) > 0) {

                $return = [];
                foreach ($data as $key => $value) {

                    $value['full_name'] = "";
                    $value['user_image'] = asset('/assets/imgs/default.png');
                    $value['post_name'] = "";
                    $value['post_image'] = asset('/assets/imgs/no_img.png');
                    $value['image'] = $this->common->getImage($this->folder_notification, $value['image']);

                    if ($value['user'] != null) {

                        $value['full_name'] = $value['user']['full_name'];
                        $value['user_image'] = $this->common->getImage($this->folder_user, $value['user']['image']);
                    }

                    if ($value['type'] == 4 || $value['type'] == 5 || $value['type'] == 7) {

                        if ($value['post'] != null) {
                            $value['post_name'] = $value['post']['title'];
                            $value['post_image'] = $this->common->getImage($this->folder_post, $value['post']['image']);
                        }
                    }

                    unset($value['image'], $value['to_user'], $value['user'], $value['post']);
                    $return[] = $value;
                }

                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $return, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function read_notification(Request $request)
    {
        try {
            if (isset($request['user_id']) && isset($request['notification_id'])) {

                $data['user_id'] = $request['user_id'];
                $data['notification_id'] = $request['notification_id'];

                Read_Notification::insertGetId($data);
                return $this->common->API_Response(200, __('api_msg.notification_successfully_read'));
            } else {
                return $this->common->API_Response(400, __('api_msg.please_enter_required_fields'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    // public function withdrawal_request(Request $request)
    // {
    //     try {
    //         $validation = Validator::make(
    //             $request->all(),
    //             [
    //                 'user_id' => 'required|numeric',
    //                 'amount' => 'required|numeric',
    //             ],
    //             [
    //                 'user_id.required' => __('api_msg.user_id_is_required'),
    //                 'amount.required' => 'Amount is required.',
    //             ]
    //         );
    //         if ($validation->fails()) {
    //             $data['status'] = 400;
    //             $data['message'] = $validation->errors()->first();
    //             return $data;
    //         }

    //         $user_wallet = User::where('id', $request['user_id'])->first();
    //         if (isset($user_wallet) && $user_wallet['wallet_amount'] >= $request['amount']) {

    //             $insert = new Withdrawal_Request();
    //             $insert['user_id'] = $request['user_id'];
    //             $insert['amount'] = $request['amount'];
    //             $insert['payment_type'] = isset($request['payment_type']) ? $request['payment_type'] : "";
    //             $insert['payment_detail'] = isset($request['payment_detail']) ? $request['payment_detail'] : "";
    //             $insert['status'] = 0;
    //             if ($insert->save()) {

    //                 User::where('id', $request['user_id'])->decrement('wallet_amount', $request['amount']);
    //                 return $this->common->API_Response(200, __('api_msg.withdrawal_request_successfully'));
    //             } else {
    //                 return $this->common->API_Response(400, __('api_msg.data_not_save'));
    //             }
    //         } else {
    //             return $this->common->API_Response(400, 'Your Request amount is not in your wallet, Please check wallet balance.');
    //         }
    //     } catch (Exception $e) {
    //         return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
    //     }
    // }
    public function withdrawal_list(Request $request)
    {
        try {

            $this->common->auto_withdrawal();
            if (isset($request['user_id']) && $request['user_id'] != null) {

                $page_size = 0;
                $current_page = 0;
                $more_page = false;

                $data = Withdrawal_Request::where('user_id', $request['user_id'])->latest();

                $total_rows = $data->count();
                $total_page = $this->page_limit;
                $page_size = ceil($total_rows / $total_page);
                $current_page = $request->page_no ?? 1;
                $offset = $current_page * $total_page - $total_page;

                $more_page = $this->common->more_page($current_page, $page_size);
                $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

                $data->take($total_page)->offset($offset);
                $data = $data->get();

                if (count($data)) {
                    return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
                } else {
                    return $this->common->API_Response(400, __('api_msg.data_not_found'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.please_enter_required_fields'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_report_reason(Request $request)
    {
        try {
            $page_size = 0;
            $current_page = 0;
            $more_page = false;

            $data = Report_Reason::orderBy('id', 'desc');

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);

            $data = $data->latest()->get();

            if (count($data) > 0) {
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $data, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.controller.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function add_report(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'post_id' => 'required|numeric',
                    'reason' => 'required',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'post_id.required' => __('api_msg.post_id_is_required'),
                    'reason.required' => __('api_msg.reason_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $report = new Report();
            $report->user_id = $request->user_id;
            $report->post_id = $request->post_id;
            $report->reason = $request->reason;
            $report->status = 0;

            if ($report->save()) {
                return $this->common->API_Response(200, __('api_msg.report_add_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_post(Request $request)
    {
        try {

            $this->common->package_expiry();

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'numeric',
                    'type' => 'numeric',
                ],
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = isset($request->user_id) ? $request->user_id : 0;
            $type = isset($request->type) ? $request->type : 0;
            $page_no = $request->page_no ?? 1;

            if ($user_id != 0) {

                // Post Report List
                $report = Report::where('user_id', $user_id)->get();
                $report_data = array();
                foreach ($report as $key => $value) {
                    $report_data[] = $value->post_id;
                }

                // Block User List
                $block_user_list = $this->common->get_block_user($user_id);
                // Sub Users List
                $subed_creators = $this->common->get_subscribed_creators($user_id);

                if ($type == 1) {
                    // Subscribed Creators Data
                    $final_array = Post::whereNotIn('user_id', $block_user_list)->whereNotIn('id', $report_data)->whereIn('user_id', $subed_creators)->where('status', 1)->with('user')->latest()->get()->toArray();
                } else if ($type == 2) {
                    // UnSubscribed Creators Data
                    $final_array = Post::whereNotIn('user_id', $block_user_list)->whereNotIn('id', $report_data)->whereNotIn('user_id', $subed_creators)->where('status', 1)->with('user')->latest()->get()->toArray();
                } else {
                    // All Data
                    // ======================= Recent For Subscribed creators Data =======================
                    $now = date("Y-m-d H:i:s");
                    $last_24_hours = date("Y-m-d H:i:s", strtotime('-24 hours', strtotime($now)));

                    $recent_sub_data = Post::where('created_at', ">", $last_24_hours)
                        ->whereIn('user_id', $subed_creators)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();

                    // ======================= Recent creators Data =======================
                    $recent_sub_data_ids = array();
                    // foreach ($recent_sub_data as $key => $value) {
                    //     $recent_sub_data_ids[] = $value['id'];
                    // }
                    $recent_sub_data_ids = array_column($recent_sub_data, 'id');

                    $recent_data = Post::where('created_at', ">", $last_24_hours)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->whereNotIn('id', $recent_sub_data_ids)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();


                    // ======================= Relation Data (comment) =======================
                    $recent_data_ids = array();
                    // foreach ($recent_sub_data as $key => $value) {
                    //     $recent_sub_data_ids[] = $value['id'];
                    // }
                    $recent_data_ids = array_column($recent_data, 'id');

                    $comment_post = [];
                    $user_comment = Comment::where('user_id', $user_id)
                        ->whereNotIn('post_id', $recent_sub_data_ids)
                        ->whereNotIn('post_id', $recent_data_ids)
                        ->get();
                    foreach ($user_comment as $key => $value) {

                        if (!in_array($value['post_id'], $comment_post)) {
                            $comment_post[] = $value['post_id'];
                        }
                    }

                    $relation_comment_data = Post::whereIn('id', $comment_post)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();

                    // ================= Relation Data (Like) ====================
                    $relation_comment_data_ids = array();
                    // foreach ($relation_comment_data as $key => $value) {
                    //     $relation_comment_data_ids[] = $value['id'];
                    // }
                    $relation_comment_data_ids = array_column($relation_comment_data, 'id');

                    $like_post = [];
                    $user_like = Like::where('user_id', $user_id)
                        ->whereNotIn('post_id', $recent_sub_data_ids)
                        ->whereNotIn('post_id', $recent_data_ids)
                        ->whereNotIn('post_id', $relation_comment_data_ids)
                        ->get();
                    foreach ($user_like as $key => $value) {

                        if (!in_array($value['post_id'], $like_post)) {
                            $like_post[] = $value['post_id'];
                        }
                    }

                    $relation_like_data = Post::whereIn('id', $like_post)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();

                    // ======================== Other Data =======================
                    $relation_like_data_ids = array();
                    // foreach ($relation_like_data as $key => $value) {
                    //     $relation_like_data_ids[] = $value['id'];
                    // }
                    $relation_like_data_ids = array_column($relation_like_data, 'id');

                    $other_data = Post::whereNotIn('id', $recent_sub_data_ids)
                        ->whereNotIn('id', $recent_data_ids)
                        ->whereNotIn('id', $relation_comment_data_ids)
                        ->whereNotIn('id', $relation_like_data_ids)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->orderBy('total_view', 'desc')
                        ->latest()->get()->toArray();

                    // ================= Marge All Array =================

                    $final_array = array_merge($recent_sub_data, $recent_data, $relation_comment_data, $relation_like_data, $other_data);
                }
            } else {
                $final_array = Post::orderBy('id', 'desc')->with('user')->latest()->get()->toArray();
            }

            $currentItems = array_slice($final_array, $this->page_limit * ($page_no - 1), $this->page_limit);
            $paginator = new LengthAwarePaginator($currentItems, count($final_array), $this->page_limit, $page_no);

            $more_page = $this->common->more_page($page_no, $paginator->lastPage());
            $pagination = $this->common->pagination_array($paginator->total(), $paginator->lastPage(), $page_no, $more_page);

            $data = $paginator->items();

            if (count($data) > 0) {

                $rk = array();
                foreach ($data as $ra) {

                    // Image Video Full Path
                    $post_content = Post_Content::where('post_id', $ra)->get();
                    $ra['post_content'] = [];
                    foreach ($post_content as $post) {
                        if ($post['content_type'] == 1) {

                            $post['content_url'] = $this->common->getImage($this->folder_post, $post['content_url']);
                        } else {
                            $post['content_url'] = $this->common->getVideo($this->folder_post, $post['content_url']);
                            $post['content_image'] = $this->common->getImage($this->folder_post, $post['content_image']);
                        }
                        $ra['post_content'][] = $post;
                    }

                    // User
                    $ra['user_name'] = "";
                    $ra['full_name'] = "";
                    $ra['email'] = "";
                    $ra['country_code'] = "";
                    $ra['mobile_number'] = "";
                    $ra['country_name'] = "";
                    $ra['profile_img'] = asset('/assets/imgs/default.png');
                    $ra['is_private'] = 0;
                    $ra['is_creator'] = 0;
                    if (isset($ra['user'])) {
                        $ra['user_name'] = $ra['user']['user_name'];
                        $ra['full_name'] = $ra['user']['full_name'];
                        $ra['email'] = $ra['user']['email'];
                        $ra['country_code'] = $ra['user']['country_code'];
                        $ra['mobile_number'] = $ra['user']['mobile_number'];
                        $ra['country_name'] = $ra['user']['country_name'];
                        $ra['profile_img'] = $this->common->getImage($this->folder_user, $ra['user']['image']);
                        $ra['is_private'] = $ra['user']['is_private'];
                        $ra['is_creator'] = $ra['user']['is_creator'];
                    }

                    // All Count
                    $ra = $this->common->get_all_count_for_post($ra, $user_id);

                    // Is Buy 
                    $ra['is_buy'] = $this->common->is_any_package_buy($user_id, $ra['user_id']);
                    unset($ra['user']);

                    $rk[] = $ra;
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $rk, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_video_post(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'numeric',
                    'type' => 'numeric',
                ],
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request->user_id;
            $type = $request->type;
            $page_no = $request->page_no ?? 1;

            if ($user_id != 0) {

                // Post Report List
                $report = Report::where('user_id', $user_id)->get();
                $report_data = array();
                foreach ($report as $key => $value) {
                    $report_data[] = $value->post_id;
                }

                // Block User List
                $block_user_list = $this->common->get_block_user($user_id);
                // Sub Users List
                $subed_creators = $this->common->get_subscribed_creators($user_id);

                if ($type == 1) {
                    $final_array = Post::whereNotIn('user_id', $block_user_list)->whereNotIn('id', $report_data)->whereIn('user_id', $subed_creators)->where('status', 1)->with('user')->latest()->get()->toArray();
                } else if ($type == 2) {
                    $final_array = Post::whereNotIn('user_id', $block_user_list)->whereNotIn('id', $report_data)->whereNotIn('user_id', $subed_creators)->where('status', 1)->with('user')->latest()->get()->toArray();
                } else {

                    // ======================= Recent For Subscribed creators Data =======================
                    $now = date("Y-m-d H:i:s");
                    $last_24_hours = date("Y-m-d H:i:s", strtotime('-24 hours', strtotime($now)));

                    $recent_sub_data = Post::where('created_at', ">", $last_24_hours)
                        ->whereIn('user_id', $subed_creators)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();

                    // ======================= Recent creators Data =======================
                    $recent_sub_data_ids = array();
                    // foreach ($recent_sub_data as $key => $value) {
                    //     $recent_sub_data_ids[] = $value['id'];
                    // }
                    $recent_sub_data_ids = array_column($recent_sub_data, 'id');

                    $recent_data = Post::where('created_at', ">", $last_24_hours)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->whereNotIn('id', $recent_sub_data_ids)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();


                    // ======================= Relation Data (comment) =======================
                    $recent_data_ids = array();
                    // foreach ($recent_sub_data as $key => $value) {
                    //     $recent_sub_data_ids[] = $value['id'];
                    // }
                    $recent_data_ids = array_column($recent_data, 'id');

                    $comment_post = [];
                    $user_comment = Comment::where('user_id', $user_id)
                        ->whereNotIn('post_id', $recent_sub_data_ids)
                        ->whereNotIn('post_id', $recent_data_ids)
                        ->get();
                    foreach ($user_comment as $key => $value) {

                        if (!in_array($value['post_id'], $comment_post)) {
                            $comment_post[] = $value['post_id'];
                        }
                    }

                    $relation_comment_data = Post::whereIn('id', $comment_post)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();

                    // ================= Relation Data (Like) ====================
                    $relation_comment_data_ids = array();
                    // foreach ($relation_comment_data as $key => $value) {
                    //     $relation_comment_data_ids[] = $value['id'];
                    // }
                    $relation_comment_data_ids = array_column($relation_comment_data, 'id');

                    $like_post = [];
                    $user_like = Like::where('user_id', $user_id)
                        ->whereNotIn('post_id', $recent_sub_data_ids)
                        ->whereNotIn('post_id', $recent_data_ids)
                        ->whereNotIn('post_id', $relation_comment_data_ids)
                        ->get();
                    foreach ($user_like as $key => $value) {

                        if (!in_array($value['post_id'], $like_post)) {
                            $like_post[] = $value['post_id'];
                        }
                    }

                    $relation_like_data = Post::whereIn('id', $like_post)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->latest()->get()->toArray();

                    // ======================== Other Data =======================
                    $relation_like_data_ids = array();
                    // foreach ($relation_like_data as $key => $value) {
                    //     $relation_like_data_ids[] = $value['id'];
                    // }
                    $relation_like_data_ids = array_column($relation_like_data, 'id');

                    $other_data = Post::whereNotIn('id', $recent_sub_data_ids)
                        ->whereNotIn('id', $recent_data_ids)
                        ->whereNotIn('id', $relation_comment_data_ids)
                        ->whereNotIn('id', $relation_like_data_ids)
                        ->whereNotIn('user_id', $block_user_list)
                        ->whereNotIn('id', $report_data)
                        ->where('status', 1)
                        ->with('user')
                        ->orderBy('total_view', 'desc')
                        ->latest()->get()->toArray();

                    // ================= Marge All Array =================

                    $final_array = array_merge($recent_sub_data, $recent_data, $relation_comment_data, $relation_like_data, $other_data);
                }
            } else {
                $final_array = Post::orderBy('id', 'desc')->latest()->get()->toArray();
            }

            $currentItems = array_slice($final_array, $this->page_limit * ($page_no - 1), $this->page_limit);
            $paginator = new LengthAwarePaginator($currentItems, count($final_array), $this->page_limit, $page_no);

            $more_page = $this->common->more_page($page_no, $paginator->lastPage());
            $pagination = $this->common->pagination_array($paginator->total(), $paginator->lastPage(), $page_no, $more_page);

            $data = $paginator->items();

            if (count($data) > 0) {

                $rk = array();
                foreach ($data as $ra) {

                    // Image Video Full Path
                    // Image Video Full Path
                    $post_content = Post_Content::where('post_id', $ra)->get();
                    $ra['post_content'] = [];
                    foreach ($post_content as $post) {
                        if ($post['content_type'] == 1) {

                            $post['content_url'] = $this->common->getImage($this->folder_post, $post['content_url']);
                        } else {
                            $post['content_url'] = $this->common->getVideo($this->folder_post, $post['content_url']);
                            $post['content_image'] = $this->common->getImage($this->folder_post, $post['content_image']);
                        }
                        $ra['post_content'][] = $post;
                    }

                    // User
                    $ra['user_name'] = "";
                    $ra['full_name'] = "";
                    $ra['email'] = "";
                    $ra['country_code'] = "";
                    $ra['mobile_number'] = "";
                    $ra['country_name'] = "";
                    $ra['profile_img'] = asset('/assets/imgs/default.png');
                    $ra['is_private'] = 0;
                    if (isset($ra['user'])) {
                        $ra['user_name'] = $ra['user']['user_name'];
                        $ra['full_name'] = $ra['user']['full_name'];
                        $ra['email'] = $ra['user']['email'];
                        $ra['country_code'] = $ra['user']['country_code'];
                        $ra['mobile_number'] = $ra['user']['mobile_number'];
                        $ra['country_name'] = $ra['user']['country_name'];
                        $ra['profile_img'] = $this->common->getImage($this->folder_user, $ra['user']['image']);
                        $ra['is_private'] = $ra['user']['is_private'];
                    }


                    // All Count
                    $ra = $this->common->get_all_count_for_post($ra, $user_id);

                    // Is Buy 
                    $ra['is_buy'] = $this->common->is_any_package_buy($user_id, $ra['user_id']);

                    unset($ra['user']);
                    $rk[] = $ra;
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $rk, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function get_user_post(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'to_user_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'to_user_id.required' => __('api_msg.to_user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request->user_id;
            $to_user_id = $request->to_user_id;
            $type = isset($request->type) ? $request->type : "";

            if ($type) {
                $data = Post::where('user_id', $to_user_id)->where('type', $type)->where('status', 1)->orderBy('id', "DESC")->with('user');
            } else {
                $data = Post::where('user_id', $to_user_id)->where('status', 1)->orderBy('created_at', "DESC")->with('user');
            }

            $total_rows = $data->count();
            $total_page = $this->page_limit;
            $page_size = ceil($total_rows / $total_page);
            $current_page = $request->page_no ?? 1;
            $offset = $current_page * $total_page - $total_page;

            $more_page = $this->common->more_page($current_page, $page_size);
            $pagination = $this->common->pagination_array($total_rows, $page_size, $current_page, $more_page);

            $data->take($total_page)->offset($offset);
            $data = $data->get()->toArray();

            if (count($data) > 0) {

                $rk = array();
                foreach ($data as $ra) {

                    $ra['is_ads'] = 0;

                    // Image Video Full Path
                    $post_content = Post_Content::where('post_id', $ra)->get();
                    $ra['post_content'] = [];
                    foreach ($post_content as $post) {
                        if ($post['content_type'] == 1) {

                            $post['content_url'] = $this->common->getImage($this->folder_post, $post['content_url']);
                        } else {
                            $post['content_url'] = $this->common->getVideo($this->folder_post, $post['content_url']);
                            $post['content_image'] = $this->common->getImage($this->folder_post, $post['content_image']);
                        }
                        $ra['post_content'][] = $post;
                    }


                    // User
                    $ra['user_name'] = "";
                    $ra['full_name'] = "";
                    $ra['email'] = "";
                    $ra['country_code'] = "";
                    $ra['mobile_number'] = "";
                    $ra['country_name'] = "";
                    $ra['profile_img'] = asset('/assets/imgs/default.png');
                    $ra['is_private'] = 0;
                    $ra['is_creator'] = 0;
                    if (isset($ra['user'])) {
                        $ra['user_name'] = $ra['user']['user_name'];
                        $ra['full_name'] = $ra['user']['full_name'];
                        $ra['email'] = $ra['user']['email'];
                        $ra['country_code'] = $ra['user']['country_code'];
                        $ra['mobile_number'] = $ra['user']['mobile_number'];
                        $ra['country_name'] = $ra['user']['country_name'];
                        $ra['profile_img'] = $this->common->getImage($this->folder_user, $ra['user']['image']);
                        $ra['is_private'] = $ra['user']['is_private'];
                        $ra['is_creator'] = $ra['user']['is_creator'];
                    }

                    // All Count
                    $ra = $this->common->get_all_count_for_post($ra, $to_user_id);

                    $ra['is_buy'] = $this->common->is_any_package_buy($user_id, $ra['user_id']);

                    unset($ra['user']);
                    $rk[] = $ra;
                }
                return $this->common->API_Response(200, __('api_msg.get_record_successfully'), $rk, $pagination);
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function image_upload(Request $request)  // 1- image, 2- Video	
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'content_type' => 'required',
                    'content' => 'required',
                ],
                [
                    'content_type.required' => __('api_msg.content_type_is_required'),
                    'content.required' => __('api_msg.content_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            if ($request['content_type'] == 2) {
                $validation2 = Validator::make(
                    $request->all(),
                    [
                        'content_image' => 'required',
                    ],
                    [
                        'content_image.required' => __('api_msg.content_image_is_required'),
                    ]
                );
                if ($validation2->fails()) {
                    $data['status'] = 400;
                    $data['message'] = $validation2->errors()->first();
                    return $data;
                }
            }

            $content_type = $request['content_type'];
            $content = $request['content'];
            $content_image = $request['content_image'];

            if ($content_type == 1) {

                if ($request->file('content')) {

                    $content = $this->common->saveImage($content, $this->folder_post, 'img_');
                } elseif (is_string($content)) {
                    $content = json_decode($content, true);
                    if (is_array($content)) {

                        $binary = implode(array_map("chr", $content));
                        $finfo = new \finfo(FILEINFO_MIME_TYPE);
                        $mimeType = $finfo->buffer($binary);
                        $extensions = [
                            'image/jpeg' => 'jpg',
                            'image/png' => 'png',
                            'image/jpeg' => 'jpeg',
                        ];
                        $img_ext = $extensions[$mimeType];
                        $filename = 'img_' . date('d_m_Y_') . rand(1111, 9999) . '.' . $img_ext;
                        file_put_contents(base_path('storage/app/public/' . $this->folder_post . '/' . $filename), $binary);
                        $content = $filename;
                    } else {
                        return $this->common->API_Response(400, __('api_msg.content_not_saved'));
                    }
                } else {
                    return $this->common->API_Response(400, __('api_msg.content_not_saved'));
                }
            } elseif ($content_type == 2) {

                // $setting_data = Setting_Data();
                // if ($setting_data['sight_engine_status'] == 1) { // sight engine video Redaction

                //     $user_key = $setting_data['sight_engine_user_key'];
                //     $secret_key = $setting_data['sight_engine_secret_key'];
                //     $concepts = $setting_data['sight_engine_concepts'];

                //     $video = $request->file('content');

                //     $params = array(
                //         'media' => new CURLFile($video),
                //         'concepts' => $concepts,
                //         'api_user' => $user_key,
                //         'api_secret' => $secret_key,
                //     );

                //     $ch = curl_init('https://api.sightengine.com/1.0/video/transform.json');
                //     curl_setopt($ch, CURLOPT_POST, true);
                //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                //     curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                //     curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable verbose output for debugging
                //     $response = curl_exec($ch);

                //     // Check for CURL errors
                //     if (curl_errno($ch)) {
                //         $curl_error = curl_error($ch);
                //         curl_close($ch);
                //         return response()->json(['status' => 500, 'errors' => 'CURL Error: ' . $curl_error]);
                //     }

                //     curl_close($ch);

                //     $output = json_decode($response, true);

                //     if (isset($output['status']) && $output['status'] == "success") {
                //         $media_id = $output['media']['id'];

                //         $params1 = array(
                //             'id' => $media_id,
                //             'api_user' => $user_key,
                //             'api_secret' => $secret_key,
                //         );

                //         $maxAttempts = 100; // Set the maximum number of attempts

                //         for ($attempts = 0; $attempts < $maxAttempts; $attempts++) {
                //             $ch = curl_init('https://api.sightengine.com/1.0/video/byid.json?' . http_build_query($params1));
                //             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                //             $response = curl_exec($ch);

                //             // Check for CURL errors 
                //             if (curl_errno($ch)) {
                //                 $curl_error = curl_error($ch);
                //                 curl_close($ch);
                //                 return response()->json(['status' => 500, 'errors' => 'CURL Error: ' . $curl_error]);
                //             }

                //             curl_close($ch);
                //             $output2 = json_decode($response, true);

                //             if (isset($output2['output']['data']['status'])) {
                //                 $status = $output2['output']['data']['status'];

                //                 if ($status === 'finished') {

                //                     $videoUrl = $output2['output']['data']['transform']['location'];

                //                     // Get the video content
                //                     $video_get = Http::get($videoUrl);
                //                     if ($video_get->successful()) {

                //                         $filename = 'vid_' . date('d_m_Y_') . rand(1111, 9999) . '.mp4';
                //                         $path = $this->folder_post . '/' . $filename;
                //                         Storage::disk('public')->put($path, $video_get->body());

                //                         // // Delete the old video file
                //                         // $this->common->deleteImageToFolder($this->folder_post, $content);
                //                         $content = $filename;
                //                     } else {

                //                         $error = 'Error on getting video from Sight Engine';
                //                         return response()->json(['status' => 400, 'errors' => $error]);
                //                     }
                //                     break; // Break the loop if processing is successful

                //                 } elseif ($status === 'ongoing') {
                //                     sleep(5);
                //                     $attempts++;
                //                     if ($attempts >= $maxAttempts - 1) {
                //                         // Reset the counter after reaching max attempts
                //                         $attempts = 0;
                //                     }
                //                 }
                //             } elseif ($output2['status'] == "failure") {
                //                 // Handle failure case
                //                 $error = isset($output2['error']['message']) ? $output2['error']['message'] : 'Unknown error';
                //                 return response()->json(['status' => 400, 'errors' => $error]);
                //             }
                //         }
                //     } else {
                //         $error = isset($output['error']['message']) ? $output['error']['message'] : 'Unknown error';
                //         return response()->json(['status' => 400, 'errors' => $error]);
                //     }
                // } else {
                // }
                
                if ($request->file('content')) {
                    $content = $this->common->saveImage($content, $this->folder_post, 'vid_');
                } elseif (is_string($content)) {

                    $content = json_decode($content, true);
                    if (is_array($content)) {

                        $binary = implode(array_map("chr", $content));
                        $finfo = new \finfo(FILEINFO_MIME_TYPE);
                        $mimeType = $finfo->buffer($binary);
                        $extensions = [
                            'video/mp4' => 'mp4',
                            'video/webm' => 'webm',
                        ];
                        $img_ext = $extensions[$mimeType];
                        $filename = 'vid_' . date('d_m_Y_') . rand(1111, 9999) . '.' . $img_ext;
                        file_put_contents(base_path('storage/app/public/' . $this->folder_post . '/' . $filename), $binary);
                        $content = $filename;
                    } else {
                        return $this->common->API_Response(400, __('api_msg.content_not_saved'));
                    }
                } else {
                    return $this->common->API_Response(400, __('api_msg.content_not_saved'));
                }

                if ($request->file('content_image')) {

                    $content_image = $this->common->saveImage($content_image, $this->folder_post, 'img_');
                } elseif (is_string($content_image)) {
                    $content_image = json_decode($content_image, true);
                    if (is_array($content_image)) {

                        $binary = implode(array_map("chr", $content_image));
                        $finfo = new \finfo(FILEINFO_MIME_TYPE);
                        $mimeType = $finfo->buffer($binary);
                        $extensions = [
                            'image/jpeg' => 'jpg',
                            'image/png' => 'png',
                            'image/jpeg' => 'jpeg',
                        ];
                        $img_ext = $extensions[$mimeType];
                        $filename = 'img_' . date('d_m_Y_') . rand(1111, 9999) . '.' . $img_ext;
                        file_put_contents(base_path('storage/app/public/' . $this->folder_post . '/' . $filename), $binary);
                        $content_image = $filename;
                    } else {
                        return $this->common->API_Response(400, __('api_msg.content_not_saved'));
                    }
                } else {
                    return $this->common->API_Response(400, __('api_msg.content_not_saved'));
                }
            }

            if ($content) {
                $data = [];
                if ($content_type == 1) {

                    $data['content_type'] = $content_type;
                    $data['content_name'] = $content;
                    $data['content_url'] = $this->common->getImage($this->folder_post, $content);
                    $data['content_image_name'] = "";
                    $data['content_image_url'] = "";
                } else {

                    $data['content_type'] = $content_type;
                    $data['content_name'] = $content;
                    $data['content_url'] = $this->common->getVideo($this->folder_post, $content);
                    $data['content_image_name'] = $content_image;
                    $data['content_image_url'] = $this->common->getImage($this->folder_post, $content_image);
                }

                if ($data != null) {
                    return $this->common->API_Response(200, __('api_msg.content_save'), $data);
                } else {
                    return $this->common->API_Response(400, __('api_msg.content_not_saved'));
                }
            } else {
                return $this->common->API_Response(400, __('api_msg.content_not_saved'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function upload_post(Request $request) // 1- image, 2- Video
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'title' => 'required',
                    'is_comment' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'title.required' => __('api_msg.title_is_required'),
                    'is_comment.required' => __('api_msg.is_comment_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $data['user_id'] = $request['user_id'];
            $hashtag_id = $this->common->checkHashTag($request['title']);
            $hashtagId = 0;
            if (count($hashtag_id) > 0) {
                $hashtagId = implode(',', $hashtag_id);
            }
            $data['hashtag_id'] = $hashtagId;
            $data['title'] = $request['title'];
            $data['descripation'] = isset($request['descripation']) ? $request['descripation'] : "";
            $data['is_comment'] = $request['is_comment'];
            $data['total_view'] = 0;

            $post_id = Post::insertGetId($data);

            if (isset($post_id)) {

                $post_content = $request['post_content'];

                if (is_string($post_content)) {
                    $post_content = json_decode($post_content, true);
                }

                if (!empty($post_content)) {

                    foreach ($post_content as $item) {
                        $content_type = $item['content_type'];
                        $content_url = $item['content_url'];
                        $content_image = $item['content_image'];

                        if (!is_null($content_url)) {
                            Post_Content::Create([
                                'post_id' => $post_id,
                                'content_type' => $content_type,
                                'content_url' => $content_url,
                                'content_image' => $content_image,
                            ]);
                        }
                    }
                }

                $sub_users = Creator_Package_Transaction::where('to_user_id', $data['user_id'])->where('status', 1)->get()->toArray();
                if (count($sub_users) > 0) {
                    $user_ids = array_column($sub_users, 'user_id');

                    $users = User::whereIn('id', $user_ids)->get();
                    $creator = User::where('id', $data['user_id'])->first();
                    foreach ($users as $value) {

                        if (isset($value) && $value != null && $value['user_id'] != $creator['id']) {

                            $title = $creator['full_name'] . " " . __('Label.just_uploaded_a_new_post_go_check_it_out');
                            $this->common->save_notification(7, $creator['id'], $value['id'], $post_id, $title);
                        }
                    }
                }
                return $this->common->API_Response(200, __('api_msg.post_upload_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function delete_post(Request $request)
    {
        try {

            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'post_id' => 'required|numeric',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'post_id.required' => __('api_msg.post_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $user_id = $request->user_id;
            $post_id = $request->post_id;

            $post = Post::where('id', $post_id)->first();
            if (isset($post) && $post != null) {

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

                $this->common->delete_all_data_post($post_id);
            }

            return $this->common->API_Response(200, __('api_msg.record_delete_successfully'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function add_view(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'post_id' => 'required|numeric',
                    'user_id' => 'required|numeric',
                ],
                [
                    'post_id.required' => __('api_msg.post_id_is_required'),
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $check = View::where('user_id', $request['user_id'])->where('post_id', $request['post_id'])->latest()->first();
            if (!isset($check) && $check == null) {

                $insert = new View();
                $insert['user_id'] = $request['user_id'];
                $insert['post_id'] = $request['post_id'];
                $insert['status'] = 1;
                if ($insert->save()) {
                    Post::where('id', $request->post_id)->increment('total_view', 1);
                }
            }
            return $this->common->API_Response(200, __('api_msg.post_view_successfully'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function add_creator_package(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'user_id' => 'required|numeric',
                    'name' => 'required',
                    'price' => 'required|numeric',
                    'time' => 'required|numeric',
                    'type' => 'required',
                ],
                [
                    'user_id.required' => __('api_msg.user_id_is_required'),
                    'name.required' => __('api_msg.name_is_required'),
                    'price.required' =>  __('api_msg.price_is_required'),
                    'time.required' => __('api_msg.time_is_required'),
                    'type.required' => __('api_msg.type_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $package = new Creator_Package();
            $package['user_id'] = $request['user_id'];
            $package['name'] = $request['name'];
            $package['price'] = $request['price'];
            $package['time'] = $request['time'];
            $package['type'] = $request['type'];
            $package['image'] = "";
            if (isset($request['image']) && $request['image'] != null) {

                $file = $request->file('image');
                $package['image'] = $this->common->saveImage($file, $this->folder_creator_package, "pack_");
            }
            $package['android_product_package'] = isset($request['android_product_package']) ? $request['android_product_package'] : "";
            $package['ios_product_package'] = isset($request['ios_product_package']) ? $request['ios_product_package'] : "";
            $package['web_product_package'] = isset($request['web_product_package']) ? $request['web_product_package'] : "";

            if ($package->save()) {

                return $this->common->API_Response(200, __('api_msg.creator_package_add_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_save'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function edit_creator_package(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'creator_package_id' => 'required|numeric',
                    'user_id' => 'required|numeric',
                ],
                [
                    'creator_package_id.required' => __('api_msg.creator_package_id_is_required'),
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $package = Creator_Package::where('id', $request['creator_package_id'])->where('user_id', $request['user_id'])->first();
            $array = array();
            if ($package != null) {

                if (isset($request->name) && $request->name != '') {
                    $array['name'] = $request->name;
                }
                if (isset($request->price) && $request->price != '') {
                    $array['price'] = $request->price;
                }
                if (isset($request->time) && $request->time != '') {
                    $array['time'] = $request->time;
                }
                if (isset($request->type) && $request->type != '') {
                    $array['type'] = $request->type;
                }
                if (isset($request->image) && $request->file('image') != '') {

                    $image = $request->file('image');
                    $old_image = $package['image'];

                    $array['image'] = $this->common->saveImage($image, $this->folder_creator_package, "pack_");
                    $this->common->deleteImageToFolder($this->folder_creator_package, $old_image);
                }
                if (isset($request->android_product_package) && $request->android_product_package != '') {
                    $array['android_product_package'] = $request->android_product_package;
                }
                if (isset($request->ios_product_package) && $request->ios_product_package != '') {
                    $array['ios_product_package'] = $request->ios_product_package;
                }
                if (isset($request->web_product_package) && $request->web_product_package != '') {
                    $array['web_product_package'] = $request->web_product_package;
                }

                Creator_Package::where('id', $request->creator_package_id)->update($array);

                return $this->common->API_Response(200, __('api_msg.creator_package_update_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function delete_creator_package(Request $request)
    {
        try {
            $validation = Validator::make(
                $request->all(),
                [
                    'creator_package_id' => 'required|numeric',
                    'user_id' => 'required|numeric',
                ],
                [
                    'creator_package_id.required' => __('api_msg.creator_package_id_is_required'),
                    'user_id.required' => __('api_msg.user_id_is_required'),
                ]
            );
            if ($validation->fails()) {
                $data['status'] = 400;
                $data['message'] = $validation->errors()->first();
                return $data;
            }

            $package = Creator_Package::where('id', $request['creator_package_id'])->where('user_id', $request['user_id'])->first();

            if ($package != null) {

                Creator_Package_Transaction::where('creator_package_id', $package['id'])->update(['status' => 0]);
                $this->common->deleteImageToFolder($this->folder_creator_package, $package['image']);
                $package->delete();

                return $this->common->API_Response(200, __('api_msg.creator_package_delete_successfully'));
            } else {
                return $this->common->API_Response(400, __('api_msg.data_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
}
