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

namespace Invizo\SubscriptionsLite\REST_API;

use WP_Error;
use WP_Query;
use WP_REST_Controller;
use WP_REST_Server;

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

class Plans_Controller extends WP_REST_Controller {

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

    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' ),
            ),
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'create_item' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
        ) );

        register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
            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 ) {
        $args = array(
            'post_type'      => 'invizo_plan',
            'posts_per_page' => 50,
            'post_status'    => 'publish'
        );
        $query = new WP_Query( $args );

        $data = array();
        foreach ( $query->posts as $post ) {
            $data[] = array(
                'id'           => $post->ID,
                'title'        => $post->post_title,
                'description'  => $post->post_content,
                'price'        => get_post_meta( $post->ID, '_price', true ),
                'interval'     => get_post_meta( $post->ID, '_interval', true ) ?: 'month',
                'signup_fee'   => get_post_meta( $post->ID, '_signup_fee', true ) ?: '',
                'trial_period' => get_post_meta( $post->ID, '_trial_period', true ) ?: '',
                'preview_url'  => get_post_meta( $post->ID, '_preview_url', true ) ?: '',
                'media'        => get_post_meta( $post->ID, '_media', true ) ?: '',
                'tags'         => get_post_meta( $post->ID, '_tags', true ) ?: '',
            );
        }

        // Return empty array if no plans exist

        return rest_ensure_response( $data );
    }

    public function create_item( $request ) {
        // Safety net: if an ID is provided, treat this request as an update.
        // This prevents accidental duplicate plans when the admin UI should edit.
        $existing_id = absint( $request->get_param( 'id' ) );
        if ( $existing_id > 0 ) {
            $existing_post = get_post( $existing_id );
            if ( $existing_post && $existing_post->post_type === 'invizo_plan' ) {
                $request->set_param( 'id', $existing_id );
                return $this->update_item( $request );
            }
        }

        $title        = sanitize_text_field( $request->get_param( 'title' ) );
        $description  = wp_kses_post( $request->get_param( 'description' ) );
        $price        = floatval( $request->get_param( 'price' ) );
        $interval     = sanitize_text_field( $request->get_param( 'interval' ) );
        $signup_fee   = sanitize_text_field( $request->get_param( 'signup_fee' ) );
        $trial_period = sanitize_text_field( $request->get_param( 'trial_period' ) );
        $preview_url  = esc_url_raw( $request->get_param( 'preview_url' ) );
        $media        = esc_url_raw( $request->get_param( 'media' ) );
        $tags         = sanitize_text_field( $request->get_param( 'tags' ) );

        if ( empty( $title ) || empty( $price ) ) {
            return new WP_Error( 'invalid_data', 'Title and price are required.', array( 'status' => 400 ) );
        }

        $post_id = wp_insert_post( array(
            'post_title'   => $title,
            'post_content' => $description,
            'post_type'    => 'invizo_plan',
            'post_status'  => 'publish'
        ) );

        if ( is_wp_error( $post_id ) ) {
            return $post_id;
        }

        update_post_meta( $post_id, '_price', $price );
        update_post_meta( $post_id, '_interval', $interval ?: 'month' );
        update_post_meta( $post_id, '_signup_fee', $signup_fee );
        update_post_meta( $post_id, '_trial_period', $trial_period );
        update_post_meta( $post_id, '_preview_url', $preview_url );
        update_post_meta( $post_id, '_media', $media );
        update_post_meta( $post_id, '_tags', $tags );

        return rest_ensure_response( array(
            'id'           => $post_id,
            'title'        => $title,
            'description'  => $description,
            'price'        => $price,
            'interval'     => $interval ?: 'month',
            'signup_fee'   => $signup_fee,
            'trial_period' => $trial_period,
            'preview_url'  => $preview_url,
            'media'        => $media,
            'tags'         => $tags,
            'message'      => 'Subscription plan created successfully'
        ) );
    }

    public function update_item( $request ) {
        $id = (int) $request['id'];
        $post = get_post($id);
        
        if ( empty($post) || $post->post_type !== 'invizo_plan' ) {
            return new WP_Error( 'not_found', 'Plan not found.', array( 'status' => 404 ) );
        }

        $payload = $request->get_json_params();
        if ( ! is_array( $payload ) || $payload === array() ) {
            $raw_body = $request->get_body();
            if ( is_string( $raw_body ) && $raw_body !== '' ) {
                $decoded = json_decode( $raw_body, true );
                if ( is_array( $decoded ) ) {
                    $payload = $decoded;
                }
            }
        }
        if ( ! is_array( $payload ) ) {
            $payload = array();
        }

        $request_has_field = static function( $key ) use ( $request, $payload ) {
            return $request->has_param( $key ) || array_key_exists( $key, $payload );
        };

        $request_get_field = static function( $key ) use ( $request, $payload ) {
            if ( $request->has_param( $key ) ) {
                return $request->get_param( $key );
            }
            return array_key_exists( $key, $payload ) ? $payload[ $key ] : null;
        };

        if ( ! $request_has_field( 'title' )
            && ! $request_has_field( 'description' )
            && ! $request_has_field( 'price' )
            && ! $request_has_field( 'interval' )
            && ! $request_has_field( 'signup_fee' )
            && ! $request_has_field( 'trial_period' )
            && ! $request_has_field( 'preview_url' )
            && ! $request_has_field( 'media' )
            && ! $request_has_field( 'tags' ) ) {
            return new WP_Error(
                'invalid_data',
                'No plan fields were received for update.',
                array( 'status' => 400 )
            );
        }

        $title_raw        = $request_get_field( 'title' );
        $description_raw  = $request_get_field( 'description' );
        $price_raw        = $request_get_field( 'price' );
        $interval_raw     = $request_get_field( 'interval' );
        $signup_fee_raw   = $request_get_field( 'signup_fee' );
        $trial_period_raw = $request_get_field( 'trial_period' );
        $preview_url_raw  = $request_get_field( 'preview_url' );
        $media_raw        = $request_get_field( 'media' );
        $tags_raw         = $request_get_field( 'tags' );

        $title        = sanitize_text_field( $title_raw );
        $description  = wp_kses_post( $description_raw );
        $price        = ( null !== $price_raw && '' !== $price_raw ) ? floatval( $price_raw ) : null;
        $interval     = sanitize_text_field( $interval_raw );
        $signup_fee   = sanitize_text_field( $signup_fee_raw );
        $trial_period = sanitize_text_field( $trial_period_raw );
        $preview_url  = esc_url_raw( $preview_url_raw );
        $media        = esc_url_raw( $media_raw );
        $tags         = sanitize_text_field( $tags_raw );

        $update_args = array( 'ID' => $id );
        if ( $request_has_field( 'title' ) ) $update_args['post_title'] = $title;
        if ( $request_has_field( 'description' ) ) $update_args['post_content'] = $description;
        
        if ( count( $update_args ) > 1 ) {
            wp_update_post( $update_args );
        }

        if ( $request_has_field( 'price' ) ) update_post_meta( $id, '_price', $price );
        if ( $request_has_field( 'interval' ) ) update_post_meta( $id, '_interval', $interval ?: 'month' );
        if ( $request_has_field( 'signup_fee' ) ) update_post_meta( $id, '_signup_fee', $signup_fee );
        if ( $request_has_field( 'trial_period' ) ) update_post_meta( $id, '_trial_period', $trial_period );
        if ( $request_has_field( 'preview_url' ) ) update_post_meta( $id, '_preview_url', $preview_url );
        if ( $request_has_field( 'media' ) ) update_post_meta( $id, '_media', $media );
        if ( $request_has_field( 'tags' ) ) update_post_meta( $id, '_tags', $tags );
        clean_post_cache( $id );
        wp_cache_delete( $id, 'post_meta' );

        return rest_ensure_response( array(
            'id'       => $id,
            'message'  => 'Plan updated successfully'
        ) );
    }

    public function delete_item( $request ) {
        $id = (int) $request['id'];
        $post = get_post($id);

        if ( empty($post) || $post->post_type !== 'invizo_plan' ) {
            return new WP_Error( 'not_found', 'Plan not found.', array( 'status' => 404 ) );
        }

        wp_delete_post( $id, true ); // Force delete
        
        return rest_ensure_response( array(
            'deleted' => true,
            'message'  => 'Plan deleted successfully'
        ) );
    }
}
