<?php

namespace App\Http\Controllers\Assets\Settings\DiscoveryTools;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ApiCredential;
use App\Services\Integrations\KandjiIntegration;
use Exception;
use Illuminate\Support\Facades\Artisan;

/**
 *  Controller Class for MobileIron API Credentials
 */
class KandjiController extends Controller
{
    public function __construct(KandjiIntegration $api)
    {
        $this->service = $api;
    }

    /**
     * Home page of Kandji in setings menu
     *
     * @return [type]
     */
    public function index()
    {
        $credentials = ApiCredential::where('slug', 'kandji')->first();

        if ($credentials) {
            $status = $this->service->checkApiConnection();

            return view('settings.discovery-tools.kandji.index', compact('credentials', 'status'));
        }

        return redirect(route('kandji.create'));
    }

    public function create()
    {
        $credential = ApiCredential::where('slug', 'kandji')->first();

        if ($credential) {
            return redirect('kandji/' . $credential->id . '/edit');
        }

        return view('settings.discovery-tools.kandji.create');
    }

    /**
     * Save the Kandji credantials
     *
     * @param Request $request
     *
     * @return [type]
     */
    public function store(Request $request)
    {
        $request->validate(
            [
                'url'       => 'required',
                'api_key'   => 'required'
            ]
        );

        ApiCredential::create(
            [
                'api_name' => 'Kandji',
                'slug' => 'kandji',
                'url' => rtrim($request->url, "/"),
                'key' => $request->api_key
            ]
        );

        return redirect('/kandji');
    }

    /**
     * Load edit page
     * @param mixed $id
     *
     * @return [type]
     */
    public function edit($id)
    {
        try {
            $credential = ApiCredential::findOrFail($id);

            return view('settings.discovery-tools.kandji.edit', compact('credential'));
        } catch (Exception $e) {
            return redirect(route('kandji.index'))->with('error', 'Something went wrong. Try again later.');
        }
    }

    /**
     * Update the Kandji credentials
     * @param Request $request
     * @param mixed $id
     *
     * @return [type]
     */
    public function update(Request $request, $id)
    {
        try {
            $credential = ApiCredential::findOrFail($id);

            $updateData = [
                'url'       => rtrim($request->url, "/"),
                'user_name' => $request->user_name,
                'password'  => $request->password ? $request->password : $credential->password,
                'key'       => $request->api_key ? $request->api_key : $credential->key,
            ];

            $credential->update($updateData);

            return redirect(route('kandji.index'))->with('message', 'Credentials updated successfully.');
        } catch (Exception $e) {
            return redirect(route('kandji.index'))->with('error', 'Something went wrong. Try again later.');
        }
    }

    /**
     * Import Kandji devices using API using console command
     * @return [type]
     */
    public function manualSync()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $output = Artisan::call('KandjiDevices:sync');

        if ($output) {
            return response()->json(array('status' => 'success', 'message' => 'Kandji manual sync finished.'));
        }

        return response()->json(array('status' => 'error', 'message' => 'Connection failed.'));
    }
}
