<?php

namespace App\Http\Controllers;

use App\Models\Betting;
use App\Models\Order;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderController extends Controller
{
    public function Orders()
    {
        $orders = Order::where(['user_id' => Auth::user()->id])->with(['product'])->latest()->get();

        $bettings = Betting::where(['user_id' => Auth::user()->id, 'tab' => 'parity'])->with(['gameId'])->latest()->get();
        $pending_bettings = $bettings->where('status', '=', 0);
        $won_bettings = $bettings->where('status', '=', 1)->where('result', '=', 1);
        $lost_bettings = $bettings->where('status', '=', 1)->where('result', '!=', 1);
        return view('userDashboard.orders', compact('orders', 'bettings', 'pending_bettings', 'won_bettings', 'lost_bettings'));
    }


    public function CreateOrder(Request $request)
    {
        $request->validate([
            'id' => 'required'
        ]);
        $product = Product::where(['id' => $request->id])->first();
        $user = User::where(['id' => Auth::user()->id])->first();
        if ($product->price > $user->amount) {
            return response()->json(['status' => 'error', 'message' => "You don't have required amount in your wallet."]);
        }
        $order = new Order();
        $order->user_id = Auth::user()->id;
        $order->product_id = $request->id;
        $order->amount = $product->price;
        $order->status = "Processing";
        $order->save();
        $user->decrement('amount', $product->price);
        return response()->json(['status' => 'success']);
    }

    // public function Orders()
    // {
    //     $orders = Order::where(['user_id' => Auth::user()->id])->with(['product'])->latest()->get();
    //     return view('userDashboard.orders', compact('orders'));
    // }


    // public function CreateOrder(Request $request)
    // {
    //     $request->validate([
    //         'id' => 'required'
    //     ]);
    //     $product = Product::where(['id' => $request->id])->first();
    //     $user = User::where(['id' => Auth::user()->id])->first();
    //     if($product->price > $user->amount) {
    //         return response()->json(['status' => 'error', 'message' => "You don't have required amount in your wallet." ]);
    //     }
    //     $order = new Order();
    //     $order->user_id = Auth::user()->id;
    //     $order->product_id = $request->id;
    //     $order->amount = $product->price;
    //     $order->status = "Processing";
    //     $order->save();
    //     $user->decrement('amount', $product->price);
    //     return response()->json(['status' => 'success']);
    // }
}
