<?php

namespace App\Http\Controllers;

use App\Repositories\CompanyOrderRepository;
use Illuminate\Http\Request;

class CompanyOrderController extends Controller {
    public function __construct() {
        $this->middleware('auth:api', ['except' => []]);
    }

    public function index(Request $request) {
        //1. Obtenim query parameters opcionals

        //2. Authorization
        auth()->user()->authorize("super_admin");

        try {
            $orders = CompanyOrderRepository::all();
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($orders, 200);
    }

    public function show(Request $request, $id) {
        try {
            $order = CompanyOrderRepository::find($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        auth()->user()->authorize("company_admin", $order->company->id);

        return response()->json($order, 200);
    }

    public function create(Request $request) {
        auth()->user()->authorize("super_admin");

        try {
            $plan = CompanyOrderRepository::create($request->all());
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($plan, 200);
    }

    public function update(Request $request, $id) {
        auth()->user()->authorize("super_admin");

        try {
            $plan = CompanyOrderRepository::update($request->all(), $id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json($plan, 200);
    }

    public function destroy($id) {
        auth()->user()->authorize("super_admin");

        try {
            CompanyOrderRepository::delete($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return response()->json(["message" => "Ok"], 200);
    }
}
