<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Ajax\Handler;

use Context;
use Customer;
use Simplyin;
use SimplyIn\Ajax\AjaxActionInterface;
use SimplyIn\Ajax\AjaxRequest;
use SimplyIn\Ajax\Service\CheckoutSessionService;
use SimplyIn\Ajax\Service\DeliveryFormRenderer;
use SimplyIn\Api\SimplyInApiClient;
use SimplyIn\Session\SimplyInSessionInterface;
use Validate;

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

final class SubmitEmailHandler implements AjaxActionInterface
{
    public function __construct(
        private readonly SimplyInApiClient $api,
        private readonly Simplyin $module,
        private readonly Context $context,
        private readonly SimplyInSessionInterface $session,
        private readonly CheckoutSessionService $checkoutSession,
        private readonly DeliveryFormRenderer $renderer,
    ) {
    }

    public function name(): string
    {
        return 'submitEmail';
    }

    public function execute(AjaxRequest $request): array
    {
        $email = $request->getString('email');
        if ($request->getBool('force_login') && $this->context->customer !== null) {
            $email = (string) $this->context->customer->email;
        }

        if ($request->getInt('login')) {
            $customer = new Customer();
            $customer->getByEmail($email);
            if (!($customer->id && !$customer->is_guest && $customer->active)) {
                // Use the same 'error' key as the API branch below (line ~83) and the SMS/email
                // handlers, so the front's `data.error === 'NOT_FOUND'` neutral path fires instead of
                // the generic-error catch-all — a not-registered login email is expected, not a fault.
                return ['error' => 'NOT_FOUND'];
            }
        }
        if ($request->getInt('logout')) {
            $this->module->logout();
        }

        // Email-first shop-login challenge: when the typed email belongs to a registered
        // PrestaShop account and the browser is not already logged in, try the by-email OTP
        // challenge before the SMS/submitEmail flow — the shopper verifies a code we e-mail them
        // and is logged into the shop account without any SMS. Any non-ok outcome falls through
        // to the existing SMS flow unchanged.
        if ($this->shouldAttemptEmailFirstChallenge($email)) {
            $challengeRaw = $this->api->apiCall(
                ['email' => $email, 'language' => strtoupper((string) $this->context->language->iso_code)],
                'POST',
                'checkout/sendShopLoginEmailOtpCommerce',
            );
            $challenge = is_array($challengeRaw) ? $challengeRaw : [];
            if (!empty($challenge['ok'])) {
                // Pin the challenge email server-side: verify/resend read it from the session,
                // never from the request (see VerifyShopLoginEmailOtpHandler).
                $this->checkoutSession->storeShopLoginChallengeEmail($email);

                return [
                    'success' => true,
                    'show_popup' => true,
                    'shop_login_challenge' => true,
                    'html' => $this->renderer->renderShopLoginChallenge($challenge),
                ];
            }
        }

        // Email-first did not start a challenge (precheck false or send not ok) and we now fall
        // through to the SMS flow — drop any pin from an earlier email-first attempt so a later
        // resend/verify can't target a stale email/mode after the shopper changed the address.
        // A started challenge returns above, keeping its pin intact.
        $this->checkoutSession->clearShopLoginChallengeEmail();

        $raw = $this->api->apiCall(['email' => $email, 'language' => strtoupper((string) $this->context->language->iso_code)], 'POST', 'checkout/submitEmail');
        $response = is_array($raw) ? $raw : [];
        $code = $response['code'] ?? null;
        if ($code === 'NOT_FOUND' || $code === 'BAD_REQUEST') {
            $this->module->logout();

            return ['error' => $code];
        }

        $this->storeNotificationId($email, $response);

        return [
            'success' => true,
            'html' => $this->renderer->renderPopupConfirmation($response),
            'show_popup' => true,
            'userUsedPushNotifications' => $response['userUsedPushNotifications'] ?? '',
        ];
    }

    /**
     * Local precheck for the email-first challenge: only a registered (non-guest, active)
     * PrestaShop account can gain anything from the shop-login challenge, and an
     * already-logged-in browser doesn't need it. Anything else goes straight to the SMS flow —
     * no backend call, so a typed email that has no shop account cannot trigger an OTP e-mail
     * from this shop.
     */
    private function shouldAttemptEmailFirstChallenge(string $email): bool
    {
        // The by-email challenge and the token-mode (post-SMS) challenge are mutually exclusive —
        // the OTP handlers prefer token mode whenever a checkout authToken is held. If a token
        // already exists, stay on the token flow.
        if ($this->checkoutSession->getAuthToken() !== false) {
            return false;
        }
        // A malformed email would make Customer::getByEmail throw / behave oddly; bail before touching it.
        if ($email === '' || !Validate::isEmail($email)) {
            return false;
        }
        $current = $this->context->customer;
        if ($current !== null && (bool) $current->isLogged()) {
            return false;
        }
        $customer = new Customer();
        $customer->getByEmail($email);

        return (bool) ($customer->id && !$customer->is_guest && $customer->active);
    }

    /**
     * @param array<string, mixed> $response
     */
    private function storeNotificationId(string $email, array $response): void
    {
        if (!empty($response['notificationTokenId'])) {
            $this->session->set('simplyin_notifiaction_token_id', (string) $response['notificationTokenId']);
        }
        $this->session->set('simplyin_email', $email);
    }
}
