<?php

declare(strict_types=1);

namespace App\Modules\Administration\Repositories;

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

final class CountyRepository
{
    private PDO $pdo;

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

    public function all(): array
    {
        $statement = $this->pdo->query(
            'SELECT
                c.*,
                s.state_code,
                s.state_name,
                s.administrative_type
             FROM counties c
             INNER JOIN states s
                ON s.id = c.state_id
             ORDER BY
                s.state_name ASC,
                c.county_name ASC'
        );

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

    public function states(): array
    {
        return $this->query
            ->table('states')
            ->where('status', 1)
            ->orderBy('state_name', 'ASC')
            ->get();
    }

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

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

    public function findByName(
        int $stateId,
        string $name
    ): ?array {
        return $this->query
            ->table('counties')
            ->where('state_id', $stateId)
            ->where('county_name', $name)
            ->first();
    }

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

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

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