<?php
namespace app\models;

use app\app;

class orders
{
    const STATUSES = [
        'SHIPPED', 'PENDING', 'HOLD', 'PARTIAL',
        'BACKORDER', 'FAILED', 'CANCELED', 'PROCESSING',
    ];

    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS orders (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL REFERENCES users(id),
            value_sats INTEGER NOT NULL CHECK(value_sats >= 0),
            value_cents INTEGER NOT NULL CHECK(value_cents >= 0),
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            status TEXT CHECK(status IN ('" . implode("', '", self::STATUSES) . "')) NOT NULL DEFAULT 'PENDING'
        );");
    }

    public static function createOrder(int $userId, int $valueSats, int $valueCents, string $status = 'PENDING'): int
    {
        self::validateStatus($status);

        $stmt = app::$db->prepare("INSERT INTO orders (user_id, value_sats, value_cents, status)
                                   VALUES (:user_id, :value_sats, :value_cents, :status)");
        $stmt->execute([
            'user_id'     => $userId,
            'value_sats'  => $valueSats,
            'value_cents' => $valueCents,
            'status'      => $status,
        ]);

        return app::$db->lastInsertId();
    }

    public static function updateStatus(int $orderId, string $status)
    {
        self::validateStatus($status);

        $stmt = app::$db->prepare("UPDATE orders SET status = :status WHERE order_id = :order_id");
        $stmt->execute([
            'order_id' => $orderId,
            'status'   => $status,
        ]);
    }

    public static function getOrder(int $orderId): array
    {
        $stmt = app::$db->prepare("SELECT * FROM orders WHERE order_id = :order_id");
        $stmt->execute(['order_id' => $orderId]);
        return $stmt->fetch() ?: [];
    }

    public static function getUserOrders(int $userId): array
    {
        $stmt = app::$db->prepare("SELECT * FROM orders WHERE user_id = :user_id ORDER BY created_at DESC");
        $stmt->execute(['user_id' => $userId]);
        return $stmt->fetchAll();
    }

    private static function validateStatus(string $status)
    {
        if (! in_array($status, self::STATUSES, true)) {
            throw new \InvalidArgumentException("Invalid order status: $status");
        }
    }
}
