<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\OrderResource;

class OrderController extends Controller
{
    //
    public function index(Request $request){

        $user = $request->session()->get('user');
//        return $user;
        $list = $request->header('list');

        if($list != 'all'){
            //Get orders based on user ownership
            $orders = Order::where('assigned_to', $user->agent_id)->get();
        } else {

            //Get orders based on company ownership
            $orders = Order::where('company_id', $user->company_id)->get();
        }

//        return $orders;
//        return OrderResource::collection($orders);
        return OrderResource::collection($orders);


    }

    public function show(Order $order, Request $request){

        $user = $request->session()->get('user');

//        return $user;
        if ($order->assigned_to != $user->agent_id || $order->company_id != $user->company_id) {
            return response()->json(['message' => 'Order Not Found.'], 401);
        }

        return new OrderResource($order);


    }

}
