<?php

namespace objects;

use classes\db;
use classes\object_property;
use classes\stripe;
use Exception;
use Stripe\Exception\ApiErrorException;
use traits\db_object_t;

class stripe_module_orders_o extends db
{
    use db_object_t;

    public object_property $invoice_id;

    public object_property $customer_id;
    public object_property $email_sent;
    public object_property $url;
    public object_property $created_at;
    private bool $paid;

    public function structure(): void
    {
        $this->setTable('stripe_module_orders');
    }

    /**
     * Add a payment link to the database
     * @param int $order_id
     * @param string $email
     * @param string $payment_link_id
     * @param string $url The URL of the payment link
     * @return void
     * @throws Exception If the object was not created successfully
     */
    public function add(int $order_id, string $invoice_id, string $stripe_customer_id, string $url): void
    {
        $tmp_id = self::add_object([
            'id' => $order_id,
            'invoice_id' => $invoice_id,
            'customer_id' => $stripe_customer_id,
            'url' => $url,
        ]);
        $this->id = $tmp_id;
        self::getObjectProperties();
        self::objectChanged();
    }

    public function getObjectProperties(): void
    {
        $this->invoice_id = new object_property($this->table, $this->id, 'invoice_id', 'string', false);
        $this->customer_id = new object_property($this->table, $this->id, 'customer_id', 'string', false);
        $this->email_sent = new object_property($this->table, $this->id, 'email_sent', 'timestamp', false);
        $this->url = new object_property($this->table, $this->id, 'url', 'string', false);
        $this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
    }

    public function objectChanged(): void
    {
        //TODO: Add cache invalidation
    }

    /**
     * @throws ApiErrorException
     */
    public function asArray(): array
    {
        $object = self::retrievePaymentLink();
        return [
            'id' => (int)$this->id,
            'invoice_id' => (string)$this->invoice_id->value(),
            'customer_id' => (string)$this->customer_id->value(),
            'url' => (string)$this->url->value(),
            'created_at' => (string)$this->created_at->value(),
            'paid' => $object->paid,
            'status' => $object->status,
            'amount_due' => $object->amount_due,
            'amount_paid' => $object->amount_paid,
        ];
    }

    /**
     * @throws ApiErrorException
     * @throws Exception
     */
    public function retrievePaymentLink(): object
    {
        // Validate the object
        self::requireSelected();
        // Return the payment link
        return (new stripe())->invoice->retrieve($this->invoice_id->value());
    }

}