<?php

namespace App\Http\Controllers;

use App\BoxOrder;
use App\Repositories\BoxOrderLineRepository;
use App\Repositories\BoxOrderRepository;
use App\Repositories\BoxRepository;
use App\Repositories\CompanyRepository;
use Illuminate\Http\Request;

class BoxOrderController extends Controller
{

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

    public function index(Request $request) {
        //1. Query params

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

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

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

    public function show($id) {
        //1. Get parameters
        $box_id = BoxOrderRepository::box($id)->id;
        $user_id = BoxOrderRepository::user($id)->id;

        //2. Authorize
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("box_admin", $box_id);
        }

        //3. Get order
        try {
            $order = BoxOrderRepository::find($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function create(Request $request) {
        //1. Get parameters
        $box_id = $request->box_id;
        $user_id = $request->user_id;

        //2. Authorize
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("box_admin", $box_id);
        }

        //3. Save order
        try {
            $order = BoxOrderRepository::create($request->all());
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function update(Request $request, $id) {
        //1. Get parameters
        $box_id = BoxOrderRepository::box($id)->id;
        $user_id = BoxOrderRepository::user($id)->id;

        //2. Autorizar
        if(!auth()->user()->itsMe($user_id)) {
            auth()->user()->authorize("box_admin", $box_id);
        }

        //3. Update order
        try {
            $order = BoxOrderRepository::update($request->all(), $id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function destroy($id) {
        //1. Get parameters
        $box_id = BoxOrderRepository::box($id)->id;

        //2. Authorize
        auth()->user()->authorize("box_admin", $box_id);

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

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

}
