<?php
/**
 * app/plugins/members/models/membership_products.php
 *
 * This class is used for the manipulation of the membership_products database table.
 *
 * @package TP Members
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */

namespace TheTempusProject\Models;

use TheTempusProject\Canary\Bin\Canary as Debug;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Bedrock\Functions\Sanitize;
use TheTempusProject\Classes\DatabaseModel;
use TheTempusProject\TheTempusProject as App;
use TheTempusProject\Bedrock\Classes\Config;

class MembershipProducts extends DatabaseModel {
    public static $stripe;
    private static $loaded = false;
    public $tableName = 'membership_products';
    public $databaseMatrix = [
        [ 'name', 'varchar', '128' ],
        [ 'description', 'text', '' ],
        [ 'monthly_price', 'int', '10' ], // must be int value greater than 99 IE $1.00 === 100, $4,399.22 === 439922
        [ 'yearly_price', 'int', '10' ], // must be int value greater than 99 IE $1.00 === 100, $4,399.22 === 439922
        [ 'stripe_product', 'varchar', '64' ], // not-required to create -  generated by stripe after
        [ 'stripe_price_monthly', 'varchar', '64' ], // not-required to create -  generated by stripe after
        [ 'stripe_price_yearly', 'varchar', '64' ], // not-required to create -  generated by stripe after
    ];

    public function __construct() {
        parent::__construct();
        if ( ! self::$loaded ) {
            $api_key = Config::getValue( 'memberships/stripeSecret' );
            if ( $api_key == 'sk_xxxxxxxxxxxxxxx' || empty($api_key) ) {
                Debug::error( "MembershipProducts:__construct No Stripe Key found" );
            } else {
                self::$stripe = new \Stripe\StripeClient( $api_key );
            }
            self::$loaded = true;
        }
    }

    public function create( $name, $description, $monthly_price, $yearly_price ) {
        if ( empty( self::$stripe ) ) {
            return false;
        }
        $stripe_product = $this->createStripeProduct( $name, $description );
        $stripe_prices = $this->createStripePrices( $stripe_product->id, $monthly_price, $yearly_price );

        $fields = [
            'name' => $name,
            'description' => $description,
            'monthly_price' => $monthly_price,
            'yearly_price' => $yearly_price,
            'stripe_product' => $stripe_product->id,
            'stripe_price_monthly' => $stripe_prices['monthly']->id,
            'stripe_price_yearly' => $stripe_prices['yearly']->id,
        ];
        
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            Debug::error( "Membership Product: $data not updated: $fields" );
            new customException( 'membershipProductCreate' );
            return false;
        }

        return true;
    }

    public function createStripeProduct( $name, $description ) {
        if ( empty( self::$stripe ) ) {
            return false;
        }
        $product = self::$stripe->products->create([
            'name' => $name,
            'description' => $description,
        ]);
        return $product;
    }

    public function createStripePrices( $product, $monthly_price, $yearly_price ) {
        $out = [];
        $out['monthly'] = $this->createStripeMonthlyPrice( $product, $monthly_price );
        $out['yearly'] =  $this->createStripeYearlyPrice( $product, $yearly_price );
        return $out;
    }

    public function createStripeMonthlyPrice( $product, $monthly_price ) {
        if ( empty( self::$stripe ) ) {
            return false;
        }
        return self::$stripe->prices->create([
            'currency' => 'usd',
            'unit_amount' => $monthly_price,
            'recurring' => ['interval' => 'month'],
            'product' => $product,
            'lookup_key' => 'membership-monthly',
        ]);
    }

    public function createStripeYearlyPrice( $product, $yearly_price ) {
        if ( empty( self::$stripe ) ) {
            return false;
        }
        return self::$stripe->prices->create([
            'currency' => 'usd',
            'unit_amount' => $yearly_price,
            'recurring' => ['interval' => 'year'],
            'product' => $product,
            'lookup_key' => 'membership-yearly',
        ]);
    }

    public function updateProduct( $id, $name, $description, $monthly_price, $yearly_price ) {
        $product = $this->findById( $id );
        if ( $product === false ) {
            return false;
        }
        if ( $product->monthly_price != $monthly_price ) {
            $new_monthly = $this->updateStripeMonthlyPrice( $product->stripe_price_monthly, $monthly_price );
        }
        if ( $product->yearly_price != $yearly_price ) {
            $new_yearly = $this->updateStripeYearlyPrice( $product->stripe_price_yearly, $yearly_price );
        }
        if ( ( $product->name != $name ) || ( $product->description != $description ) ) {
            $this->updateStripeProduct( $product->stripe_product, $name, $description );
        }

        $fields = [
            'name' => $name,
            'description' => $description,
            'monthly_price' => $monthly_price,
            'yearly_price' => $yearly_price,
            'stripe_price_monthly' => $new_monthly->id,
            'stripe_price_yearly' => $new_yearly->id,
        ];
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            new CustomException( 'membershipProductUpdate' );
            Debug::error( "membership Product: $id not updated: $fields" );

            return false;
        }
        self::$log->admin( "Updated membership Product: $id" );
        return true;
    }

    public function updateStripeProduct( $id, $name, $description ) {
        if ( empty( self::$stripe ) ) {
            return false;
        }
        $product = self::$stripe->products->update(
            $id,
            [
                'name' => $name,
                'description' => $description,
            ]
        );
        return $product;
    }

    public function updateStripeYearlyPrice( $product, $yearly_price ) {
        $stripe->prices->update(
            $yearly_price,
            ['lookup_key' => ""]
        );
        return $this->createStripeYearlyPrice( $product, $yearly_price );
    }

    public function updateStripeMonthlyPrice( $product, $monthly_price ) {
        $stripe->prices->update(
            $monthly_price,
            ['lookup_key' => ""]
        );
        return $this->createStripeMonthlyPrice( $product, $monthly_price );
    }
    
    public function filter( $postArray, $params = [] ) {
        foreach ( $postArray as $instance ) {
            if ( !is_object( $instance ) ) {
                $instance = $postArray;
                $end = true;
            }

            $instance->prettyPriceMonthly = '&#36;' . number_format( $instance->monthly_price / 100, 2 ); // Outputs: $99.49
            $instance->prettyPriceYearly = '&#36;' . number_format( $instance->yearly_price / 100, 2 ); // Outputs: $99.49
            $instance->prettySavings = '&#36;' . number_format( 
                ( $instance->yearly_price - ( $instance->monthly_price * 12 ) ) / 100, 
                2
            ); // Outputs: $99.49

            $out[] = $instance;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }
    
    public function findByPriceID( $d ) {
        $data = self::$db->get( $this->tableName, [ 'stripe_price_monthly', '=', $d, 'OR', 'stripe_price_yearly', '=', $d ] );
        if ( ! $data->count() ) {
            return false;
        }
        return $this->filter( $data->first() );
    }

    public function mainProduct() {
        $data = self::$db->get( $this->tableName, '*' );
        if ( ! $data->count() ) {
            return false;
        }
        
        return $this->filter( $data->first() );
    }
}