<?php

require_once __DIR__ . '/../core/Database.php';

class UserModel
{
    public static function updatePassword(int $userId, string $password): bool
    {
        $pdo = Database::getInstance();
        $stmt = $pdo->prepare('UPDATE usuarios SET password = :password WHERE id = :id');

        return $stmt->execute([
            ':password' => password_hash($password, PASSWORD_BCRYPT),
            ':id' => $userId
        ]);
    }

    public static function create(array $data): bool
    {
        $pdo = Database::getInstance();
        $columns = self::availableColumns();
        $fields = ['nombre', 'email', 'password'];

        if (in_array('telefono', $columns, true)) {
            $fields[] = 'telefono';
        }

        if (in_array('ciudad', $columns, true)) {
            $fields[] = 'ciudad';
        }

        if (in_array('tipo_mascota', $columns, true)) {
            $fields[] = 'tipo_mascota';
        }

        $placeholders = array_map(static fn(string $field): string => ':' . $field, $fields);
        $sql = 'INSERT INTO usuarios (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $placeholders) . ')';
        $stmt = $pdo->prepare($sql);

        $params = [
            ':nombre' => $data['nombre'],
            ':email' => $data['email'],
            ':password' => password_hash($data['password'], PASSWORD_BCRYPT)
        ];

        if (in_array('telefono', $columns, true)) {
            $params[':telefono'] = $data['telefono'] ?? '';
        }

        if (in_array('ciudad', $columns, true)) {
            $params[':ciudad'] = $data['ciudad'] ?? '';
        }

        if (in_array('tipo_mascota', $columns, true)) {
            $params[':tipo_mascota'] = $data['tipo_mascota'] ?? '';
        }

        return $stmt->execute($params);
    }

    public static function findByEmail(string $email): ?array
    {
        $pdo = Database::getInstance();
        $stmt = $pdo->prepare('SELECT * FROM usuarios WHERE email = :email LIMIT 1');
        $stmt->execute([':email' => $email]);
        $user = $stmt->fetch();

        return $user ?: null;
    }

    public static function findByEmailOrName(string $identifier): ?array
    {
        $pdo = Database::getInstance();
        $stmt = $pdo->prepare('SELECT * FROM usuarios WHERE email = :email OR nombre = :nombre LIMIT 1');
        $stmt->execute([
            ':email' => $identifier,
            ':nombre' => $identifier
        ]);
        $user = $stmt->fetch();

        return $user ?: null;
    }

    private static function availableColumns(): array
    {
        $pdo = Database::getInstance();
        $stmt = $pdo->query(
            'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = "usuarios"'
        );

        return array_map(static fn(array $row): string => $row['COLUMN_NAME'], $stmt->fetchAll());
    }
}
