<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Order;
use App\Models\Closer;
use App\Models\Coupon;
use App\Models\ProductCoupon;
use App\Models\BusinessInformation;
use App\Models\LoginActivity;
use App\Traits\OrderTrait;
use Illuminate\Support\Facades\Validator;
use DataTables;
use PDF;
use Response;



class AdminController extends Controller
{
    use OrderTrait;

    public function index(){

        $orders = Order::all();
        $countorder  = $orders->count();
        $users = User::where('roles','0')->get();
        $countuser = $users->count();

        $readytopay = Order::pluck('client_id');

        $businessreadytopay = BusinessInformation::whereNotIn('client_id', $readytopay)
                                    ->get();
        $rtp = $businessreadytopay->count();
        $business = BusinessInformation::all();
        $countbusiness = $business->count();
        return view('admin.admindashboard')->with(['orders'=>$countorder, 'users' => $countuser,'business' => $countbusiness,'readytopay'=>$rtp]);
    }
    public function userslist(Request $request){
        if ($request->ajax()) {
            $data = User::where('roles','=','0')
            ->orderBy('id', 'DESC') 
            ->get();
            return Datatables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function($row){

                   $btn = '<a href="single-user/'.$row->id.'" class="edit btn btn-primary btn-sm">View</a>';

                    return $btn;
            })
            ->rawColumns(['action'])
            ->make(true);
        }
        return view('admin.users');
    }

    public function singleuser(Request $request){
        $singleuser = User::where('id',$request->id)->get();
        return view('admin.viewuser')->with('singleuser',$singleuser);
    }

    public function add_user(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'first_name' => 'required',
            'last_name' => 'required',
            'email'=>['required','unique:users'],
            'phone'=>['required','unique:users'],
            'address' => ['required', 'string'],
            'password' => ['required', 'string', 'min:5', 'confirmed'],
        ]);
          if ($validator->fails()){
            return redirect('admin/allusers')->withErrors($validator)->withInput();
        }
        else
        {
            $user  = User::create([
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'email' => $request->email,
                'phone' => $request->phone,
                'address' => $request->address,
                'password' => Hash::make($request->password),
                'isVerified'=>'1'
            ]);
            return redirect('admin/allusers')->with('success','User Added Successfully');
        }
    }

    public function update_user(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'first_name' => 'required',
            'last_name' => 'required',
            'phone'=>'required',
        ]);

        if ($validator->fails()){
            return redirect('admin/single-user/'.$request->userid)->withErrors($validator)->withInput();
        }
        else
        {
            $updateuser = User::where('id',$request->userid)
            ->update([
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'phone'=> $request->phone,
                'address' => $request->address,
            ]);
            return redirect('admin/single-user/'.$request->userid)->with('success','User updated successfully.');
        }
    }

    public function orderslist(Request $request){

        if ($request->ajax()) {
            $orders = Order::select()
                        ->join('business_information', 'business_information.client_id', '=', 'orders.client_id')
                        ->join('users', 'users.id', '=', 'business_information.client_id')
                        ->join('products','products.id','=','business_information.pid')
                        ->get('orders.payment_method','orders.id AS orderid','orders.ordernumber','orders.order_status', 'orders.client_id AS clientid', 'orders.product_id AS productid','orders.created_at','orders.invoice_id','business_information.bname AS bname','business_information.bemail AS bemail','business_information.bphone AS bphone', 'business_information.baddress AS baddress','business_information.website_url', 'business_information.radius_address','business_information.radius','closers.closer_name AS closer_name','business_information.services AS services','products.productname AS productname','products.productdescription','users.first_name','users.last_name');
            // dd($orders);
            return Datatables::of($orders)
            ->addIndexColumn()
            ->addColumn('action', function($row){
                   $btn = '<a href="view-order/'.$row->client_id.'" target="_blank" class="edit btn btn-primary text-white btn-sm">View</a>';
                    return $btn;
            })
            ->rawColumns(['action'])
            ->make(true);
        }
        return view('admin.orderslist');
    }

    public function order_invoice(Request $request){
     
        $orderdetail = $this->get_business_order($request->id);
            foreach($orderdetail as $order)
            {
                $orderid  = $order->ordernumber;
            }   
            $id = [
                'id' => $orderid,
            ];

            $data = [
                'title' => 'Order Invoice',
                'date' => date('m/d/Y'),
                'orderdetail' => $orderdetail
            ];     

            $pdf = PDF::loadView('admin.orderview', $data);
            return $pdf->stream('Order#'.$id["id"].'.pdf');

    }

public function invoice(){
    return view('admin.orderview');
}

public function loginactivity(Request $request){

    if ($request->ajax()) {
        $loginactivity = LoginActivity::select()
                    ->join('users', 'users.id', '=','login_activities.users_id')
                    ->select('users.first_name AS fname','users.last_name AS lname','users.email AS email','login_activities.created_at AS login_date','login_activities.ip_address AS ip_address','login_activities.id AS loginid')
                    ->get();   
                    return Datatables::of($loginactivity)
                    ->make(true);
    }
    return view('admin.loginactivity');
    }

    public function closerslist(Request $request){
        

        $orderedUserIds = Order::pluck('client_id');

        $businessUserIds = BusinessInformation::pluck('client_id');

        $excludedUserIds = $orderedUserIds->merge($businessUserIds);

        $usersWithoutOrdersAndBusiness = User::whereNotIn('id', $excludedUserIds)
                                            ->where('roles', '0')
                                            ->get();

        if ($request->ajax()) {

            $data =User::select(
                                'users.id AS userid', 
                                'closers.id AS closerid', 
                                'users.first_name', 
                                'users.last_name', 
                                'users.email'
                            )
                            ->join('closers', 'closers.user_id', '=', 'users.id')
                            ->where('users.roles', '=', 2)
                            ->get();
                    return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){

                   $btn = '<a href="single-user/'.$row->userid.'" class="edit btn btn-primary btn-sm">View</a>';
                   $couponbtn = '<a href="closer-coupons/'.$row->userid.'" class="edit btn btn-success btn-sm">Coupons</a>';

                   return $btn.' '.$couponbtn;
            })
            ->rawColumns(['action'])
            ->make(true);
        
        }
        return view('admin.closers')->with('users',$usersWithoutOrdersAndBusiness);
    }

    public function change_to_closer(Request $request)
    {
        $business = BusinessInformation::where('client_id',$request->userid)->exists();
        if($business)
        {
            return redirect('admin/all-closers')->with('error','Cannot change this user to closer.');
        }
        else{
                $closercheck = Closer::where('id',$request->closer_id)->exists();
                if($closercheck){
                    return redirect('admin/all-closers')->with('error','Please use unique ID for closer.');
                }
                else{
                    $closeruser = User::where('id',$request->userid)->get();
                    foreach($closeruser as $cuser)
                    {
                        $firstname = $cuser->first_name;
                        $lastname = $cuser->last_name;
                    }
                    $closer = [
                        'id'=> $request->closer_id,
                        'closer_name' => $firstname.' '.$lastname,
                        'user_id' => $request->userid
                    ];    
                    Closer::create($closer);
                    $user = User::where('id',$request->userid)
                    ->update([
                        'roles' => '2',
                    ]);
                    return redirect('admin/all-closers')->with('closer',$firstname.'  changed to closer Successfully!!!');
                }   
        }
    }

    public function closer_coupons($id)
    {
            $closer = Coupon::select()
                        ->join('closers','closers.user_id','=','coupons.closer_id')
                        ->where('closer_id','=',$id)
                        ->select('closers.closer_name','closers.id','coupons.code','coupons.discount_price')
                        ->get();
        
            return view('admin.closercoupons')->with('closer',$closer);
    }

    public function coupons_list(Request $request)
    {
        if ($request->ajax()) {

            $data = Coupon::select('coupons.id', 'closers.closer_name', 'coupons.discount_price', 'coupons.code')
            ->join('closers', 'closers.user_id', '=', 'coupons.closer_id')
            ->leftJoin('product_coupons', 'product_coupons.coupon_id', '=', 'coupons.id')
            ->selectRaw('COUNT(product_coupons.id) as usage_count')
            ->groupBy('coupons.id', 'closers.closer_name', 'coupons.discount_price', 'coupons.code')
            ->get();
                return Datatables::of($data)
                ->make(true);
        }
        return view('admin.coupons');
    }

    public function business_profiles(Request $request)
    {
        if ($request->ajax()) {
            $data = BusinessInformation::select()
                ->join('closers', 'closers.id', '=', 'business_information.closerid')
                ->join('products', 'products.id', '=','business_information.pid')
                ->select('business_information.id AS bid','business_information.radius AS bradius','business_information.*','closers.*','products.*')
                ->get(); 
                return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
    
                       $btn = '<a target="_blank" href="single-business-profile/'.$row->bid.'" class="edit btn btn-primary btn-sm">View</a>';
                       return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
        return view('admin.businessprofiles');
    }

    public function single_business_profile($bid)
    {
        $business = BusinessInformation::select()
                                    ->join('products','products.id','=','business_information.pid')
                                    ->join('closers','closers.id','=','business_information.closerid')
                                    ->join('users','users.id','=','business_information.client_id')
                                    ->where('business_information.id','=',$bid)
                                    ->select('business_information.*',
                                             'business_information.radius AS bradius',
                                             'closers.*',
                                             'users.*',
                                             'products.*'
                                    )
                                    ->get();
        return view('admin.single-business-profile')->with('business',$business);
    }
}

