<?php

namespace App\Models;
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['email', 'ref', 'ip', 'currency', 'last_active', 'registered_date'];

    public function getUser($email){
        return $this->where('email', $email)->first();
    }

    public function getUserById($id){
        return $this->where('id', $id)->first();
    }

    public function getUserByRef($ref){
        return $this->where('ref', $ref)->first();
    }

    public function getUserByIp($ip){
        return $this->where('ip', $ip)->first();
    }

    public function RegisterUser($email, $ip, $ref = null){
        $data = [
            'email' => $email,
            'ip' => $ip,
            'ref' => $ref,
            'registered_date' => date('Y-m-d H:i:s'),
            'last_active' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s'),
        ];
        return $this->insert($data);
    }

    public function createAdmin($username, $email, $password){
        $data = [
            'username' => $username,
            'email' => $email,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'role' => 'admin',
            'ip' => '127.0.0.1',
            'registered_date' => date('Y-m-d H:i:s'),
            'last_active' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s'),
        ];
        return $this->insert($data);
    }

    public function getAdmins(){
        return $this->where('role', 'admin')->findAll();
    }

    public function isAdmin($userId){
        $user = $this->where('id', $userId)->first();
        return $user && $user['role'] === 'admin';
    }
    
}
