<?php
/**
 * app/controllers/api/users.php
 *
 * This is the users' api controller.
 *
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Controllers\Api;

use Stripe\StripeClient;
use Stripe\Event;
use TheTempusProject\Models\User;
use TheTempusProject\Classes\ApiController;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Bedrock\Classes\Config;
use TheTempusProject\Canary\Bin\Canary as Debug;
use TheTempusProject\Models\MembershipCustomers;
use TheTempusProject\Models\Memberships;

class Stripe extends ApiController {
    public static $stripe;
    public static $customers;
    public static $memberships;

    public function __construct() {
        parent::__construct( false );
        $api_key = Config::getValue( 'memberships/stripeSecret' );
        self::$stripe = new StripeClient($api_key);
    }
    
    public function webhook() {
        try {
            $payload = @file_get_contents('php://input');
            $payload = json_decode( $payload, true );
            if ( ! is_array( $payload ) ) {
                throw new \Exception("Error Processing Request", 1);
            }
            $event = null;
            $event = Event::constructFrom( $payload );
            
            $eventData = $event->data->object;

            // $event->type gives the event type obv
            switch ($event->type) {
                // case 'invoice.paid':
                    // Debug::error( 'processing: ' . $event->type );
                    // "id": "in_1QSDcJGsigymNdIJo0Z1a20K",
                    // "customer": "cus_RKtOtR7X7CwPRU",
                    // "charge": "ch_3QSDcJGsigymNdIJ0Smb7Rmx",
                    // "subscription": "sub_1QSDcJGsigymNdIJWGw7Zrv9",
                    // break;

                // case 'charge.succeeded':
                    // Debug::error( 'processing: ' . $event->type );
                    // "id": "ch_3QSDcJGsigymNdIJ0Smb7Rmx",
                    // "invoice": "in_1QSDcJGsigymNdIJo0Z1a20K",
                    // "status": "succeeded",
                    // break;

                case 'customer.subscription.updated':
                case 'customer.subscription.paused':
                case 'customer.subscription.resumed':
                case 'customer.subscription.deleted':
                    Debug::error( 'processing: ' . $event->type );

                    self::$memberships = new Memberships;
                    $membership_id = self::$memberships->findBySubscriptionID( $eventData->id );
                    if ( empty( $membership_id ) ) {
                        Debug::error( 'membership not found' );

                        self::$customers = new MembershipCustomers;
                        $customer = self::$customers->findByCustomerID( $eventData->customer );
                        if ( empty( $customer ) ) {
                            Debug::error( 'customer not found' );
                            Debug::v( $eventData->customer );
                            break;
                        }

                        $result = self::$memberships->create(
                            $eventData->customer,
                            $eventData->id,
                            $eventData->plan->id,
                            $eventData->current_period_start,
                            $eventData->current_period_end,
                            $eventData->status,
                            $customer->local_user,
                            'frequency'
                        );
                    } else {
                        $result = self::$memberships->update( $membership_id->ID, $eventData->current_period_start, $eventData->current_period_end, $eventData->status );
                    }
                    
                    if ( empty( $result ) ) {
                        Debug::error( 'membership not updated' );
                        Debug::v( $result );
                    }
                    break;
                case 'customer.subscription.created':
                    Debug::error( 'processing: ' . $event->type );
                    
                    self::$memberships = new Memberships;
                    $membership_id = self::$memberships->findBySubscriptionID( $eventData->id );
                    if ( ! empty( $membership_id ) ) {
                        Debug::error( 'subscription already created' );
                        break;
                    }
                    self::$customers = new MembershipCustomers;
                    $customer = self::$customers->findByCustomerID( $eventData->customer );
                    if ( empty( $customer ) ) {
                        Debug::error( 'customer not found' );
                        Debug::v( $eventData->customer );
                        break;
                    }
                    Debug::error( 'processing: ' . $event->type );

                    $result = self::$memberships->create(
                        $eventData->customer,
                        $eventData->id,
                        $eventData->plan->id,
                        $eventData->current_period_start,
                        $eventData->current_period_end,
                        $eventData->status,
                        $customer->local_user,
                        'frequency'
                    );
                    Debug::error( 'processing: ' . $event->type );

                    if ( empty( $result ) ) {
                        Debug::error( 'membership not made' );
                        Debug::v( $result );
                    }
                    Debug::error( 'done processing: ' . var_export($result,true) );
                    break;
                // case 'invoice.created':
                    // Debug::error( 'processing: ' . $event->type );
                    // happens when the payment first starts
                    
                    // "id": "in_1QSDcJGsigymNdIJo0Z1a20K",
                    // "customer": "cus_RKtOtR7X7CwPRU",
                    // "status": "open",
                    // "total": 888,
                    // break;
                // case 'checkout.session.completed':
                    // Debug::error( 'processing: ' . $event->type );
                    // new customer has completed first checkout
                    // add thier record or update iit

                    // "invoice": "in_1QSDcJGsigymNdIJo0Z1a20K",
                    // "mode": "subscription",
                    // "status": "complete",
                    // "customer": "cus_RKtOtR7X7CwPRU",
                    // break;
                // case 'payment_intent.succeeded':
                    // Debug::error( 'processing: ' . $event->type );
                    // $paymentIntent = $event->data->object;
                    // break;
                // case 'payment_method.attached':
                    // Debug::error( 'processing: ' . $event->type );
                    // $paymentMethod = $event->data->object;
                    // break;
                default:
                    Debug::error( 'Skipped Event:' . $event->type );
                    break;
            }


            $responseType = 'success';
            $response = true;
        } catch(\UnexpectedValueException $e) {
            Debug::error( 'UnexpectedValueException' );
            Debug::v( $e );
            http_response_code(400);
            $responseType = 'error';
            $response = 'UnexpectedValueException';
        } catch(\Exception $e) {
            Debug::error( 'Exception' );
            Debug::error( $e );
            http_response_code(400);
            $responseType = 'error';
            $response = 'Exception';
        }
        Views::view( 'api.response', ['response' => json_encode( [ $responseType => $response ], true )]);
    }
}