<?php

namespace App\Http\Controllers\Assets\Settings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ApiCredential;
use App\Services\Asset\AsnPresidioIntegration;

class PresidioController extends Controller
{
    public $service;

    public function __construct(AsnPresidioIntegration $service)
    {
        $this->service = $service;
    }

    /**
     * SHows ASN Presidio settings page
     *
     * @return view
     */
    public function index()
    {
        $credentials = ApiCredential::whereSlug('asn_presidio')->first();
        $status = 0;
        if ($credentials) {
            $status = $this->service->checkConnection();

            return view('settings.presidio.index', compact('credentials', 'status'));
        }

        return redirect()->route('asn-presidio-settings.create');
    }

    /**
     * Shows Presidio API credentails create page
     *
     * @return view
     */
    public function create()
    {
        return view('settings.presidio.create');
    }

    /**
     * Stores Presidio API credentails
     *
     * @param  mixed $request
     * @return response
     */
    public function store(Request $request)
    {
        $request->validate([
            'user_name' => 'required',
            'password' => 'required',
            'url' => 'required',
        ]);

        ApiCredential::create([
            'api_name'  => 'ASN Presidio',
            'slug'      => 'asn_presidio',
            'url'       => add_slash_at_end($request->url),
            'user_name' => $request->user_name,
            'password'  => $request->password,
        ]);

        return redirect()->route('presidio-settings')->with('message', 'Created successfully');
    }

    /**
     * Shows Presidio API credentails edit page
     *
     * @return view
     */
    public function edit($id)
    {
        $credential = ApiCredential::find($id);

        return view('settings.presidio.edit', compact('credential'));
    }

    /**
     * Update Presidio API credentails
     *
     * @param  mixed $request
     * @return response
     */
    public function update(Request $request, $id)
    {
        $presidioCredential = ApiCredential::find($id);

        $presidioCredential->update([
            'url'       => add_slash_at_end($request->url),
            'user_name' => $request->user_name ?? $presidioCredential->user_name,
            'password'  => $request->password ?? $presidioCredential->password,
        ]);

        return redirect()->route('presidio-settings')->with('message', 'Updated successfully');
    }
}
