<?php

namespace Models;

class PaymentModel
{
    private \PDO $pdo;
    public const STATUS_PENDING = 0;
    public const STATUS_COMPLETED = 1;

    public function __construct()
    {
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
            $this->pdo = $GLOBALS['pdo'];
            return;
        }

        throw new \RuntimeException('Global PDO connection not initialized');
    }

    public function create(
        string $paymentExternalId,
        int $statusId,
        int $userId,
        ?int $paymentTs = null,
        ?string $paymentE2e = null,
        ?string $paymentFlag = null
    ): int {
        $stmt = $this->pdo->prepare(
            'INSERT INTO "payment" (
                payment_external_id,
                status_id,
                user_id,
                payment_ts,
                payment_e2e,
                payment_flag
            ) VALUES (
                :external_id,
                :status_id,
                :user_id,
                :payment_ts,
                :payment_e2e,
                :payment_flag
            ) RETURNING payment_id'
        );

        $stmt->execute([
            'external_id' => $paymentExternalId,
            'status_id' => $statusId,
            'user_id' => $userId,
            'payment_ts' => $paymentTs ?? 0,
            'payment_e2e' => $paymentE2e ?? '',
            'payment_flag' => $paymentFlag ?? '',
        ]);

        return (int)$stmt->fetchColumn();
    }

    public function findById(int $paymentId): ?array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM "payment" WHERE payment_id = :payment_id');
        $stmt->execute(['payment_id' => $paymentId]);
        $record = $stmt->fetch(\PDO::FETCH_ASSOC);

        return $record ?: null;
    }

    public function findByExternalId(string $paymentExternalId): ?array
    {
        $stmt = $this->pdo->prepare(
            'SELECT * FROM "payment" WHERE payment_external_id = :external_id LIMIT 1'
        );
        $stmt->execute(['external_id' => $paymentExternalId]);
        $record = $stmt->fetch(\PDO::FETCH_ASSOC);

        return $record ?: null;
    }

    public function updateStatusId(int $paymentId, int $statusId): void
    {
        $stmt = $this->pdo->prepare(
            'UPDATE "payment" SET status_id = :status_id WHERE payment_id = :payment_id'
        );
        $stmt->execute([
            'status_id' => $statusId,
            'payment_id' => $paymentId,
        ]);
    }
}
