<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\HappyClient;

class HappyClientController extends Controller
{

    public function index()
    {
        $clients = HappyClient::orderBy('id', 'desc')->get();
        return sendSuccessResponse($clients->map(function ($client) {
            return [
                'id' => $client->id,
                'name' => $client->name,
                'logo' => getObjUrl('happy-clients', $client->logo)
            ];
        }));
    }

    public function happyClients()
    {
        return view('Backend.HappyClient.index', [
            'happyClients' => HappyClient::orderBy('id', 'desc')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp|max:10240',
        ]);


        try {
            if ($request->hasFile('logo')) {
                $logoName = uploadImageR2($request->file('logo'), 'happy-clients');
            }

            HappyClient::create([
                'name' => $request->name,
                'logo' => $logoName,
            ]);

            toastr()->success('Client logo uploaded successfully');
            return redirect()->route('admin.happy-clients');
        } catch (\Exception $e) {
            toastr()->error('An error occurred while uploading the client logo');
            return redirect()->back()->withInput();
        }
    }

    public function destroy($id)
    {
        try {
            $happyClient = HappyClient::find($id);
            if ($happyClient->logo) {
                deleteOldFileR2('speed-net/happy-clients', $happyClient->logo);
            }
            $happyClient->delete();
            toastr()->success('Client logo deleted successfully');
            return redirect()->route('admin.happy-clients');
        } catch (\Exception $e) {
            toastr()->error('An error occurred while deleting the client logo');
            return redirect()->back();
        }
    }
}
