<?php

namespace App\Http\Controllers;

use App\Repositories\InvoiceRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class InvoiceController 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 {
            $invoices = InvoiceRepository::all();
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

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

    public function show($id) {
        //sense autoritzacio

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

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

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

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

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

    public function exportHTML(Request $request,$id) {
        $invoice = InvoiceRepository::find($id);
        if ( $invoice->box_order!=null ) {
            if ( !auth()->user()->itsMe($invoice->box_order->user_id) ) {
                auth()->user()->authorize("box_admin",$invoice->box_order->box_id);
            }
        } else if ( $invoice->company_order!=null ) {
            auth()->user()->authorize("company_admin",$invoice->company_order->company->id);
        } else throw new \Exception("Esta factura no pertenece a ninguna compra");
        try {
            $invoice = InvoiceRepository::exportHTML($id);
        }
        catch(\Exception $e) { return response()->json(["error" => $e->getMessage()], 400); };

        return $invoice;
    }
}
