<?php
class UserModel extends Model {
    protected static string $table = 'users';

    public static function findByEmail(string $email, int $tenantId): ?array {
        $stmt = db()->prepare("SELECT * FROM users WHERE email=? AND tenant_id=? AND is_active=1 LIMIT 1");
        $stmt->execute([$email,$tenantId]);
        return $stmt->fetch() ?: null;
    }

    public static function findFirstAdminByEmail(string $email): ?array {
        // For login: find tenant by user email across all tenants
        $stmt = db()->prepare(
            "SELECT u.*,t.id as tenant_id,t.slug as tenant_slug,t.business_name,t.status as tenant_status,t.logo as tenant_logo
             FROM users u JOIN tenants t ON t.id=u.tenant_id
             WHERE u.email=? AND u.is_active=1 LIMIT 1"
        );
        $stmt->execute([$email]);
        return $stmt->fetch() ?: null;
    }

    public static function create(array $data): int {
        $data['password'] = Security::hashPassword($data['password']);
        return parent::create($data);
    }

    public static function updatePassword(int $id, string $password): bool {
        return static::update($id, ['password' => Security::hashPassword($password)]);
    }
}
