<?php

namespace App\Controllers\API;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Libraries\JwtService;
use App\Libraries\ResponseFormatter;

class AuthController extends BaseController
{
    protected $userModel;
    protected $jwt;

    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->jwt = new JwtService();
    }

    // 🔐 LOGIN
    public function login()
    {
        $input = $this->request->getJSON(true);

        $user = $this->userModel
            ->where('email', $input['email'])
            ->first();

        if (!$user) {
            return $this->response->setJSON(
                ResponseFormatter::error('Email tidak ditemukan', 404)
            );
        }

        if (!password_verify($input['password'], $user['password'])) {
            return $this->response->setJSON(
                ResponseFormatter::error('Password salah', 401)
            );
        }

        // 🔥 Generate token
        $token = $this->jwt->generate([
            'id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email'],
            'role' => $user['role']
        ]);
        unset($user['password']);
        return $this->response->setJSON(
            ResponseFormatter::success([
                'token' => $token,
                'user' => $user
            ], 'Login berhasil')
        );
    }

    // 📝 REGISTER (optional)
    public function register()
    {
        $input = $this->request->getJSON(true);

        $userId = $this->userModel->insert([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => password_hash($input['password'], PASSWORD_DEFAULT),
            'role' => $input['role'] ?? 'kasir'
        ]);

        return $this->response->setJSON(
            ResponseFormatter::success([
                'user_id' => $userId
            ], 'Register berhasil')
        );
    }

    // 👤 PROFILE (cek token valid)
    
   public function profile()
{
    /** @var object $user */
    $user = $this->request->user ?? null;

    return $this->response->setJSON(
        ResponseFormatter::success($user)
    );
}
}