<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;
use Firebase\JWT\JWT;

class Auth extends BaseController
{
    use ResponseTrait;

    public function register()
    {
        $rules = [
            'phone' => 'required|is_unique[users.phone]',
            'password' => 'required|min_length[6]',
            'role' => 'required|in_list[customer,worker]'
        ];

        if (!$this->validate($rules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $userModel = new UserModel();
        $data = [
            'phone' => $this->request->getVar('phone'),
            'password_hash' => $this->request->getVar('password'),
            'role' => $this->request->getVar('role'),
            'email' => $this->request->getVar('email'), // Optional
        ];

        $userModel->save($data);
        
        return $this->respondCreated(['message' => 'User registered successfully']);
    }

    public function login()
    {
        $rules = [
            'phone' => 'required',
            'password' => 'required'
        ];

        if (!$this->validate($rules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $userModel = new UserModel();
        $user = $userModel->where('phone', $this->request->getVar('phone'))->first();

        if (!$user || !password_verify($this->request->getVar('password'), $user['password_hash'])) {
            return $this->failUnauthorized('Invalid phone or password');
        }

        $key = getenv('JWT_SECRET') ?: 'super-secret-key'; // Move to .env
        $payload = [
            'iss' => 'localhost',
            'aud' => 'localhost',
            'iat' => time(),
            'exp' => time() + (60 * 60 * 24 * 30), // 30 days
            'uid' => $user['id'],
            'role' => $user['role']
        ];

        $token = JWT::encode($payload, $key, 'HS256');

        return $this->respond([
            'token' => $token,
            'user' => [
                'id' => $user['id'],
                'phone' => $user['phone'],
                'role' => $user['role'],
                'is_verified' => $user['is_verified']
            ]
        ]);
    }
}
