<?php

namespace App\Http\Controllers\Admin;

use App\functions;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use App\AdminUser;
use Morilog\Jalali;
use DB;
use Auth;
use SoulDoit\DataTable\SSP;

class AdminsController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if(Auth::user()->role != 'admin')
                abort(404);
            return $next($request);
        });
    }

    public function index(){

        $functions = new \App\functions;
        $admins = \App\AdminUser::select('id','name','email','role','mobile','access','created_at')
            ->latest('created_at')
            ->paginate(10);
        foreach ($admins as $admin) {
            $admin->created_at = Jalali\CalendarUtils::strftime('H:i Y/m/d', strtotime($admin->created_at));
        }

        return view('admin.admins', ['admins'=>$admins]);
    }

    function insert(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required',
            'mobile' => 'required|numeric|mobile',
            'email'=>'required|email',
            'password'=>'required',
        ]);

        if ($validator->fails()) {
            $result = array('status' => false, 'message' => $validator->errors()->first());
            return response()->json($result);
        }

        $user = AdminUser::where('mobile',$request->mobile)->first();
        if (isset($user)) {
            $result = array('status' => false, 'message' => 'این موبایل توسط ادمین دیگری ثبت شده است!');
            return response()->json($result);
        }
        $user = AdminUser::where('email',$request->email)->first();
        if (isset($user)) {
            $result = array('status' => false, 'message' => 'این ایمیل توسط ادمین دیگری ثبت شده است!');
            return response()->json($result);
        }

        DB::beginTransaction();
        try {
            $AdminUser = new AdminUser;
            $AdminUser->mobile = $request->mobile;
            $AdminUser->email = $request->email;
            $AdminUser->name = $request->name;
            $AdminUser->password = bcrypt($request->password);
            $AdminUser->access_orders = $request->access_orders;
            $AdminUser->access_ticket = $request->access_ticket;
            $AdminUser->access_users = $request->access_users;
            $AdminUser->access_settings = $request->access_settings;
            $AdminUser->access_finance = $request->access_finance;
            $AdminUser->access_notification = $request->access_notification;
            $AdminUser->save();

            DB::commit();
            $result = array('status' => true, 'message' => 'ادمین جدید با موفقیت ثبت شد','id'=>$AdminUser->id);
            return response()->json($result);

        } catch (\Exception $e) {
            DB::rollback();
            $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد' . $e);
        }

        return response()->json($result);
    }

    public function single(Request $request){
        $id = $request->id;
        $result = (object) array();
        $result->user = AdminUser::find($request->id);
        $result->CountCardbank = \App\CardBank::where('id_admin',$id)->count();
        $result->CountOrders = \App\Orders::where('id_admin',$id)->count();
        $result->CountTicket = \App\TicketMessage::where('id_admin',$id)->count();
        $result->CountAuthImg = \App\User::where('auth_img_confirm_admin',$id)->count();
        $result->CountLog = \App\AdminLog::where('id_admin',$id)->count();
        $result->LastLogin = \App\AdminLog::where('id_admin',$id)->where('model','login')->orderBy('id','desc')->first();
        if($result->LastLogin)
            $result->LastLogin = Jalali\CalendarUtils::strftime('d F Y - H:i', strtotime($result->LastLogin->created_at));

        $result->LastLog = \App\AdminLog::where('id_admin',$id)->where('model','logout')->orderBy('id','desc')->first();
        if($result->LastLog)
            $result->LastLog = Jalali\CalendarUtils::strftime('d F Y - H:i', strtotime($result->LastLog->created_at));

        return view('admin.admins.admin',['result'=>$result]);
    }
    function edit(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required',
            'mobile' => 'required|numeric|mobile',
            'email'=>'required|email',
        ]);

        if ($validator->fails()) {
            $result = array('status' => false, 'message' => $validator->errors()->first());
            return response()->json($result);
        }

        $user = AdminUser::where('mobile',$request->mobile)->where('id','!=',$request->id)->first();
        if (isset($user)) {
            $result = array('status' => false, 'message' => ' این موبایل توسط ادمین دیگری ثبت شده است! '.$user->name);
            return response()->json($result);
        }
        $user = AdminUser::where('email',$request->email)->where('id','!=',$request->id)->first();
        if (isset($user)) {
            $result = array('status' => false, 'message' => 'این ایمیل توسط ادمین دیگری ثبت شده است!');
            return response()->json($result);
        }

        DB::beginTransaction();
        try {
            $AdminUser = AdminUser::find($request->id);
            $AdminUser->mobile = $request->mobile;
            $AdminUser->email = $request->email;
            $AdminUser->name = $request->name;
            $AdminUser->stock = str_replace(',','',$request->stock);
            if(isset($request->password))
                $AdminUser->password = bcrypt($request->password);
            $AdminUser->access_orders = $request->access_orders;
            $AdminUser->access_ticket = $request->access_ticket;
            $AdminUser->access_users = $request->access_users;
            $AdminUser->access_settings = $request->access_settings;
            $AdminUser->access_finance = $request->access_finance;
            $AdminUser->access_notification = $request->access_notification;
            $AdminUser->save();

            DB::commit();
            $result = array('status' => true, 'message' => 'ادمین با موفقیت ویرایش شد');
            return response()->json($result);

        } catch (\Exception $e) {
            DB::rollback();
            $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد' . $e);
        }

        return response()->json($result);
    }

    public function block(Request $request){
        $validator = \Validator::make($request->all(), [
            'block' => 'required'
        ]);

        if($validator->fails()!=1):
            $user = AdminUser::where('id', $request->id)->update(['access' => $request->block,'access_reason' => $request->reason]);
            if($user){
                $result = array('status' => 'true' , 'messege' => 'با موفقیت تغییر کرد');
            }else
                $result = array('status' => 'false' , 'messege' => 'تغییر امکان پذیر نیست');

        else:
            $result = array('status' => 'false' , 'messege' => 'خطا در ارسال پارامتر');
        endif;
        return response()->json($result);
    }



    public function user_delete(Request $request){

        $user = AdminUser::where('role','!=','admin')->find($request->id);
        if($user):
            try {

                \App\TicketMessage::where('id_admin',$user->id)->update(['id_admin'=>Auth::user()->id]);
                \App\Orders::where('id_admin',$user->id)->update(['id_admin'=>Auth::user()->id]);
                \App\UserFinance::where('id_admin',$user->id)->update(['id_admin'=>Auth::user()->id]);
                \App\CardBank::where('id_admin',$user->id)->update(['id_admin'=>Auth::user()->id]);
                \App\User::where('auth_img_confirm_admin',$user->id)->update(['auth_img_confirm_admin'=>Auth::user()->id]);
                \App\AdminLog::where('id_admin',$user->id)->delete();


                if($user->delete())
                    $result = array('status' => 'true' , 'messege' => 'با موفقیت حذف شد');

            } catch (\Illuminate\Database\QueryException $e) {
                $result = array('status' => 'false' , 'messege' => 'حذف امکان پذیر نیست'.$e->getMessage());
            }
        else:
            $result = array('status' => 'false' , 'messege' => 'حذف ادمین کل امکان پذیر نیست');
        endif;
        return response()->json($result);
    }



    public function LogList(Request $request){

        $functions = new functions;
        if(isset($request->date_start)){
            $request->date_start = $functions->toLatin($request->date_start);
            $request->date_start = Jalali\CalendarUtils::createCarbonFromFormat('Y/m/d H:i', $request->date_start);
        }

        if(isset($request->date_stop)){
            $request->date_stop = $functions->toLatin($request->date_stop);
            $request->date_stop = Jalali\CalendarUtils::createCarbonFromFormat('Y/m/d H:i', $request->date_stop);
        }

        $dt = [
            ['db' => 'id', 'dt' => 0],
            ['db' => 'text', 'dt' => 1],
            ['db' => 'created_at', 'dt' => 2, 'formatter' => function ($value, $model) {
                return  Jalali\CalendarUtils::strftime('d F Y - H:i:s', strtotime($value));;
            }],
        ];


        $my_ssp = (new SSP('\App\AdminLog', $dt))->where(function($query) {

            $query->where('admin_log.id_admin', request()->id);


            if (isset(request()->date_start)) {
                $query->where('admin_log.created_at', '>', request()->date_start);
            }

            if (isset(request()->date_stop)) {
                $query->where('admin_log.created_at', '<', request()->date_stop);
            }
        });

        return response()->json($my_ssp->getDtArr());

    }
}
