<?php

namespace App\Repositories;

use App\Models\State;
use Config\Database;
use PDO;

class StateRepository
{
    public function getStateByPercentage($percentage)
    {
        $db = Database::getConnection();

        $stmt = $db->prepare("
            SELECT * FROM states
            WHERE :percentage BETWEEN start_percentage AND end_percentage
            AND active = 1 AND deleted_at IS NULL
            LIMIT 1
        ");
        $stmt->bindValue(":percentage", $percentage, PDO::PARAM_INT);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            return null;
        }

        $state = new State();
        foreach ($row as $key => $value) {
            $state->$key = $value;
        }

        return $state;
    }

    public function preloadStates(): array
    {
        $db = Database::getConnection();
        $stmt = $db->query("
            SELECT *
            FROM states
            WHERE active = 1 AND deleted_at IS NULL
            ORDER BY start_percentage ASC
        ");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $states = [];
        foreach ($rows as $row) {
            $state = new State();
            foreach ($row as $k => $v) {
                $state->$k = $v;
            }
            $states[] = $state;
        }
        return $states;
    }

}