<?php
namespace app\models;

use app\app;

class quotes
{
    private const STATUSES = [
        'DRAFT', 'PUBLISHED', 'SENT', 'PURCHASED',
        'EXPIRED', 'CANCELED',
    ];

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

    public static function createQuote(int $userId, string $status = 'DRAFT'): int
    {
        self::validateStatus($status);

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

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

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

        $stmt = app::$db->prepare("UPDATE quotes SET status = :status WHERE quote_id = :quote_id");
        $stmt->execute([
            'quote_id' => $quoteId,
            'status'   => $status,
        ]);
    }

    public static function getQuote(int $quoteId): array
    {
        $stmt = app::$db->prepare("SELECT * FROM quotes WHERE quote_id = :quote_id");
        $stmt->execute(['quote_id' => $quoteId]);
        return $stmt->fetch() ?: [];
    }

    public static function getUserQuotes(int $userId): array
    {
        $stmt = app::$db->prepare("SELECT * FROM quotes 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 quote status: $status");
        }
    }
}
