<?php

declare(strict_types=1);

namespace App\Modules\Administration\Repositories;

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

final class DepartmentRepository
{
    private PDO $pdo;

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

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

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

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

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

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

    public function findByCode(
        string $code
    ): ?array {
        return $this->query
            ->table('departments')
            ->where(
                'department_code',
                $code
            )
            ->first();
    }

    public function findByName(
        int $branchId,
        string $name
    ): ?array {
        return $this->query
            ->table('departments')
            ->where(
                'branch_id',
                $branchId
            )
            ->where(
                'department_name',
                $name
            )
            ->first();
    }

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

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

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