<?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 SlaLogControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $query = DB::table('sla_logs')
            ->select('sla_logs.*', 'tasks.name as task_name', 'users.first_name', 'users.last_name')
            ->leftJoin('tasks', 'tasks.id', '=', 'sla_logs.task_id')
            ->leftJoin('users', 'users.id', '=', 'sla_logs.user_id')
            ->orderBy('sla_logs.created_at', 'desc');

        if (request()->get('task_id')) {
            $query->where('sla_logs.task_id', request()->get('task_id'));
        }

        $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();
        
        $slaLogId = DB::table('sla_logs')->insertGetId([
            'task_id' => $data['task_id'],
            'user_id' => $data['user_id'] ?? auth()->id(),
            'action' => $data['action'],
            'description' => $data['description'] ?? '',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $slaLog = DB::table('sla_logs')
            ->select('sla_logs.*', 'tasks.name as task_name', 'users.first_name', 'users.last_name')
            ->leftJoin('tasks', 'tasks.id', '=', 'sla_logs.task_id')
            ->leftJoin('users', 'users.id', '=', 'sla_logs.user_id')
            ->where('sla_logs.id', $id)
            ->first();

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

        return Response::json($slaLog);
    }
}
