<?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 SlaControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $query = DB::table('slas')
            ->select('slas.*')
            ->orderBy('slas.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();
        
        $slaId = DB::table('slas')->insertGetId([
            'name' => $data['name'],
            'description' => $data['description'] ?? '',
            'hours' => $data['hours'] ?? 24,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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

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

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

        return Response::json($sla);
    }

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

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

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

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

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

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

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

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

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