<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Controller\Api;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Check email controller
 *
 * Verifies if email exists in SimplyIN and sends OTP
 */
class CheckEmail implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    /**
     * @var ApiClient
     */
    private $apiClient;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * Constructor
     *
     * @param JsonFactory $resultJsonFactory
     * @param ApiClient $apiClient
     * @param RequestInterface $request
     * @param LoggerInterface $logger
     */
    public function __construct(
        JsonFactory $resultJsonFactory,
        ApiClient $apiClient,
        RequestInterface $request,
        LoggerInterface $logger
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->apiClient = $apiClient;
        $this->request = $request;
        $this->logger = $logger;
    }

    /**
     * Execute check email action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();

        try {
            $data = json_decode($this->request->getContent(), true);
            $email = $data['email'] ?? '';

            if (empty($email)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Email is required')
                ]);
            }

            // Call Simply.IN API to check email and send OTP (default method: SMS or push)
            $response = $this->apiClient->submitEmail($email);

            if ($response['success']) {
                $responseData = $response['data'] ?? [];
                
                // Check if user uses push notifications (matching WordPress plugin logic)
                $userUsedPushNotifications = isset($responseData['userUsedPushNotifications'])
                    && $responseData['userUsedPushNotifications'] === true;
                
                // Get notification token ID for push notification polling
                $notificationTokenId = $responseData['notificationTokenId'] ?? null;
                
                return $result->setData([
                    'success' => true,
                    'userExists' => true,
                    'message' => __('If an account exists, a verification code has been sent.'),
                    'data' => $responseData,
                    'userUsedPushNotifications' => $userUsedPushNotifications,
                    'notificationTokenId' => $notificationTokenId,
                    // Also include code and masked data for OTP modal display
                    'code' => $responseData['code'] ?? null,
                    'maskedData' => $responseData['data'] ?? null
                ]);
            } else {
                // Security: use identical response structure and timing-neutral message
                // to prevent email enumeration. The frontend distinguishes via userExists flag.
                if (isset($response['error']) && $response['error'] === 'USER_NOT_FOUND') {
                    return $result->setData([
                        'success' => true,
                        'userExists' => false,
                        'message' => __('If an account exists, a verification code has been sent.')
                    ]);
                }

                return $result->setData([
                    'success' => false,
                    'message' => __('Unable to process request. Please try again.')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN CheckEmail: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }
}
