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

        // Apply filters
        if (request()->get('user_id')) {
            $query->where('activity_logs.user_id', request()->get('user_id'));
        }

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

        if (request()->get('date_from')) {
            $query->where('activity_logs.created_at', '>=', request()->get('date_from'));
        }

        if (request()->get('date_to')) {
            $query->where('activity_logs.created_at', '<=', request()->get('date_to'));
        }

        $query = $query->orderBy('id', 'desc')->with('creator')->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();
        
        $activityLog = DB::table('activity_logs')->insert([
            'user_id' => $data['user_id'] ?? auth()->id(),
            'action' => $data['action'],
            'description' => $data['description'] ?? '',
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return Response::json(['success' => true, 'message' => 'Activity log created']);
    }

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

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

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