<?php

namespace App\Http\Controllers\Manager;
use App\Exports\CustomerExport;
use App\Http\Controllers\Controller;
use App\Http\Resources\EmployeeResource;
use App\Models\Customer;
use App\Models\Order;
use App\User;
use App\Http\Requests\Manager\StoreEmployeeRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Facades\Excel;

class ManagerController extends Controller
{
    public function index(){
        $orders = Order::all();
        $wait = $orders->where('state', 1)->count();
        $working = $orders->where('state', 2)->count();
        $done = $orders->where('state', 3)->count();
        $delv = $orders->where('state', 4)->count();
        $canceled = $orders->where('state', 6)->count();
        $stock = $orders->where('state', 7)->count();

        $cost = $orders->whereIn('proccess_type', [1,2,3,4,5])->sum('cost');
        $totalDiscount = $cost - $orders->whereIn('proccess_type', [1,2,3,4])->sum('discount');

        $compcost = $orders->whereIn('proccess_type', [1, 2,3,4])->sum('cost');
        $comdiscount = $compcost - $orders->whereIn('proccess_type', [1, 2,3,4])->sum('discount');

        $mobilecost = $orders->where('proccess_type', 5)->sum('cost');
        $mobildiscount =$mobilecost - $orders->where('proccess_type', 5)->sum('discount');

        $costRec = $orders->where('state', 4)->sum('cost');
        $costRec -= $orders->where('state', 4)->sum('discount');
        $customers = Customer::all()->count();
        $users = User::all();
        $hdcuser = $users->where('type', 2)->count();
        $swcuser = $users->where('type', 3)->count();
        $mobuser = $users->where('type', 4)->count();
        $manageruser = $users->where('type', 5)->count();
        $mobile = \App\Models\Request::where('current_state',3)->where('work_type', 1)->count();
        $swc = \App\Models\Request::where('current_state',2)->where('work_type', 1)->count();
        $hdc = \App\Models\Request::where('current_state',1)->where('work_type', 1)->count();
        return view('manager.index', compact('wait', 'working','done','delv','canceled','stock','cost','totalDiscount',
                        'compcost','comdiscount','mobilecost', 'mobildiscount','hdcuser','swcuser','mobuser','costRec','manageruser','customers', 'mobile', 'swc', 'hdc'));
    }

    public function employees(){
        return view('manager.employees.index');
    }

    public function employeesData(){
        return EmployeeResource::collection(User::where('type', '!=', 1)->orderBy('created_at', 'desc')->get());
    }

    public function storeEmployee(StoreEmployeeRequest $storeEmployeeRequest)
    {
//        return $storeEmployeeRequest;
        $validated = $storeEmployeeRequest->validated();
        $validated['password'] = Hash::make($storeEmployeeRequest->password);
        if($validated){
            User::create(array_merge($validated, [
                'joined_date' => $storeEmployeeRequest->joinedDate,
                'phone' => $storeEmployeeRequest->phone,
                'notice' => $storeEmployeeRequest->notice
            ]));
        }
        return $this->employeesData();
    }

    public function deleteEmployee(Request $request){
        $user = User::findOrFail($request->id);
        if($user) {
            $user->isEnabled =!$user->isEnabled ;
            $user->save();
            return response()->json(['message' => 'ok'], 201);
        }
         abort(302);
    }


    public function viewDetails(Request $request){
        $emp = User::where('id', $request->id)->first();
        $order = Order::all();
        $rec_ord = $order->where('created_employee', $emp->id)->count();
        $delv_ord = Order::where('created_employee', $emp->id)->orWhere('updated_employee', $emp->id)->where('state', 4)->count();

        //
        $rec_req = $emp->requests->count();
        $delv_req = \App\Models\Request::where('latest_updated_user', $emp->id)->where('work_type', 1)->count();
        if($emp->type === 2){
            $waited = $order->where('state', 1)->whereIn('proccess_type', [1, 3])->count();
        }elseif ($emp->type === 3){
            $waited = $order->where('state', 1)->whereIn('proccess_type', [2, 4])->count();
        } else {
            $waited = $order->where('state', 1)->where('proccess_type', 5)->count();
        }

        return response()->json([
            'emp' => $emp,
            'rec' => $rec_ord,
            'delv' => $delv_ord,
            'rec_req' => $rec_req,
            'delv_req'=> $delv_req,
            'waited' => $waited
        ], 200);
    }


    public function editEmployee(StoreEmployeeRequest $storeEmployeeRequest){
        $employee = User::findOrFail($storeEmployeeRequest->id);
        if($storeEmployeeRequest->filled('password')){
        }
        $data = [
            'name' => $storeEmployeeRequest->name,
            'type' => $storeEmployeeRequest->type,
            'joined_date' => $storeEmployeeRequest->joinedDate,
            'phone' => $storeEmployeeRequest->phone,
            'notice' => $storeEmployeeRequest->notice
        ];
        if($storeEmployeeRequest->filled('password')){
            $data['password']=  Hash::make($storeEmployeeRequest->password) ;
        }
        $employee = $employee->update($data);
        if($employee){
            return response()->json(['message' => 'ok'], 201);
        }
    }

    // *******************************Orders********************************

    public function ordersPage(){
        return view('manager.orders.orders');
    }
    public function getOrders(Request $request){
        if($request->pageState == 0){
            $data = Order::with('employee')
                ->with(['updatedEmployee' => function($q) {
                    return $q->select('id', 'name');
                }])
                ->with('canceledOrder')
                ->with('customer')
                ->with('customer.device')
                ->with('requests.user')
                ->latest()
                ->paginate(8);
        } else{
            // return results based on order state
            $data = Order::where('state', $request->pageState)
                ->with(['updatedEmployee' => function($q) {
                   return $q->select('id', 'name');
                }])
                ->with('employee')
                ->with('canceledOrder')
                ->with('customer')
                ->with('customer.device')
                ->with('requests.user')
                ->paginate(8);
        }
        return $data;
    }

    //Search name phone
    public function getSearchedOrders(Request $request){
        $pageState = $request->pageState  ? [$request->pageState] : [1, 2, 3, 4, 6, 7] ;
        $search = $request->search;
        $searchResult = Customer::whereHas('order', function($q) use($pageState)  {
            $q->whereIn('state', $pageState);
        })
            ->where('name', 'LIKE', "%{$search}%")
            ->orWhere('phone', 'LIKE', "%{$search}%")
            ->with('order.employee')
            ->with('device')
            ->with('order.canceledOrder')
            ->paginate(10);
        return $searchResult;
    }

    // view order details
    public function viewOrderDetails(Request $request){
        $order = Order::where('id', $request->id)
            ->with('stockNotes')
            ->with('canceledOrder')
            ->with('employee')
            ->with('updatedEmployee')
            ->with('customer.device')
            ->with('requests.user')
            ->first();
        return $order;
    }

    public function setting(Request $request){

        $user = Auth::user();
        if($request->isMethod('POST')){
            $request->validate([
                'name' => 'required',
                'old_password' => 'required',
                'password' => 'confirmed',
            ],[
                'name.required' => 'إسم مدير النظام مطلوب',
                'old_password.required' => 'يجب إدخال كلمة المرور القديمة',
                'password.confirmed' => 'يجب أن تكون كلمة المرور الجديدة مطابقة',
            ]);
                if (Hash::check($request->old_password, $user->password)) {
                    if(is_null($request->password)){
                        $user->fill([
                            'name' => $request->name
                        ])->save();
                    }else {
                        $user->fill([
                            'password' => Hash::make($request->password),
                            'name' => $request->name
                        ])->save();
                    }

                \session()->flash('success', 'تم تحديث البيانات بنجاح');
                return redirect()->back();
            } else {
                \session()->flash('error', 'خطأ');
                return redirect()->back();
            }
        }else
        return view('manager.setting.profile', ['user' => $user->name]);
    }

    public function excel(){

        return Excel::download(new CustomerExport(), 'customers.xlsx');
    }
}
