<?php namespace App\Controllers\Api;
use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\UserModel;
use CodeIgniter\RESTful\ResourceController;

class UserController extends BaseApiController
{
    public function details()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');


        if (! $authHeader || ! str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        
       
        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;
            // You can also get query param if needed:
            // $requestedId = $this->request->getGet('user_id');

            if (!$userId) {
                return $this->failUnauthorized('Invalid token');
            }

            $userModel = new UserModel();
            $user = $userModel
                    ->select('id, name, email, user_id, mobile')
                    ->where('user_id', $userId)
                    ->first();
          

            if (!$user) {
                return $this->failNotFound('User not found');
            }
              

            return $this->respond([
                'id' => $user['id'],
                'name' => $user['name'],
                'email' => $user['email'],
                'mobile' => $user['mobile'],
                'user_id' => $user['user_id']
            ]);
        } catch (\Exception $e) {
            return $this->failUnauthorized('Invalid or expired token');
        }
    }
    public function updateUser()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token');
            }

            $userModel = new \App\Models\UserModel();
            $user = $userModel->where('user_id', $userId)->first();

            if (!$user) {
                return $this->failNotFound('User not found');
            }

            $input = $this->request->getPost();

            $updateData = [];

            if (!empty($input['name'])) {
                $updateData['name'] = $input['name'];
            }

            if (!empty($input['email'])) {
                $updateData['email'] = $input['email'];
            }

            if (!empty($input['mobile_no'])) {
                $updateData['mobile'] = $input['mobile_no'];
            }
            
            if (!empty($input['password'])) {
                $updateData['password'] = $input['password']; // will be hashed by model's beforeUpdate hook
            }


            $userModel->update($user['id'], $updateData);

            return $this->respond([
                'status' => true,
                'message' => 'User updated successfully.'
            ]);
        } catch (\Exception $e) {
            return $this->failUnauthorized('Invalid or expired token');
        }
    }

}
