<?php

require_once __DIR__ . "/../config/database.php";

class PaymentRepository
{

    private PDO $db;

    public function __construct()
    {
        $database = new Database();
        $this->db = $database->connect();
    }


    /**
     * Create Payment
     */
    public function create(

        int $orderId,

        string $provider,

        string $phone,

        float $amount,

        string $currency

    ): int
    {

        $sql = "

        INSERT INTO payments

        (

            order_id,
            provider,
            phone,
            amount,
            currency

        )

        VALUES

        (

            :order_id,
            :provider,
            :phone,
            :amount,
            :currency

        )

        ";

        $stmt = $this->db->prepare($sql);

        $stmt->execute([

            ":order_id" => $orderId,

            ":provider" => $provider,

            ":phone" => $phone,

            ":amount" => $amount,

            ":currency" => $currency

        ]);

        return (int)$this->db->lastInsertId();

    }


    /**
     * Update Payment
     */
    public function update(

        int $paymentId,

        string $referenceId,

        ?string $transactionId,

        string $status

    ): bool
    {

        $sql = "

        UPDATE payments

        SET

            reference_id = :reference,

            transaction_id = :transaction,

            status = :status

        WHERE id = :id

        ";

        $stmt = $this->db->prepare($sql);

        return $stmt->execute([

            ":reference" => $referenceId,

            ":transaction" => $transactionId,

            ":status" => $status,

            ":id" => $paymentId

        ]);

    }


    /**
     * Find Payment
     */
    public function find(int $paymentId): ?array
    {

        $stmt = $this->db->prepare(

            "SELECT * FROM payments WHERE id=?"

        );

        $stmt->execute([$paymentId]);

        $payment = $stmt->fetch();

        return $payment ?: null;

    }

}