<?php

namespace App\Http\Controllers;
use anlutro\LaravelSettings\Facade as Setting;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\UserWallet;
use App\Models\OrderStatus;
use App\Models\OrderProductsDelivery;
use App\Models\User;
use App\Models\OrderProduct;
use App\Models\OrderCancelRequest;
use App\Models\UserAuthLogin;
use App\Models\Notification;
use App\Models\Driver;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Response;
use App\Exports\OrdersExport;
use App\Exports\RevenueExport;
use Maatwebsite\Excel\Facades\Excel;
use DB;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = DB::table('order')->get();
        $filter = array();
        $filter['user'] = User::where('id','!=',1)->where('type','user')->get();
        $filter['order_status'] = OrderStatus::get();
        return view('orders.index',compact('data'))->with('filter',$filter);
    }

    public function makeOrder(Request $request)
    {

        $input = $request->all();
        $id = $input['user_id'];
        $no_of_bottles = $input['number_of_bottles'];

        $data = ['user_id' => $id,'no_of_bottles'=>$no_of_bottles,'order_date'=>strtotime("now")];

        DB::table('order')->insert($data);

        return redirect(route('orders.index'));


    }

     public function assignOrder(Request $request)
    {

        $input = $request->all();
        $order_id = $input['order_id'];
        $driver = $input['driver'];

        $data = ['driver_id' => $driver,'order_status'=>'Order Received','assigned_date'=>strtotime("now")];

        DB::table('order')->where('id',$order_id)->update($data);

        return redirect(route('orders.index'));


    }

     public function assignDriver($id)
    {
        $order = DB::table('order')->where('id',$id)->get();
    
        return view('orders.assignDriver',compact('order'));
    }


    /**
     * Display the specified Order.
     *
     * @param int $id
     */

    public function show(Request $request, $id)
    {
        $data = Order::where('id',$id)->with('product_orders')->with('order_status')->with('payment')->with('delivery_address')->with('time_slots')->first();
        if (empty($data)) {
            Session::flash('error', 'Order not found!');
            return redirect(route('orders.index'));
        }
        
        $total_wallet = UserWallet::getWalletbalance($data->user_id);
        $orderStatus = OrderStatus::pluck('status', 'id');
        
        return view('orders.show', compact('data'))->with("total_wallet",$total_wallet)->with("orderStatus",$orderStatus);
    }

    public function edit(Request $request, $id)
    {
        $data = Order::where('id',$id)->with('product_orders')->with('order_status')->with('payment')->with('delivery_address')->with('time_slots')->first();
        if (empty($data)) {
            Session::flash('error', 'Order not found!');
            return redirect(route('orders.index'));
        }
        
        $total_wallet = UserWallet::getWalletbalance($data->user_id);
        $orderStatus = OrderStatus::pluck('status', 'id');

        return view('orders.edit', compact('data'))->with("total_wallet",$total_wallet)->with("orderStatus",$orderStatus);
    }

    public function update(Request $request, $id)
    {
        $post = $request->all();
        
        $data = Order::find($id);
        $input = array(
            'order_status_id' => $post['order_status_id'],
            'updated_at' => date("Y-m-d H:i:s"),
        );
        $data->update($input);
        
        $key = setting('fcm_key');

        $notificationPost = array(
            'user_id' => $data->user_id,
            'image' => 'en',
            'title' => "Order Placed",
            'message' => "Order Place successfully.",
            'created_at' => date("Y-m-d H:i:s"),
            'read_status' => 0
        );
        Notification::insert($notificationPost);
            
        $tokens = array();
        $users = UserAuthLogin::where('user_id',$data->user_id)->get();
        if(count($users)>0){
            foreach ($users as $row) {
                if($row->device_token!=null){
                    array_push($tokens,$row->device_token);
                }   
            }
        }
        \Helpers::sendNotification($tokens,"Order Place successfully.","Order Placed",$key);
            
        Session::flash('success', 'Order status updated successfully!'); 
        return redirect()->route('orders.index')
                        ->with('success','Order status updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Order::find($id)->delete();
        return redirect()->route('orders.index')
                        ->with('success','Order deleted successfully');
    }


    /**
     * Display a listing of the delivery.
     *
     * @return \Illuminate\Http\Response
     */
    public function delivery(Request $request)
    {
        $post = $request->all();
        $data = OrderProductsDelivery::getLists($post);
        $filter['user'] = User::where('id','!=',1)->where('type','user')->get();
        $filter['order_status'] = OrderStatus::get();
        $filter['drivers'] = User::where('type','driver')->where('status',1)->get();
        return view('orders.delivery',compact('data'))->with('filter',$filter);
    }

    /**
     * Update the specified Order in storage.
     *
     * @param int $id
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateOrderDeliveryStatus(Request $request)
    {
        $input = $request->all();
        $id = $input['order_item_id'];
        $oldOrder = OrderProductsDelivery::where('id',$id)->first();
        if (empty($oldOrder)) {
            return $this->sendError('Order not found');
        }
        
        try {
            $orderPost = array(
                'order_status_id' => $input['order_status_id']
            );
            OrderProductsDelivery::where('id',$id)->update($orderPost);

            $key = setting('fcm_key');

            $notificationPost = array(
                'user_id' => $oldOrder->user_id,
                'image' => 'en',
                'title' => "Order Placed",
                'message' => "Order Place successfully.",
                'created_at' => date("Y-m-d H:i:s"),
                'read_status' => 0
            );
            Notification::insert($notificationPost);
                
            $tokens = array();
            $users = UserAuthLogin::where('user_id',$oldOrder->user_id)->get();
            if(count($users)>0){
                foreach ($users as $row) {
                    if($row->device_token!=null){
                        array_push($tokens,$row->device_token);
                    }   
                }
            }
            \Helpers::sendNotification($tokens,"Order Place successfully.","Order Placed",$key);

        } catch (ValidatorException $e) {
            return $this->sendError($e->getMessage());
        }

        return $this->sendResponse([],"Status updated successfully.");
    }

    public function assignDriverForDeliver(Request $request)
    {
        $input = $request->all();
        $id = $input['order_item_id'];
        $oldOrder = OrderProductsDelivery::where('id',$id)->first();
        if (empty($oldOrder)) {
            return $this->sendError('Order not found');
        }
        
        try {
            $orderPost = array(
                'driver_id' => $input['driver_id']
            );
            OrderProductsDelivery::where('id',$id)->update($orderPost);

            $key = setting('fcm_key');

            $notificationPost = array(
                'user_id' => $input['driver_id'],
                'image' => 'en',
                'title' => "Order Assigned",
                'message' => "Order Assigned successfully.",
                'created_at' => date("Y-m-d H:i:s"),
                'read_status' => 0
            );
            Notification::insert($notificationPost);
                
            $tokens = array();
            $users = UserAuthLogin::where('user_id',$input['driver_id'])->get();
            if(count($users)>0){
                foreach ($users as $row) {
                    if($row->device_token!=null){
                        array_push($tokens,$row->device_token);
                    }   
                }
            }
            \Helpers::sendNotification($tokens,"Order Assigned successfully.","Order Assigned",$key);

        } catch (ValidatorException $e) {
            return $this->sendError($e->getMessage());
        }

        return $this->sendResponse([],"Status updated successfully.");
    }

    public function bulkAssignDriverForDeliver(Request $request)
    {
        $input = $request->all();
        $id = explode(",",$input['order_item_id']);
        // $oldOrder = OrderProductsDelivery::where('id',$id)->first();
        // if (empty($oldOrder)) {
        //     return $this->sendError('Order not found');
        // }
        
        try {
            $orderPost = array(
                'driver_id' => $input['driver_id']
            );
            OrderProductsDelivery::whereIn('id',$id)->update($orderPost);

            $key = setting('fcm_key');

            $notificationPost = array(
                'user_id' => $input['driver_id'],
                'image' => 'en',
                'title' => "Order Assigned",
                'message' => "Order Assigned successfully.",
                'created_at' => date("Y-m-d H:i:s"),
                'read_status' => 0
            );
            Notification::insert($notificationPost);
                
            $tokens = array();
            $users = UserAuthLogin::where('user_id',$input['driver_id'])->get();
            if(count($users)>0){
                foreach ($users as $row) {
                    if($row->device_token!=null){
                        array_push($tokens,$row->device_token);
                    }   
                }
            }
            \Helpers::sendNotification($tokens,"Order Assigned successfully.","Order Assigned",$key);

        } catch (ValidatorException $e) {
            return $this->sendError($e->getMessage());
        }

        return $this->sendResponse([],"Status updated successfully.");
    }

    /**
     * Display a listing of the revenue.
     *
     * @return \Illuminate\Http\Response
     */
    public function revenue(Request $request)
    {
        $post = $request->all();
        $data = OrderProductsDelivery::getReport($post);
        return view('orders.revenue',compact('data'));
    }

    /**
     * Display a listing of the revenue.
     *
     * @return \Illuminate\Http\Response
     */
    public function activeSubscription(Request $request)
    {
        $post = $request->all();
        $data = OrderProduct::getActiveSubscrpition($post);
        return view('orders.active_subscription',compact('data'));
    }

    public function export() 
    {
        return Excel::download(new OrdersExport, 'Orders '. date("d M Y h i s A").'.csv', \Maatwebsite\Excel\Excel::CSV);
    }

    public function exportRevenueReport(Request $request) 
    {
        return Excel::download(new RevenueExport, 'Revenue Report '. date("d M Y h i s A").'.xlsx');
    }

    public function cancelOrderRequest(Request $request)
    {
        $data = OrderCancelRequest::getLists();
        $filter = array();
        $filter['user'] = User::where('id','!=',1)->where('type','user')->get();
        return view('orders.cancelrequest.index',compact('data'))->with('filter',$filter);
    }

    public function declinedOrderRequest($id)
    {
        OrderCancelRequest::where('id',$id)->update(array('status'=>2,'updated_at' => date("Y-m-d H:i:s")));
        Session::flash('success', 'Status updated successfully');
        return redirect()->back()->with('message','Status updated successfully!');
    }

    public function approvedOrderRequest($id)
    {
        $data = OrderCancelRequest::find($id);
        $postUpdate = array(
            'status'=>1,
            'updated_at' => date("Y-m-d H:i:s")
        );
        if($data->order){
            if($data->order->payment_method!='cash'){
                $totalWalletAmount = 0;
                $productsDelivery = OrderProductsDelivery::where('order_status_id','<',5)->where('delivery_date','>=',date("Y-m-d"))->where('order_id',$data->order_id)->with('product_orders')->get();
                foreach ($productsDelivery as $row) {
                    if($row->product_orders){
                        $totalWalletAmount = $totalWalletAmount + $row->product_orders->per_delivery_amount;
                    }
                    OrderProductsDelivery::where('id',$row->id)->update(array('order_status_id'=>6,'updated_at' => date("Y-m-d H:i:s")));
                }
                $postUpdate['refund_amount'] = $totalWalletAmount;
                if($totalWalletAmount>0){
                    $postData = array(
                        'order_id'=>$data->order_id,
                        'user_id' => $data->user_id,
                        'description' => 'Your order has been cancelled and refund credited',
                        'type' => 'credit',
                        'amount' => $totalWalletAmount,
                        'created_at' => date("Y-m-d H:i:s")
                    );
                    UserWallet::insert($postData);
                    $postUpdate['refund_status'] = 1;
                }
            }
        }
        
        OrderCancelRequest::where('id',$id)->update($postUpdate);

        //Update order status
        // $orderUpdate = array(
        //     'order_status_id'=> 6,
        //     'updated_at' => date("Y-m-d H:i:s")
        // );
        // Order::where('id',$data->order_id)->update($orderUpdate);

        Session::flash('success', 'Status updated successfully');
        return redirect()->back()->with('message','Status updated successfully!');
    }
}