<?php

namespace App\Http\Controllers\SM;

use App\Http\Controllers\Controller;
use App\Services\SM\AppService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AppController extends Controller
{
    /**
     * Display a listing of the resource.
     */

    public function __construct(private AppService $appService)
    {
        
    }
    public function index()
    {
        try {
            $data = $this->appService->dataTable();
            return response()->json($data);
        } catch (Exception $e) {
            return response()->json(['data' => [], 'message' => $e->getMessage()], 500);
        }
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();
            $app = $this->appService->create($request->all());
            DB::commit();
            return response()->json(['app' => $app, 'message' => 'App created']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

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

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        try {
            DB::beginTransaction();
            $app = $this->appService->update($id,$request->all());
            DB::commit();
            return response()->json(['app' => $app, 'message' => 'App updated']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

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