<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';

class User
{
    public function findByUsername(string $username): ?array
    {
        $stmt = db()->prepare('SELECT * FROM users WHERE username = :username LIMIT 1');
        $stmt->execute(['username' => $username]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function find(int $id): ?array
    {
        $stmt = db()->prepare('SELECT * FROM users WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    /**
     * @param 'admin'|'manager'|'customer' $role
     */
    public function create(
        string $fullName,
        string $username,
        string $password,
        string $role = 'customer',
        ?string $email = null,
        ?string $phone = null
    ): bool {
        $stmt = db()->prepare(
            'INSERT INTO users (full_name, username, email, phone, password_hash, role) VALUES (:full_name, :username, :email, :phone, :password_hash, :role)'
        );
        return $stmt->execute([
            'full_name' => $fullName,
            'username' => $username,
            'email' => $email,
            'phone' => $phone,
            'password_hash' => password_hash($password, PASSWORD_DEFAULT),
            'role' => $role,
        ]);
    }

    public function updateProfile(int $id, array $data): bool
    {
        $stmt = db()->prepare(
            'UPDATE users SET full_name=:full_name, email=:email, phone=:phone, address=:address, profile_image=COALESCE(:profile_image, profile_image) WHERE id=:id'
        );
        return $stmt->execute([
            'id' => $id,
            'full_name' => $data['full_name'],
            'email' => $data['email'] ?: null,
            'phone' => $data['phone'] ?: null,
            'address' => $data['address'] ?: null,
            'profile_image' => $data['profile_image'] ?? null,
        ]);
    }

    public function setRole(int $id, string $role): bool
    {
        $stmt = db()->prepare('UPDATE users SET role = :role WHERE id = :id');
        return $stmt->execute(['id' => $id, 'role' => $role]);
    }

    public function setSuspended(int $id, bool $suspended): bool
    {
        $stmt = db()->prepare('UPDATE users SET suspended = :s WHERE id = :id');
        return $stmt->execute(['id' => $id, 's' => $suspended ? 1 : 0]);
    }

    public function all(int $limit = 500): array
    {
        $stmt = db()->prepare(
            'SELECT id, full_name, username, email, phone, role, wallet_balance, suspended, created_at FROM users ORDER BY id DESC LIMIT :lim'
        );
        $stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public function countByRole(): array
    {
        $stmt = db()->query('SELECT role, COUNT(*) c FROM users GROUP BY role');
        $out = ['admin' => 0, 'manager' => 0, 'customer' => 0];
        foreach ($stmt->fetchAll() as $row) {
            $r = (string)$row['role'];
            if (isset($out[$r])) {
                $out[$r] = (int)$row['c'];
            }
        }
        return $out;
    }
}
