<?php

declare(strict_types=1);

namespace App\Modules\Administration\Repositories;

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

final class BranchRepository
{
    private PDO $pdo;

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

    public function all(): array
    {
        $statement = $this->pdo->query(
            'SELECT
                b.*,
                o.organization_name
             FROM branches b
             INNER JOIN organizations o
                ON o.id = b.organization_id
             ORDER BY b.id DESC'
        );

        return $statement->fetchAll(
            PDO::FETCH_ASSOC
        );
    }

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

    public function findByName(
        int $organizationId,
        string $name
    ): ?array {
        return $this->query
            ->table('branches')
            ->where(
                'organization_id',
                $organizationId
            )
            ->where(
                'branch_name',
                $name
            )
            ->first();
    }

    public function organizations(): array
    {
        return $this->query
            ->table('organizations')
            ->where('active', 1)
            ->orderBy(
                'organization_name',
                'ASC'
            )
            ->get();
    }

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

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

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