<?php

namespace SGC\eGiftCard\Http\Controller;

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

use SGC\eGiftCard\Http\Request\ValidatorHandler;

class CartController extends BaseController
{
    public function add(): \WP_REST_Response
    {
        if (! class_exists('WooCommerce')) {
            return $this->response(array(
                'success' => false,
                'message' => 'WooCommerce is not active. Contact site administrator.',
                'data'    => [],
            ) );
        }

        if (null === WC()->cart) {
            wc_load_cart();
            WC()->cart->get_cart();
        }
        
        // Validate the cart data using a custom validator
        $errors = ValidatorHandler::validateCartData($this->request);

        if (count($errors) > 0) {
            return $this->response($errors, 403);
        }
        
        $settings = self::getOption('sgc_smart_gift_general_settings', []);
        $allowed_with_others = isset($settings['sgc_allow_with_others']) ? $settings['sgc_allow_with_others'] : 'yes';
       
        if ( $allowed_with_others === 'no' ) {
            // Check if cart has other products
            if ( ! WC()->cart->is_empty() ) {
                return $this->response(array(
                    'success' => false,
                    'message' => 'You cannot add a Gift Card to the cart with other products.',
                    'data'    => [],
                ) );
            }
        }

        // Handle file upload if a custom file is uploaded
        //Nonce verification is not required here as the request is made using rest api and nonce already verified there
        if ( ! empty($_FILES['selected_file']['name']) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $selected_file = '_temp_' . self::handle_file_upload('selected_file', SMART_GIFT_CARD_PLUGIN_ASSET_ID . '/' . '_temp');
        } else {
            $selected_file = sanitize_text_field($this->request->get('selected_file'));
        }

        // Check if file selection is empty
        if ( empty($selected_file) ) {
            return $this->response(
                array(
                    'success' => false,
                    'message' => 'No design file selected',
                    'data'    => [],
                ),
            );
        }

        // Prepare the gift card data to be added to the cart
        $gift_card_data = $this->getCartData();
        $gift_card_data['design_url'] = $selected_file;
        $gift_card_amount = $gift_card_data['gift_amount'];

        // Create a unique key for this custom gift card item
        $unique_key = 'gift_card_' . md5(wp_json_encode($gift_card_data));
        $cart_page_url = wc_get_cart_url();
        $product_id = intval($this->request->get('product_id'));

        // Add the gift card to the WooCommerce cart
        WC()->cart->add_to_cart($product_id, 1, 0, array(), array(
            'gift_card_data' => $gift_card_data,
            'unique_key'     => $unique_key,
            'custom_price'   => $gift_card_amount,
        ));

        // Return a success response
        return $this->response(
            array(
                'success' => true,
                'message' => 'Item added to cart successfully!',
                'data'    => [
                    'redirect_url' => $cart_page_url
                ],
            )
        );
    }


    public function update(): \WP_REST_Response
    {
        if (! class_exists('WooCommerce')) {
            return $this->response(array(
                'success' => false,
                'message' => 'WooCommerce is not active. Contact site administrator.',
                'data'    => [],
            ) );
        }

        if (null === WC()->cart) {
            wc_load_cart();
            WC()->cart->get_cart();
        }
        
        $errors = ValidatorHandler::validateCartData( $this->request );

        if ( count( $errors ) > 0 ) {
            return $this->response( $errors, 403 );
        }

        //Custom file uploaded
        //Nonce verification is not required here as the request is made using rest api and nonce already verified there
        if (isset($_FILES['selected_file']) && !empty($_FILES['selected_file']['name'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $selected_file = '_temp_' . self::handle_file_upload('selected_file', SMART_GIFT_CARD_PLUGIN_ASSET_ID . '/' . '_temp');
        } else {
            $selected_file = sanitize_text_field($this->request->get('selected_file'));
        }

        if ( empty( $selected_file ) ) {
            return $this->response(
                array(
                    'success' => false,
                    'message' => 'No design file selected',
                    'data'    => [],
                ),
            );
        }

        $gift_card_data = $this->getCartData();
        $gift_card_data['design_url'] = $selected_file;
        $gift_card_amount = $gift_card_data['gift_amount'];
        $unique_key = sanitize_text_field( $this->request->get('unique_key') );
        $cart_page_url = wc_get_cart_url();

        // Loop through cart items to find the item with the matching unique key
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
            if (isset($cart_item['unique_key']) && $cart_item['unique_key'] === $unique_key) {
                WC()->cart->cart_contents[$cart_item_key]['gift_card_data'] = $gift_card_data;
                WC()->cart->cart_contents[$cart_item_key]['data']->set_price($gift_card_amount);
                WC()->cart->calculate_totals();
                break;
            }
        }

        return $this->response(
            array(
                'success' => true,
                'message' => 'Item added to cart successfully!',
                'data'    => [
                    'redirect_url' => $cart_page_url
                ],
            )
        );
    }

    private function getCartData() {
        $gift_card_amount = floatval( $this->request->get('gift_amount') );
        return array(
            'gift_amount'        => $gift_card_amount,
            'recipient_name'     => sanitize_text_field( $this->request->get('recipient_name') ),
            'recipient_email'    => sanitize_email( $this->request->get('recipient_email') ),
            'gift_message'       => sanitize_text_field( $this->request->get('gift_message') ),
            'sender_name'        => sanitize_text_field( $this->request->get('sender_name') ),
            'delivery_date'      => sanitize_text_field( $this->request->get('delivery_date') ),
            'design_type'        => sanitize_text_field( $this->request->get('design_type') ),
        );
    }
}