<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class AuthMobileController extends Controller
{
    /**
     * Login API for Mobile using API Key, Username, and Password.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $apiKey = $request->header('x-api-key');

        // Validate API Key
        if (! $apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if (config('app.mobile_api_key') !== $apiKey) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Boleh pakai username atau nip
        $credentials = $request->only(['username', 'password']);

        if (empty($credentials['username']) || empty($credentials['password'])) {
            return response()->json(['error' => 'Username/NIP and password are required'], 400);
        }

        $user = DB::table('tbl_user')
            ->join('tbl_user_level', 'tbl_user.level_id', '=', 'tbl_user_level.id')
            ->select('tbl_user.*', 'tbl_user_level.level_name')
            ->where(function ($query) use ($credentials) {
                $query->where('tbl_user.username', $credentials['username'])
                    ->orWhere('tbl_user.nip', $credentials['username']);
            })
            ->first();

        if (! $user) {
            return response()->json(['error' => 'Username/NIP not found'], 404);
        }

        if (! Hash::check($credentials['password'], $user->password)) {
            return response()->json(['error' => 'Incorrect password'], 401);
        }

        if ('1' !== $user->status) {
            return response()->json(['error' => 'Account is inactive'], 403);
        }

        // Generate token
        $token = Str::random(60);

        // Save the token and last login timestamp to the database
        DB::table('tbl_user')->where('id', $user->id)->update([
            'token_login' => $token,
            'last_login'  => now('Asia/Jakarta'),
        ]);

        return response()->json([
            'message' => 'Login successful',
            'token'   => $token,
            'user'    => [
                'id'           => $user->id,
                'username'     => $user->username,
                'nama_lengkap' => $user->nama_lengkap,
                'nip'          => $user->nip,
                'jabatan'      => $user->jabatan,
                'email'        => $user->email,
                'no_hp'        => $user->no_hp,
                'level_id'     => $user->level_id,
                'level_name'   => $user->level_name,
                'last_login'   => now('Asia/Jakarta'),
            ],
        ], 200);
    }

    /**
     * Change Password API for Mobile.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(Request $request)
    {
        $apiKey = $request->header('x-api-key');

        // Validate API Key
        if (! $apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if (config('app.mobile_api_key') !== $apiKey) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        $data = $request->only(['id', 'new_password', 'confirm_password']);

        if (empty($data['id']) || empty($data['new_password']) || empty($data['confirm_password'])) {
            return response()->json(['error' => 'ID, new password, and confirm password are required'], 400);
        }

        if ($data['new_password'] !== $data['confirm_password']) {
            return response()->json(['error' => 'New password and confirm password do not match'], 400);
        }

        $user = DB::table('tbl_user')->where('id', $data['id'])->first();

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

        // Update password
        DB::table('tbl_user')->where('id', $data['id'])->update([
            'password'   => Hash::make($data['new_password']),
            'updated_at' => now('Asia/Jakarta'),
        ]);

        return response()->json([
            'message' => 'Password successfully updated',
        ], 200);
    }

    public function getUserByToken(Request $request)
    {
        $apiKey = $request->header('x-api-key');

        // Validasi API Key
        if (! $apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if (config('app.mobile_api_key') !== $apiKey) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Validasi Request Body
        $token = $request->input('token_login');

        if (! $token) {
            return response()->json(['error' => 'Token Login is required'], 400);
        }

        // Cek apakah token valid
        $user = DB::table('tbl_user')
            ->where('token_login', $token)
            ->where('status', "1")
            ->first();

        if (! $user) {
            return response()->json(['error' => 'Invalid or expired Token Login'], 401);
        }

        // Ambil detail pengguna berdasarkan token
        $userData = DB::table('tbl_user')
            ->join('tbl_user_level', 'tbl_user.level_id', '=', 'tbl_user_level.id')
            ->leftJoin('tbl_office', 'tbl_user.office_id', '=', 'tbl_office.id') // Join dengan tbl_office
            ->where('tbl_user.id', $user->id)
            ->where('tbl_user.status', "1")
            ->select(
                'tbl_user.id',
                'tbl_user.level_id',
                'tbl_user_level.level_name',
                'tbl_user.office_id',
                'tbl_office.office_name',
                'tbl_user.ai_label',
                'tbl_user.username',
                'tbl_user.nama_lengkap',
                'tbl_user.email',
                'tbl_user.no_hp',
                'tbl_user.nip',
                'tbl_user.jabatan',
                'tbl_user.last_login'
            )
            ->first();

        return response()->json([
            'message' => 'User fetched successfully.',
            'data'    => $userData,
        ], 200);
    }

    public function getUserById(Request $request)
    {
        $apiKey = $request->header('x-api-key');

        // Validasi API Key
        if (! $apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if (config('app.mobile_api_key') !== $apiKey) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Validasi request
        $userId = $request->input('user_id');
        if (! $userId) {
            return response()->json(['error' => 'User ID is required'], 400);
        }

        // Ambil data user
        $user = DB::table('tbl_user')
            ->join('tbl_user_level', 'tbl_user.level_id', '=', 'tbl_user_level.id')
            ->leftJoin('tbl_office', 'tbl_user.office_id', '=', 'tbl_office.id') // Join dengan tbl_office
            ->where('tbl_user.id', $userId)
            ->where('tbl_user.status', "1")
            ->select(
                'tbl_user.id',
                'tbl_user.level_id',
                'tbl_user_level.level_name',
                'tbl_user.office_id',
                'tbl_office.office_name',
                'tbl_user.ai_label',
                'tbl_user.username',
                'tbl_user.nama_lengkap',
                'tbl_user.email',
                'tbl_user.no_hp',
                'tbl_user.nip',
                'tbl_user.jabatan',
                'tbl_user.last_login'
            )
            ->first();

        if (! $user) {
            return response()->json(['error' => 'User not found or inactive'], 404);
        }

        return response()->json([
            'message' => 'User fetched successfully.',
            'data'    => $user,
        ], 200);
    }

    public function getAllActiveUsers(Request $request)
    {
        $apiKey = $request->header('x-api-key');

        // Validasi API Key
        if (! $apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if (config('app.mobile_api_key') !== $apiKey) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Ambil daftar user dengan status aktif (1)
        $users = DB::table('tbl_user')
            ->join('tbl_user_level', 'tbl_user.level_id', '=', 'tbl_user_level.id')
            ->leftJoin('tbl_office', 'tbl_user.office_id', '=', 'tbl_office.id') // Join dengan tbl_office
            ->where('tbl_user.status', operator: "1")
            ->select(
                'tbl_user.id',
                'tbl_user.level_id',
                'tbl_user_level.level_name',
                'tbl_user.office_id',
                'tbl_office.office_name',
                'tbl_user.ai_label',
                'tbl_user.username',
                'tbl_user.nama_lengkap',
                'tbl_user.email',
                'tbl_user.no_hp',
                'tbl_user.nip',
                'tbl_user.jabatan',
                'tbl_user.last_login'
            )
            ->get();

        return response()->json([
            'message' => 'Active users fetched successfully.',
            'data'    => $users,
        ], 200);
    }
}