<?php

namespace App\Http\Controllers\Assets\Settings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ApiCredential;
use Exception;

class FedexTrackingController extends Controller
{
    public function index()
    {
        $credentials = ApiCredential::where('slug', 'fedex_tracking')->first();

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

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

        return redirect()->route('fedex-tracking-api.create');
    }

    public function create()
    {
        $credential = ApiCredential::where('slug', 'fedex_tracking')->first();
        if ($credential) {
            return redirect('fedex-tracking-api/' . $credential->id . '/edit');
        }
        return view('settings.fedex.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'user_name' => 'required',
            'password' => 'required',
            'url' => 'required',
            'key' => 'required',
        ]);

        ApiCredential::create([
            'api_name'  => 'Fedex Tracking',
            'slug'      => 'fedex_tracking',
            'url'       => $request->url,
            'user_name' => $request->user_name,
            'key'       => $request->key,
            'password'  => $request->password,
            'account_no' => $request->account_no,
            'meter_no'  => $request->meter_no,
        ]);

        return redirect()->route('fedex-tracking-api.index')->with('message', __('message.created'));
    }

    public function edit($id)
    {
        try {
            $credential = ApiCredential::findOrFail($id);
            return view('settings.fedex.edit', compact('credential'));
        } catch (Exception $e) {
            return redirect(route('fedex-tracking-api.index'))->with('error', 'Something went wrong. Try again later');
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $credential = ApiCredential::findOrFail($id);
            $updateData = [
                'url'       => $request->url,
                'user_name' => $request->user_name,
                'key'       => $request->key ? $request->key : $credential->key,
                'password'  => $request->password ? $request->password : $credential->password,
                'account_no' => $request->account_no,
                'meter_no'  => $request->meter_no,
            ];
            $credential->update($updateData);
            return redirect(route('fedex-tracking-api.index'))->with('message', 'Credentials updated successfully');
        } catch (Exception $e) {
            return redirect(route('fedex-tracking-api.index'))->with('error', 'Something went wrong. Try again later');
        }
    }
}
