<?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_customers_o extends db
{
    use db_object_t;

    public object_property $email;

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

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

    /**
     * Add a customer to the database
     * @param string $email The customer's email address
     * @param string $customer_id The Stripe customer ID
     * @return void
     * @throws Exception If the object was not created successfully
     */
    public function add(string $email, string $customer_id): void
    {
        $tmp_id = self::add_object([
            'email' => $email,
            'customer_id' => $customer_id,
        ]);
        $this->id = $tmp_id;
        self::getObjectProperties();
        self::objectChanged();
    }

    public function getObjectProperties(): void
    {
        $this->email = new object_property($this->table, $this->id, 'email', 'string', false);
        $this->customer_id = new object_property($this->table, $this->id, 'customer_id', '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::retrieveCustomer();
        return [
            'id' => (int)$this->id,
            'email' => $this->email->value(),
            'customer_id' => $this->customer_id->value(),
            'created_at' => $this->created_at->value(),
            'object' => $object
        ];
    }

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

    /**
     * Check if a customer has an account
     * @param string $email
     * @return bool
     */
    public function doesCustomerHaveAccount(string $email): bool
    {
        return (bool)self::getFieldsWhere(['email' => $email], ['id']);
    }

    /**
     * Get the customer ID from the email address
     * @param string $email
     * @return string
     */
    public function getCustomerId(string $email): string
    {
        return self::getFieldsWhere(['email' => $email], ['customer_id'])[0]['customer_id'];
    }

}