<?php

namespace App\Http\Controllers;

use App\PaymentType;
use App\Repositories\PaymentTypeRepository;
use Illuminate\Http\Request;

class PaymentTypeController extends Controller
{

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

    public function index(Request $request) {
        //1. Params - No en necessita
        $active = $request->query("active") == "Y";

        //2. Authorization
        //sense autoritzacio

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

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

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

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

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

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

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

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

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

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

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

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

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

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