<?php

namespace App\Http\Controllers\WS;

use App\Http\Controllers\Controller;
use App\Http\Requests\WS\ServiceRequest;
use App\Services\WS\ServiceService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ServiceController extends Controller
{

    public function __construct(private ServiceService $serviceService)
    {
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return $this->serviceService->datatable();
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(ServiceRequest $request)
    {
        try {
            DB::beginTransaction();
            $this->serviceService->create((object)$request->validated());
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data saved successfully']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        return response()->json(['success' => true, 'service' => $this->serviceService->detail($id)]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ServiceRequest $request, string $id)
    {
        try {
            DB::beginTransaction();
            $this->serviceService->update($id, (object)$request->validated());
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Service updated']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function delete(Request $request)
    {
        try {
            DB::beginTransaction();
            $this->serviceService->delete($request->all());
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Services deleted']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}
