<?php
namespace App;

use PDO;

class Order {
    public static function create(string $stripeSessionId, int $amount_cents, string $status = 'pending', ?int $userId = null): int {
        $db = get_db();
        $stmt = $db->prepare('INSERT INTO orders (user_id, stripe_session_id, amount_cents, status) VALUES (:uid, :ss, :amt, :st)');
        $stmt->execute([':uid'=>$userId, ':ss'=>$stripeSessionId, ':amt'=>$amount_cents, ':st'=>$status]);
        return (int)$db->lastInsertId();
    }

    public static function all(): array {
        $db = get_db();
        $stmt = $db->query('SELECT * FROM orders ORDER BY id DESC');
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function allByUser(int $userId): array {
        $db = get_db();
        $stmt = $db->prepare('SELECT * FROM orders WHERE user_id = :uid ORDER BY id DESC');
        $stmt->execute([':uid' => $userId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function findBySession(string $stripeSessionId): ?array {
        $db = get_db();
        $stmt = $db->prepare('SELECT * FROM orders WHERE stripe_session_id = :ss LIMIT 1');
        $stmt->execute([':ss'=>$stripeSessionId]);
        $r = $stmt->fetch(PDO::FETCH_ASSOC);
        return $r ?: null;
    }

    public static function updateStatusBySession(string $stripeSessionId, string $status): bool {
        $db = get_db();
        $stmt = $db->prepare('UPDATE orders SET status = :st WHERE stripe_session_id = :ss');
        return $stmt->execute([':st'=>$status, ':ss'=>$stripeSessionId]);
    }
}
