<?php

declare(strict_types=1);

namespace App\Modules\Administration\Repositories;

use PDO;
use System\Contracts\DatabaseInterface;
use System\Database\QueryBuilder;

final class PermissionRepository
{
    private PDO $pdo;

    public function __construct(
        private QueryBuilder $query,
        DatabaseInterface $database
    ) {
        $this->pdo = $database->getConnection();
    }

    public function all(): array
    {
        return $this->query
            ->table('permissions')
            ->orderBy('id', 'DESC')
            ->get();
    }

    public function find(int $id): ?array
    {
        return $this->query
            ->table('permissions')
            ->find($id);
    }

    public function findByName(
        string $permissionName
    ): ?array {
        return $this->query
            ->table('permissions')
            ->where(
                'permission_name',
                $permissionName
            )
            ->first();
    }

    public function create(array $data): bool
    {
        return $this->query
            ->table('permissions')
            ->insert($data);
    }

    public function update(
        int $id,
        array $data
    ): bool {
        return $this->query
            ->table('permissions')
            ->where('id', $id)
            ->update($data);
    }

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

    public function assignedCount(
        int $permissionId
    ): int {
        $statement = $this->pdo->prepare(
            'SELECT COUNT(*)
             FROM role_permissions
             WHERE permission_id = ?'
        );

        $statement->execute([
            $permissionId
        ]);

        return (int) $statement->fetchColumn();
    }
}