<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Style;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class StyleController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $styles = Style::all();
        return response()->json($styles);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $request->validate([
                'style_name' => 'required|string|max:100|unique:styles,style_name',
                'active_status' => 'int',
            ]);

            $style = Style::create($request->all());
            return response()->json($style, 201);
        } catch (ValidationException $e) {
            return response()->json(['errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error creating style', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Style $style)
    {
        return response()->json($style);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Style $style)
    {
        try {
            $request->validate([
                'style_name' => 'sometimes|required|string|max:100|unique:styles,style_name,' . $style->style_id . ',style_id',
                'active_status' => 'sometimes|boolean',
            ]);

            $style->update($request->all());
            return response()->json($style);
        } catch (ValidationException $e) {
            return response()->json(['errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error updating style', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Style $style)
    {
        try {
            $style->delete();
            return response()->json(['message' => 'Style deleted successfully'], 204);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error deleting style', 'error' => $e->getMessage()], 500);
        }
    }
}
