<?php

namespace SGC\eGiftCard\Http\Controller;

defined('ABSPATH') || exit; // Prevent direct file access.

use SGC\eGiftCard\Http\Model\GiftEvent;
use SGC\eGiftCard\Http\Controller\BaseController;

class SettingsController extends BaseController
{
    /**
     * Retrieve and return plugin settings.
     *
     * @return mixed Response data.
     */
    public function index( \WP_REST_Request $request )
    {
        $settings = self::getOption('sgc_smart_gift_general_settings', []);
        $design_settings = $settings['design_settings'] ?? [];
        $uniqueOrderId = sanitize_text_field($request->get_param('uniqueOrderId'));
        $gift_message = $design_settings['initial_message'] ?  $design_settings['initial_message'] : __('Your kindness, love, and warmth light up my life every day. This gift is a small token of my appreciation for all the joy you bring. May it brighten your day as much as you brighten mine!', 'smart-gift-card');
        $gift_card_background = $design_settings['gift_card_background'] ?? '';
        $gift_card_data = array(
            'gift_amount'      => '0.00',
            'recipient_name'   => '',
            'recipient_email'  => '',
            'gift_message'     => $gift_message,
            'sender_name'      => '',
            'delivery_date'    => gmdate('Y-m-d'),
            'design_url'       => '',
            'design_type'      => 'static'
        );

        $options = GiftEvent::getRandTenItem();
        $occasions = self::get_event_list();

        $raw = maybe_unserialize(isset($settings['sgc_allowed_occasions']) ? $settings['sgc_allowed_occasions'] : []);
        $sgc_allowed_occasions = [];
        
        if ( is_array($raw) && ! empty($raw) ) {
            $sgc_allowed_occasions = json_decode(stripslashes($raw[0]), true);
        }

        if( ! empty( $sgc_allowed_occasions ) ) {
            $new_occations = [];
            foreach ($sgc_allowed_occasions as $key) {
                if (isset($occasions[$key])) {
                    $new_occations[$key] = $occasions[$key];
                }
            }

            if( ! empty( $new_occations ) ) {
                $occasions = $new_occations;
                //Filter event data based on allowed occasions
                $filtered_event_data = [];
                foreach ( $options as $event ) {
                    // Check if event_name is a key in $occasions
                    if ( isset($occasions[$event->event_name]) ) {
                        $filtered_event_data[] = $event;
                    }
                }

                $options = $filtered_event_data;
            }
        }

        $occasions =  apply_filters( 'smart_gift_card_occasions_list' , $occasions );
        $options =  apply_filters( 'smart_gift_card_event_option_list' , $options );
        
        if ( $uniqueOrderId ) {
            if ( ! class_exists('WooCommerce') ) {
                return $this->response('WooCommerce is not loaded.', 500);
            }

            if ( is_null(WC()->cart) ) {
                wc_load_cart();
            }
            
            foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( isset($cart_item['unique_key']) && $cart_item['unique_key'] === $uniqueOrderId ) {
                    $gift_card_data = $cart_item['gift_card_data'];
                    break;
                }
            }
        }

        $selected_option = [
            'gift_amount'       => $gift_card_data['gift_amount'],
            'recipient_name'    => $gift_card_data['recipient_name'],
            'recipient_email'   => $gift_card_data['recipient_email'],
            'gift_message'      => $gift_card_data['gift_message'],
            'sender_name'       => $gift_card_data['sender_name'],
            'delivery_date'     => $gift_card_data['delivery_date'],
            'design_url'        => $gift_card_data['design_url'],
            'design_type'       => $gift_card_data['design_type'],
            'unique_key'        => $uniqueOrderId,
            'gift_image'       => $gift_card_background,
        ];

        $selected_option =  apply_filters( 'smart_gift_card_selected_option_data' , $selected_option );

        return $this->response([
            'options' => $options,
            'occasions' => $occasions,
            'selected_option' => $selected_option
        ]);
    }

    /**
     * Retrieve and return the list of events.
     *
     * @return array List of events.
     */
    public function design_list()
    {
        $giftEvent = GiftEvent::getInstance();

        $eventData = $giftEvent::all();
        $sgc_allowed_occasions = self::get_event_list();
        $settings = self::getOption('sgc_smart_gift_general_settings', []);
        $raw = maybe_unserialize(isset($settings['sgc_allowed_occasions']) ? $settings['sgc_allowed_occasions'] : []);
        $sgc_allowed_occasions = [];
        
        if ( is_array($raw) && ! empty($raw) ) {
            $sgc_allowed_occasions = json_decode($raw[0], true);
        }
        $occasions = self::get_event_list();
        if( ! empty( $sgc_allowed_occasions ) ) {
            $new_occations = [];
            foreach ($sgc_allowed_occasions as $key) {
                if (isset($occasions[$key])) {
                    $new_occations[$key] = $occasions[$key];
                }
            }

            if( ! empty( $new_occations ) ) {
                $occasions = $new_occations;
                //Filter event data based on allowed occasions
                $filtered_event_data = [];
                foreach ( $eventData as $event ) {
                    // Check if event_name is a key in $occasions
                    if ( isset($occasions[$event->event_name]) ) {
                        $filtered_event_data[] = $event;
                    }
                }

                $eventData = $filtered_event_data;
            }
        }

        return $this->response([
            'design_list' => $eventData,
            'occasions' => $occasions,
        ]);
    }
}
