<?php
/**
 * Webhook handler for Subscription System
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/includes
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

/**
 * Webhook handler class
 */
class Subs_Sys_Webhook {

    /**
     * Initialize the class
     */
    public function __construct() {
        // Register REST API routes
        add_action('rest_api_init', array($this, 'register_routes'));
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
        register_rest_route('subscription-system/v1', '/webhook', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_webhook'),
            'permission_callback' => '__return_true',
        ));
    }

    /**
     * Handle webhook
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response
     */
    public function handle_webhook($request) {
        // Get the webhook payload
        $payload = $request->get_body();
        $sig_header = $request->get_header('stripe-signature');
        
        // Get webhook secret
        $webhook_secret = get_option('subscription_stripe_webhook_secret');
        
        try {
            // Verify the webhook signature
            $event = \Stripe\Webhook::constructEvent(
                $payload, $sig_header, $webhook_secret
            );
            
            // Handle the event
            switch ($event->type) {
                case 'payment_intent.succeeded':
                    $this->handle_payment_intent_succeeded($event->data->object);
                    break;
                case 'payment_intent.payment_failed':
                    $this->handle_payment_intent_failed($event->data->object);
                    break;
                case 'customer.subscription.created':
                    $this->handle_subscription_created($event->data->object);
                    break;
                case 'customer.subscription.updated':
                    $this->handle_subscription_updated($event->data->object);
                    break;
                case 'customer.subscription.deleted':
                    $this->handle_subscription_deleted($event->data->object);
                    break;
                default:
                    // Unexpected event type
                    error_log('Received unknown event type: ' . $event->type);
            }
            
            // Return success response
            return new WP_REST_Response(array('status' => 'success'), 200);
        } catch (\UnexpectedValueException $e) {
            // Invalid payload
            error_log('Webhook error: ' . $e->getMessage());
            return new WP_REST_Response(array('status' => 'error', 'message' => 'Invalid payload'), 400);
        } catch (\Stripe\Exception\SignatureVerificationException $e) {
            // Invalid signature
            error_log('Webhook error: ' . $e->getMessage());
            return new WP_REST_Response(array('status' => 'error', 'message' => 'Invalid signature'), 400);
        } catch (Exception $e) {
            // Other error
            error_log('Webhook error: ' . $e->getMessage());
            return new WP_REST_Response(array('status' => 'error', 'message' => $e->getMessage()), 500);
        }
    }

    /**
     * Handle payment intent succeeded event
     *
     * @param object $payment_intent Payment intent object
     */
    private function handle_payment_intent_succeeded($payment_intent) {
        // Get metadata
        $metadata = $payment_intent->metadata;
        
        // Check if this is a subscription payment
        if (isset($metadata->plan_id)) {
            // Update subscription status
            global $wpdb;
            $subscription_table = $wpdb->prefix . 'subscriptions';
            
            $wpdb->update(
                $subscription_table,
                array(
                    'status' => 'active',
                    'payment_id' => $payment_intent->id,
                ),
                array(
                    'payment_id' => $payment_intent->id,
                )
            );
            
            // Log the event
            error_log('Payment succeeded for subscription: ' . $payment_intent->id);
        }
    }

    /**
     * Handle payment intent failed event
     *
     * @param object $payment_intent Payment intent object
     */
    private function handle_payment_intent_failed($payment_intent) {
        // Get metadata
        $metadata = $payment_intent->metadata;
        
        // Check if this is a subscription payment
        if (isset($metadata->plan_id)) {
            // Update subscription status
            global $wpdb;
            $subscription_table = $wpdb->prefix . 'subscriptions';
            
            $wpdb->update(
                $subscription_table,
                array(
                    'status' => 'failed',
                ),
                array(
                    'payment_id' => $payment_intent->id,
                )
            );
            
            // Log the event
            error_log('Payment failed for subscription: ' . $payment_intent->id);
        }
    }

    /**
     * Handle subscription created event
     *
     * @param object $subscription Subscription object
     */
    private function handle_subscription_created($subscription) {
        // Log the event
        error_log('Subscription created: ' . $subscription->id);
    }

    /**
     * Handle subscription updated event
     *
     * @param object $subscription Subscription object
     */
    private function handle_subscription_updated($subscription) {
        // Update subscription status
        global $wpdb;
        $subscription_table = $wpdb->prefix . 'subscriptions';
        
        // Get the status based on Stripe subscription status
        $status = 'active';
        if ($subscription->status === 'canceled' || $subscription->status === 'unpaid') {
            $status = 'canceled';
        } else if ($subscription->status === 'past_due') {
            $status = 'past_due';
        }
        
        // Update the subscription
        $wpdb->update(
            $subscription_table,
            array(
                'status' => $status,
                'end_date' => date('Y-m-d H:i:s', $subscription->current_period_end),
            ),
            array(
                'payment_id' => $subscription->id,
            )
        );
        
        // Log the event
        error_log('Subscription updated: ' . $subscription->id . ' - Status: ' . $status);
    }

    /**
     * Handle subscription deleted event
     *
     * @param object $subscription Subscription object
     */
    private function handle_subscription_deleted($subscription) {
        // Update subscription status
        global $wpdb;
        $subscription_table = $wpdb->prefix . 'subscriptions';
        
        $wpdb->update(
            $subscription_table,
            array(
                'status' => 'canceled',
            ),
            array(
                'payment_id' => $subscription->id,
            )
        );
        
        // Log the event
        error_log('Subscription deleted: ' . $subscription->id);
    }
} 