<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Common;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class CreatorController extends Controller
{
    private $folder_user = "user";
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {
            $params['data'] = [];
            if ($request->ajax()) {

                $input_search = $request['input_search'];
                $input_type = $request['input_type'];
                $input_login_type = $request['input_login_type'];

                if ($input_search != null && isset($input_search)) {

                    if ($input_login_type == "all") {

                        if ($input_type == "today") {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->whereDay('created_at', date('d'))
                                ->whereMonth('created_at', date('m'))
                                ->whereYear('created_at', date('Y'))
                                ->latest()->get();
                        } else if ($input_type == "month") {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->whereMonth('created_at', date('m'))
                                ->whereYear('created_at', date('Y'))
                                
                                ->latest()->get();
                        } else if ($input_type == "year") {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->whereYear('created_at', date('Y'))
                                ->latest()->get();
                        } else {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->latest()->get();
                        }
                    } else {

                        if ($input_type == "today") {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->where('type', $input_login_type)
                                ->whereDay('created_at', date('d'))
                                ->whereMonth('created_at', date('m'))
                                ->whereYear('created_at', date('Y'))
                                ->latest()->get();
                        } else if ($input_type == "month") {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->where('type', $input_login_type)
                                ->whereMonth('created_at', date('m'))
                                ->whereYear('created_at', date('Y'))
                                ->latest()->get();
                        } else if ($input_type == "year") {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->where('type', $input_login_type)
                                ->whereYear('created_at', date('Y'))
                                ->latest()->get();
                        } else {

                            $data = User::where(function ($query) use ($input_search) {
                                $query->where('full_name', 'LIKE', "%{$input_search}%")->orWhere('email', 'LIKE', "%{$input_search}%")->orWhere('mobile_number', 'LIKE', "%{$input_search}%");
                            })
                                ->where('is_creator', 1)
                                ->where('type', $input_login_type)
                                ->latest()->get();
                        }
                    }
                } else {

                    if ($input_login_type == "all") {

                        if ($input_type == "today") {

                            $data = User::where('is_creator', 1)->whereDay('created_at', date('d'))->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'))->latest()->get();
                        } else if ($input_type == "month") {

                            $data = User::where('is_creator', 1)->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'))->latest()->get();
                        } else if ($input_type == "year") {

                            $data = User::where('is_creator', 1)->whereYear('created_at', date('Y'))->latest()->get();
                        } else {

                            $data = User::where('is_creator', 1)->latest()->get();
                        }
                    } else {

                        if ($input_type == "today") {

                            $data = User::where('is_creator', 1)->where('type', $input_login_type)->whereDay('created_at', date('d'))->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'))->latest()->get();
                        } else if ($input_type == "month") {

                            $data = User::where('is_creator', 1)->where('type', $input_login_type)->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'))->latest()->get();
                        } else if ($input_type == "year") {

                            $data = User::where('is_creator', 1)->where('type', $input_login_type)->whereYear('created_at', date('Y'))->latest()->get();
                        } else {

                            $data = User::where('is_creator', 1)->where('type', $input_login_type)->latest()->get();
                        }
                    }
                }

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

                return DataTables()::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function ($row) {
                        $creator_delete = __('Label.delete_creator');

                        $delete = '<form onsubmit="return confirm(\'' . $creator_delete . '\');" method="POST"  action="' . route('creator.destroy', [$row->id]) . '">
                                <input type="hidden" name="_token" value="' . csrf_token() . '">
                                <input type="hidden" name="_method" value="DELETE">
                                <button type="submit" class="edit-delete-btn" style="outline: none;" title="Delete"><i class="fa-solid fa-trash-can fa-xl"></i></button></form>';

                        $btn = '<div class="d-flex justify-content-around">';
                        $btn .= '<a href="' . route('creator.edit', [$row->id]) . '" class="edit-delete-btn" title="Edit">';
                        $btn .= '<i class="fa-solid fa-pen-to-square fa-xl"></i>';
                        $btn .= '</a>';
                        $btn .= $delete;
                        $btn .= '</a></div>';
                        return $btn;
                    })
                    ->addColumn('date', function ($row) {
                        $date = date("Y-m-d", strtotime($row->created_at));
                        return $date;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
            }
            return view('admin.creator.index', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function create()
    {
        try {
            $params['data'] = [];
            return view('admin.creator.add', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'full_name' => 'required|min:2',
                'mobile_number' => [
                    'required',
                    'numeric',
                    Rule::unique('tbl_user')->where(function ($query) use ($request,) {
                        return $query->where('country_code', $request->country_code)
                            ->where('mobile_number', $request->mobile_number);
                    }),
                ],
                'country_code' => 'required',
                'country_name' => 'required',
                'email' => 'required|unique:tbl_user|email',
                'password' => 'required|min:4',
                'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
                'cover_img' => 'required|image|mimes:jpeg,png,jpg|max:2048',
                'is_verified_at' => 'required',
                'gender' => 'required',
                'date_of_birth' => 'required|date|before_or_equal:today',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            $requestData = $request->all();

            $requestData['firebase_id'] = "";
            $email_array = explode('@', $request->email);
            $requestData['user_name'] = $this->common->user_name($email_array[0]);
            $requestData['password'] = Hash::make($requestData['password']);
            if (isset($requestData['image'])) {
                $files = $requestData['image'];
                $requestData['image'] = $this->common->saveImage($files, $this->folder_user, "creactor_");
            }
            if (isset($requestData['cover_img'])) {
                $files = $requestData['cover_img'];
                $requestData['cover_img'] = $this->common->saveImage($files, $this->folder_user, "creactor_");
            }
            $requestData['type'] = 4;
            $requestData['bio'] = isset($request->bio) ? $request->bio : $this->common->user_tag_line();
            $requestData['device_type'] = 0;
            $requestData['device_token'] = "";
            $requestData['facebook_url'] = isset($request->facebook_url) ? $request->facebook_url : "";
            $requestData['instagram_url'] = isset($request->instagram_url) ? $request->instagram_url : "";
            $requestData['youtube_url'] = isset($request->youtube_url) ? $request->youtube_url : "";
            $requestData['twitter_url'] = isset($request->twitter_url) ? $request->twitter_url : "";
            $requestData['is_private'] = 0;
            $requestData['is_creator'] = 1;
            $requestData['wallet_amount'] = 0;
            $requestData['coin_wallet'] = 0;
            $requestData['earned_coin'] = 0;
            $requestData['bank_name'] = "";
            $requestData['account_no'] = "";
            $requestData['ifsc_no'] = "";
            $requestData['front_id_proof_img'] = "";
            $requestData['back_id_proof_img'] = "";
            $requestData['status'] = 1;

            $user_data = User::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($user_data->id)) {
                return response()->json(array('status' => 200, 'success' => __('Label.data_add_successfully')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('Label.data_not_added')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function edit($id)
    {
        try {
            $params['data'] = User::where('id', $id)->first();

            if ($params['data'] != null) {

                $this->common->imageNameToUrl(array($params['data']), 'image', $this->folder_user);
                $this->common->imageNameToUrl(array($params['data']), 'cover_img', $this->folder_user);
                return view('admin.creator.edit', $params);
            } else {
                return redirect()->back()->with('error', __('Label.page_not_found'));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function update($id, Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'full_name' => 'required|min:2',
                'mobile_number' => [
                    'required',
                    'numeric',
                    Rule::unique('tbl_user')->where(function ($query) use ($request,) {
                        return $query->where('country_code', $request->country_code)
                            ->where('mobile_number', $request->mobile_number)
                            ->where('id', '!=', $request->id);
                    }),
                ],
                'country_code' => 'required',
                'country_name' => 'required',
                'email' => 'required|email|unique:tbl_user,email,' . $id,
                'image' => 'image|mimes:jpeg,png,jpg|max:2048',
                'cover_img' => 'image|mimes:jpeg,png,jpg|max:2048',
                'bio' => 'required',
                'is_verified_at' => 'required',
                'gender' => 'required',
                'date_of_birth' => 'required|date|before_or_equal:today',
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            $requestData = $request->all();

            if (isset($requestData['image'])) {
                $files = $requestData['image'];
                $requestData['image'] = $this->common->saveImage($files, $this->folder_user, "creactor_");

                $this->common->deleteImageToFolder($this->folder_user, basename($requestData['old_image']));
            }
            if (isset($requestData['cover_img'])) {
                $files = $requestData['cover_img'];
                $requestData['cover_img'] = $this->common->saveImage($files, $this->folder_user, "creactor_");

                $this->common->deleteImageToFolder($this->folder_user, basename($requestData['old_cover_image']));
            }
            unset($requestData['old_image'], $requestData['old_cover_image']);

            $requestData['facebook_url'] = isset($request->facebook_url) ? $request->facebook_url : "";
            $requestData['instagram_url'] = isset($request->instagram_url) ? $request->instagram_url : "";
            $requestData['youtube_url'] = isset($request->youtube_url) ? $request->youtube_url : "";
            $requestData['twitter_url'] = isset($request->twitter_url) ? $request->twitter_url : "";
            
            $User_data = User::updateOrCreate(['id' => $requestData['id']], $requestData);
            if (isset($User_data->id)) {
                return response()->json(array('status' => 200, 'success' => __('Label.data_edit_successfully')));
            } else {
                return response()->json(array('status' => 400, 'errors' => __('Label.data_not_updated')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function destroy($id)
    {
        try {
            $data = User::where('id', $id)->first();

            if (isset($data)) {
                $this->common->deleteImageToFolder($this->folder_user, $data['image']);
                $this->common->deleteImageToFolder($this->folder_user, $data['cover_img']);
                $this->common->deleteImageToFolder($this->folder_user, $data['front_id_proof_img']);
                $this->common->deleteImageToFolder($this->folder_user, $data['back_id_proof_img']);
                $data->delete();

                $this->common->delete_all_data_user($id);
            }
            return redirect()->route('creator.index')->with('success', __('Label.data_delete_successfully'));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
}
