<?php

namespace App\Http\Controllers\Instructor;

use App\Http\Controllers\Controller;
use App\Models\InstructorOrder;
use App\Models\Order;
use Datatables;
use Carbon\Carbon;
use Validator;
use Auth;

class OrderController extends Controller
{
    public $curr;

    public function __construct()
    {
        $this->middleware('auth');
  
        $this->curr = \DB::table('currencies')->where('register_id',0)->where('is_default','=',1)->first();
  
    }

    //*** JSON Request
    public function datatables()
    {
        $user = Auth::user();
        $datas = Order::where('register_id',0)->get()->reject(function($item) use ($user){
            if($item->instructororders()->where('user_id','=',$user->id)->count() == 0){
                return true;
            }
            return false;
          });
         //--- Integrating This Collection Into Datatables
         return Datatables::of($datas)
                            ->addColumn('user', function(Order $data) {
                                return $data->user->showName();
                            })
                            ->addColumn('price', function(Order $data) {
                                $user = Auth::user();
                                return $data->currency_sign.round(($data->instructorTotalPrice($user->id) * $data->currency_value),2);
                            })
                            ->addColumn('details', function(Order $data) {
                                $details = '<a href="'. route('instructor.purchase.details',$data->order_number) .'" class="btn btn-primary btn-sm btn-rounded">
                                <i class="fas fa-eye"></i> '.__("Purchase Details").'
                                </a>';
                              return $details;
                            })
                            ->rawColumns(['details'])
                            ->toJson(); //--- Returning Json Data To Client Side
    }

    //*** GET Request
    public function index()
    {
        return view('instructor.purchase.index');
    }

    public function purchasedetails($order_number)
    {
        $user  = Auth::user();
        $order = Order::where('register_id',0)->where('order_number',$order_number)->first();
        $cart  = json_decode($order->cart, true);
        $price = InstructorOrder::totalPrice($order->order_number,$user->id);
        $disns = $order->instructororders()->where('order_number','=',$order->order_number)->where('user_id','=',$user->id)->pluck('charge');
        return view('instructor.purchase.details',compact('user','order','cart','price','disns'));
    }
}
