<?php


namespace Mamad\Order\Repository;



use Illuminate\Support\Facades\DB;
use Mamad\Order\Models\Order;

class OrderRepository
{
    public static function find($id)
    {
        return Order::find($id);
    }

    public static function user_find_order($id,$user=null){
        if(!$user) $user=auth()->user();

        return $user->orders()->findOrFail($id);
    }
    public static function user_all_orders($user=null){
        if(!$user) $user=auth()->user();
        return $user->orders()->orderByDesc("created_at")->get();
    }
    public static function get_all_orders_by_status($status){
        return Order::query()->where("status",$status)->orderByDesc("created_at")->paginate(15);
    }

    public static function get_all_orders()
    {
        return Order::query()->orderByDesc("created_at")->paginate(10);
    }

    public static function getOrderByPeriod($start, $end){
        return Order::query()
            ->whereDate('created_at', '<=', $start)
            ->whereDate('created_at', '>=', $end)
            ->count();
    }
    public static function getOrdersByDays($date)
    {
        return Order::query()
            ->whereDate('created_at', $date)
            ->count();
    }
    public static function getAllCount()
    {
        return Order::query()->count();
    }
    public static function getDailySummery(\Illuminate\Support\Collection $dates, $seller_id = null)
    {
        $query = Order::query()
            ->where('created_at', '>', $dates->keys()->first())
            ->groupBy('date')
            ->orderBy('date');
//
//        if (!is_null($seller_id)) {
//            $query->where('seller_id', $seller_id);
//        }

        return $query->get([
            DB::raw('DATE(created_at) as date'),
            DB::raw('COUNT(id) as total'),
        ]);

    }
    public static function admin_add_order($request)
    {
        return Order::create([
            "user_id"=>$request["user_id"],
            "products_id"=>$request["products_id"],
            "status"=>$request["status"],
            "price"=>$request["price"],
        ]);
    }




    public static function admin_edit_order(Order $order,$request)
    {
        return $order->update([
            "user_id"=>$request["user_id"],
            "products_id"=>$request["products_id"],
            "status"=>$request["status"],
            "price"=>$request["price"],
        ]);
    }

    public static function destroy($id)
    {
        Order::destroy($id);
    }




    public static function add_order($request,$status="pending")
    {
        return Order::create([
            "user_id"=>$request["user_id"],
            "price"=>$request["price"],
            "products_id"=>$request["products_id"],
            "status"=>$status,
            "payment_type"=>$request["payment_type"],

        ]);
    }

    public static function update_status(Order $order,$status)
    {
        return $order->update([
            "status"=>$status,
        ]);
    }
}
