<?php

namespace App\Models;

use PDO;
use Config\Database;

class State extends BaseModel
{
    protected static $table = 'states';

    public $id;
    public $color;
    public $description;
    public $start_percentage;
    public $end_percentage;
    public $active;
    public $deleted_at;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->active = $data['active'] ?? 1;
    }

    public function save()
    {
        $db = Database::getConnection();
        if ($this->id) {
            $query = "UPDATE states SET color = :color, description = :description, start_percentage = :start_percentage, end_percentage = :end_percentage, active = :active WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':color' => $this->color,
                ':description' => $this->description,
                ':start_percentage' => $this->start_percentage,
                ':end_percentage' => $this->end_percentage,
                ':active' => $this->active
            ]);
        } else {
            $query = "INSERT INTO states (color, description, start_percentage, end_percentage, active) VALUES (:color, :description, :start_percentage, :end_percentage, :active)";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':color' => $this->color,
                ':description' => $this->description,
                ':start_percentage' => $this->start_percentage,
                ':end_percentage' => $this->end_percentage,
                ':active' => $this->active
            ]);
            $this->id = $db->lastInsertId();
        }
    }

    public static function getStates()
    {
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT * FROM states ORDER BY start_percentage ASC");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }
}