<?php
/**
 * Subscriptions REST Controller
 *
 * @package Invizo\SubscriptionsLite\REST_API
 */

namespace Invizo\SubscriptionsLite\REST_API;

use Invizo\SubscriptionsLite\Gateway\StripeGateway;
use WP_Error;
use WP_Query;
use WP_REST_Controller;
use WP_REST_Server;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Subscriptions_Controller extends WP_REST_Controller {

    public function __construct() {
        $this->namespace = 'invizo-subs/v1';
        $this->rest_base = 'subscriptions';
    }

    public function register_routes() {
        register_rest_route( $this->namespace, '/' . $this->rest_base, array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_items' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
        ) );

        register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_item' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
            array(
                'methods'             => WP_REST_Server::EDITABLE,
                'callback'            => array( $this, 'update_item' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
            array(
                'methods'             => WP_REST_Server::DELETABLE,
                'callback'            => array( $this, 'delete_item' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
        ) );
    }

    public function permissions_check( $request ) {
        return current_user_can( 'manage_options' );
    }

    public function get_items( $request ) {
        // Query the invizo_sub CPT
        $args = array(
            'post_type'      => 'invizo_sub',
            'posts_per_page' => 20,
            'post_status'    => 'any'
        );
        $query = new WP_Query( $args );

        $data = array();
        foreach ( $query->posts as $post ) {
            if ( class_exists( StripeGateway::class, false ) && ! get_post_meta( $post->ID, '_next_payment_date', true ) ) {
                StripeGateway::sync_invizo_sub_from_stripe( $post->ID );
            }
            $plan_id = get_post_meta( $post->ID, '_plan_id', true );
            $plan_title = $plan_id ? get_the_title( $plan_id ) : 'N/A';
            
            // Look up WooCommerce product meta or Custom generic engine meta
            $plan_price = $plan_id ? get_post_meta( $plan_id, '_price', true ) : '0.00';
            
            // Woo Product approach:
            $plan_interval_count = get_post_meta( $plan_id, '_invizo_sub_interval_count', true ) ?: '1';
            $plan_interval_period = get_post_meta( $plan_id, '_invizo_sub_interval_period', true ) ?: 'Month';
            
            // Standalone Plan logic fallback:
            if ( ! get_post_meta( $plan_id, '_invizo_sub_interval_period', true ) && get_post_meta( $plan_id, '_interval', true ) ) {
                $plan_interval_period = get_post_meta( $plan_id, '_interval', true );
            }

            $amount_str = '$' . number_format((float)$plan_price, 2) . ' / ' . $plan_interval_count . ' ' . ucfirst($plan_interval_period);
            
            $user_id = get_post_meta( $post->ID, '_wp_user_id', true );
            $user_info = get_userdata( $user_id );
            $user_name = $user_info ? $user_info->display_name : (get_post_meta( $post->ID, '_customer_email', true ) ?: 'Guest');

            $woo_order_id = get_post_meta( $post->ID, '_woo_order_id', true );
            $woo_order_url = '';
            if ( $woo_order_id && function_exists( 'wc_get_order' ) ) {
                $order = wc_get_order( $woo_order_id );
                if ( $order ) {
                    $woo_order_url = $order->get_edit_order_url();
                }
            }

            $data[] = array(
                'id'            => $post->ID,
                'order_id'      => $woo_order_id ?: '---',
                'order_url'     => $woo_order_url,
                'status'        => ucfirst( get_post_meta( $post->ID, '_status', true ) ?: 'Active' ),
                'product_name'  => $plan_title,
                'amount'        => $amount_str,
                'user_name'     => $user_name,
                'next_payment'  => get_post_meta( $post->ID, '_next_payment_date', true ) ?: '---',
                'expiry_date'   => get_post_meta( $post->ID, '_expiry_date', true ) ?: '---',
            );
        }

        return rest_ensure_response( $data );
    }

    public function get_item( $request ) {
        // Implement single fetch
        return rest_ensure_response( array() );
    }

    public function update_item( $request ) {
        // Implement update
        return rest_ensure_response( array() );
    }

    /**
     * Permanently delete a subscription CPT record (local dashboard only; does not cancel Stripe).
     *
     * @param WP_REST_Request $request Request.
     * @return WP_REST_Response|WP_Error
     */
    public function delete_item( $request ) {
        $id = (int) $request['id'];
        $post = get_post( $id );

        if ( ! $post || $post->post_type !== 'invizo_sub' ) {
            return new WP_Error(
                'invizo_rest_invalid_subscription',
                __( 'Subscription not found.', 'invizo-subscriptions-lite' ),
                array( 'status' => 404 )
            );
        }

        $deleted = wp_delete_post( $id, true );

        if ( ! $deleted ) {
            return new WP_Error(
                'invizo_rest_delete_failed',
                __( 'Could not delete subscription.', 'invizo-subscriptions-lite' ),
                array( 'status' => 500 )
            );
        }

        return rest_ensure_response(
            array(
                'deleted' => true,
                'id'      => $id,
            )
        );
    }
}
