<?php
require_once __DIR__ . '/../DBconnection.php';

class ColoresController extends DBconnection
{
    public function getColores()
    {
        $query = "SELECT id, nombre, codigo_hex, status FROM colores WHERE status = 1 ORDER BY nombre";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($result);
    }

    public function getColor($id)
    {
        $query = "SELECT id, nombre, codigo_hex, status FROM colores WHERE id = :id";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':id' => $id));
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode($result);
    }

    public function createColor($nombre, $codigo_hex)
    {
        $query = "INSERT INTO colores (nombre, codigo_hex, status) VALUES (:nombre, :codigo_hex, 1)";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':nombre' => $nombre, ':codigo_hex' => $codigo_hex));
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Color creado exitosamente']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No se pudo crear el color']);
        }
    }

    public function updateColor($id, $nombre, $codigo_hex)
    {
        $query = "UPDATE colores SET nombre = :nombre, codigo_hex = :codigo_hex WHERE id = :id";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':nombre' => $nombre, ':codigo_hex' => $codigo_hex, ':id' => $id));
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Color actualizado exitosamente']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No se pudo actualizar el color']);
        }
    }

    public function deleteColor($id)
    {
        $query = "UPDATE colores SET status = 0 WHERE id = :id";
        $stmt = $this->connect()->prepare($query);
        $stmt->execute(array(':id' => $id));
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Color eliminado exitosamente']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No se pudo eliminar el color']);
        }
    }
}
?>