<?php

namespace App\Http\Controllers\api\v1;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;

class SeverityControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $query = DB::table('severities')
            ->select('severities.*')
            ->orderBy('severities.name', 'asc');

        $query = $query->paginate(request()->get('limit', 20));

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
        ];

        return Response::json($response);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $data = request()->all();
        
        $severityId = DB::table('severities')->insertGetId([
            'name' => $data['name'],
            'description' => $data['description'] ?? '',
            'color' => $data['color'] ?? '#000000',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return Response::json(['success' => true, 'severity_id' => $severityId]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $severity = DB::table('severities')->where('id', $id)->first();

        if (!$severity) {
            return Response::json(['error' => 'Severity not found'], 404);
        }

        return Response::json($severity);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        $severity = DB::table('severities')->where('id', $id)->first();

        if (!$severity) {
            return Response::json(['error' => 'Severity not found'], 404);
        }

        $data = request()->all();
        $data['updated_at'] = now();

        DB::table('severities')->where('id', $id)->update($data);

        return Response::json(['success' => true, 'message' => 'Severity updated']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $severity = DB::table('severities')->where('id', $id)->first();

        if (!$severity) {
            return Response::json(['error' => 'Severity not found'], 404);
        }

        DB::table('severities')->where('id', $id)->delete();

        return Response::json(['success' => true, 'message' => 'Severity deleted']);
    }
}
