<?php

namespace App\Models;

use App\Core\Model;

class User extends Model
{
    protected string $table = 'users';
    protected string $primaryKey = 'user_id';

    public function findByEmail(string $email): ?array
    {
        return $this->findWhere(['email' => $email]);
    }

    public function verifyPassword(string $password, string $hash): bool
    {
        return password_verify($password, $hash);
    }

    public function hashPassword(string $password): string
    {
        return password_hash($password, PASSWORD_DEFAULT);
    }

    public function register(array $data): ?int
    {
        $config = require dirname(__DIR__, 2) . '/config/app.php';
        
        $isAdmin = in_array(strtolower($data['email']), $config['admin_emails'] ?? []);
        
        return $this->create([
            'email' => $data['email'],
            'password_hash' => $this->hashPassword($data['password']),
            'full_name' => $data['full_name'],
            'phone' => $data['phone'] ?? null,
            'city' => $data['city'] ?? null,
            'is_admin' => $isAdmin ? 'true' : 'false',
            'is_active' => 'true'
        ]);
    }

    public function authenticate(string $email, string $password): ?array
    {
        $user = $this->findByEmail($email);
        
        if (!$user) {
            return null;
        }

        if (!$user['is_active']) {
            return null;
        }

        if (!$this->verifyPassword($password, $user['password_hash'])) {
            return null;
        }

        $this->update($user['user_id'], [
            'last_login' => date('Y-m-d H:i:s')
        ]);

        return $user;
    }

    public function getActive(int $limit = 50): array
    {
        $sql = "SELECT * FROM {$this->table} 
                WHERE is_active = TRUE 
                ORDER BY created_at DESC 
                LIMIT ?";
        return $this->query($sql, [$limit]);
    }

    public function getAllPaginated(int $limit = 50, int $offset = 0): array
    {
        $sql = "SELECT * FROM {$this->table} 
                ORDER BY created_at DESC 
                LIMIT ? OFFSET ?";
        return $this->query($sql, [$limit, $offset]);
    }

    public function emailExists(string $email): bool
    {
        $user = $this->findByEmail($email);
        return $user !== null;
    }

    public function updateProfile(int $userId, array $data): bool
    {
        $allowedFields = ['full_name', 'phone', 'city'];
        $updateData = array_intersect_key($data, array_flip($allowedFields));
        $updateData['updated_at'] = date('Y-m-d H:i:s');
        
        return $this->update($userId, $updateData);
    }

    public function changePassword(int $userId, string $newPassword): bool
    {
        return $this->update($userId, [
            'password_hash' => $this->hashPassword($newPassword),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
    }

    public function setActive(int $userId, bool $active): bool
    {
        return $this->update($userId, [
            'is_active' => $active,
            'updated_at' => date('Y-m-d H:i:s')
        ]);
    }
}
