<?php

namespace App\Http\Controllers\api\v1;

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

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

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

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

        $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();
        
        $userId = DB::table('users')->insertGetId([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'role' => $data['role'] ?? 'user',
            'active' => $data['active'] ?? 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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

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

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

        // Remove sensitive data
        unset($user->password);

        return Response::json($user);
    }

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

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

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

        // Hash password if provided
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }

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

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

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

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

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

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

    /**
     * Get current user profile
     *
     * @return Response
     */
    public function profile()
    {
        $user = Auth::user();
        
        if (!$user) {
            return Response::json(['error' => 'User not authenticated'], 401);
        }

        // Remove sensitive data
        unset($user->password);

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