<?php

namespace App\Http\Controllers\Assets\Settings;

use App\Http\Controllers\Controller;
use App\Models\SlackNotificationCredential;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;

class SlackNotificationCredentialsController extends Controller
{

    /**
     * settings page for the integration
     * 
     * @return object
     */
    public function index()
    {
        $credentials = SlackNotificationCredential::get();
        return view('settings.slack-notification.index', compact('credentials'));
    }

    /**
     * edit page for credentials
     * 
     * @param int $id
     * 
     * @return object
     */
    public function edit($id)
    {
        $credential = SlackNotificationCredential::findOrFail($id);
        return view('settings.slack-notification.edit', compact('credential'));
    }

    /**
     * update the credentials
     * 
     * @param Request $request
     * @param int $id
     * 
     * @return object
     */
    public function update(Request $request, $id)
    {
        try {
            $credential = SlackNotificationCredential::findOrFail($id);
            $credential->update([
                'webhook_url' => $request->webhook_url
            ]);

            return redirect('/slack-notification-credentials')->with('message', 'Webhook URL updated successfully');
        } catch (Exception $e) {
            Log::error('Slack manual update error : ' . $e->getMessage());

            return redirect('/slack-notification-credentials')->with('error', 'Something went wrong. Try again later');
        }
    }

    /**
     * Send notification manually 
     * 
     * @return object
     */
    public function manualNotify()
    {
        $response = true;

        try {
            Artisan::call('TerminatedUsersStillAssignedToAssets:notify');
            $terminationNotifyResponse = Artisan::output();
            $terminationNotifyResponseData = json_decode($terminationNotifyResponse, true);

            if ($terminationNotifyResponseData['status'] != 'success') {
                $response = false;
            }

            Artisan::call('NewHiresWithZeroAssets:notify');
            $newHiresResponse = Artisan::output();
            $newHiresResponseData = json_decode($newHiresResponse, true);

            if ($newHiresResponseData['status'] != 'success') {
                $response = false;
            }
        } catch (Exception $e) {
            dd($e->getMessage());
            Log::error('Slack manual notification error : ' . $e->getMessage());
            $response = false;
        }

        return response()->json($response);
    }
}
