<?php

namespace IyzicoIntegration;

require_once __DIR__ . '/../vendor/iyzico/iyzipay-php/IyzipayBootstrap.php';
\IyzipayBootstrap::init();

use Iyzipay\Options;
use Iyzipay\Model\ThreedsInitialize;
use Iyzipay\Model\ThreedsPayment;
use Iyzipay\Request\CreatePaymentRequest;
use Iyzipay\Request\CreateThreedsPaymentRequest;
use Iyzipay\Model\Buyer;
use Iyzipay\Model\Address;
use Iyzipay\Model\BasketItem;
use Iyzipay\Model\PaymentCard;

class IyzicoService
{
    private $options;
    private $config;

    public function __construct()
    {
        $this->config = require __DIR__ . '/../config/iyzico.php';
        $this->options = new Options();
        $this->options->setApiKey($this->config['api_key']);
        $this->options->setSecretKey($this->config['secret_key']);
        $this->options->setBaseUrl($this->config['base_url']);
    }

    /**
     * Initialize 3D Secure payment and get redirect URL
     */
    public function initializeThreedsPayment($paymentData)
    {
        $request = new CreatePaymentRequest();
        $request->setLocale(\Iyzipay\Model\Locale::TR);
        $request->setConversationId($paymentData['conversation_id']);
        $request->setPrice($paymentData['price']);
        $request->setPaidPrice($paymentData['paid_price']);
        $request->setCurrency(\Iyzipay\Model\Currency::TL);
        $request->setInstallment(1);
        $request->setBasketId($paymentData['basket_id']);
        $request->setPaymentChannel(\Iyzipay\Model\PaymentChannel::WEB);
        $request->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);
        $request->setCallbackUrl($this->config['callback_url']);

        // Payment Card
        $paymentCard = new PaymentCard();
        $paymentCard->setCardHolderName($paymentData['card']['holder_name']);
        $paymentCard->setCardNumber($paymentData['card']['number']);
        $paymentCard->setExpireMonth($paymentData['card']['expire_month']);
        $paymentCard->setExpireYear($paymentData['card']['expire_year']);
        $paymentCard->setCvc($paymentData['card']['cvc']);
        $paymentCard->setRegisterCard(0);
        $request->setPaymentCard($paymentCard);

        // Buyer Information
        $buyer = new Buyer();
        $buyer->setId($paymentData['buyer']['id']);
        $buyer->setName($paymentData['buyer']['name']);
        $buyer->setSurname($paymentData['buyer']['surname']);
        $buyer->setGsmNumber($paymentData['buyer']['gsm_number']);
        $buyer->setEmail($paymentData['buyer']['email']);
        $buyer->setIdentityNumber($paymentData['buyer']['identity_number']);
        $buyer->setLastLoginDate($paymentData['buyer']['last_login_date']);
        $buyer->setRegistrationDate($paymentData['buyer']['registration_date']);
        $buyer->setRegistrationAddress($paymentData['buyer']['registration_address']);
        $buyer->setIp($paymentData['buyer']['ip']);
        $buyer->setCity($paymentData['buyer']['city']);
        $buyer->setCountry($paymentData['buyer']['country']);
        $buyer->setZipCode($paymentData['buyer']['zip_code']);
        $request->setBuyer($buyer);

        // Shipping Address
        $shippingAddress = new Address();
        $shippingAddress->setContactName($paymentData['shipping_address']['contact_name']);
        $shippingAddress->setCity($paymentData['shipping_address']['city']);
        $shippingAddress->setCountry($paymentData['shipping_address']['country']);
        $shippingAddress->setAddress($paymentData['shipping_address']['address']);
        $shippingAddress->setZipCode($paymentData['shipping_address']['zip_code']);
        $request->setShippingAddress($shippingAddress);

        // Billing Address
        $billingAddress = new Address();
        $billingAddress->setContactName($paymentData['billing_address']['contact_name']);
        $billingAddress->setCity($paymentData['billing_address']['city']);
        $billingAddress->setCountry($paymentData['billing_address']['country']);
        $billingAddress->setAddress($paymentData['billing_address']['address']);
        $billingAddress->setZipCode($paymentData['billing_address']['zip_code']);
        $request->setBillingAddress($billingAddress);

        // Basket Items
        $basketItems = [];
        foreach ($paymentData['basket_items'] as $item) {
            $basketItem = new BasketItem();
            $basketItem->setId($item['id']);
            $basketItem->setName($item['name']);
            $basketItem->setCategory1($item['category1']);
            $basketItem->setCategory2($item['category2'] ?? '');
            $basketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
            $basketItem->setPrice($item['price']);
            $basketItems[] = $basketItem;
        }
        $request->setBasketItems($basketItems);

        $threedsInitialize = ThreedsInitialize::create($request, $this->options);

        if ($threedsInitialize->getStatus() == 'success') {
            return [
                'success' => true,
                'redirect_url' => $threedsInitialize->getHtmlContent(),
                'payment_id' => $threedsInitialize->getPaymentId(),
                'conversation_id' => $threedsInitialize->getConversationId()
            ];
        } else {
            return [
                'success' => false,
                'error' => $threedsInitialize->getErrorMessage(),
                'error_code' => $threedsInitialize->getErrorCode()
            ];
        }
    }

    /**
     * Complete 3D Secure payment after callback
     */
    public function completeThreedsPayment($callbackData)
    {
        $request = new CreateThreedsPaymentRequest();
        $request->setLocale(\Iyzipay\Model\Locale::TR);
        $request->setConversationId($callbackData['conversationId']);
        $request->setPaymentId($callbackData['paymentId']);

        $threedsPayment = ThreedsPayment::create($request, $this->options);

        if ($threedsPayment->getStatus() == 'success') {
            return [
                'success' => true,
                'payment_id' => $threedsPayment->getPaymentId(),
                'payment_status' => $threedsPayment->getPaymentStatus(),
                'fraud_status' => $threedsPayment->getFraudStatus(),
                'merchant_commission_rate' => $threedsPayment->getMerchantCommissionRate(),
                'merchant_commission_rate_amount' => $threedsPayment->getMerchantCommissionRateAmount(),
                'iyzi_commission_rate_amount' => $threedsPayment->getIyziCommissionRateAmount(),
                'iyzi_commission_fee' => $threedsPayment->getIyziCommissionFee(),
                'card_type' => $threedsPayment->getCardType(),
                'card_association' => $threedsPayment->getCardAssociation(),
                'card_family' => $threedsPayment->getCardFamily(),
                'bin_number' => $threedsPayment->getBinNumber(),
                'last_four_digits' => $threedsPayment->getLastFourDigits(),
                'auth_code' => $threedsPayment->getAuthCode(),
                'host_reference' => $threedsPayment->getHostReference()
            ];
        } else {
            return [
                'success' => false,
                'error' => $threedsPayment->getErrorMessage(),
                'error_code' => $threedsPayment->getErrorCode()
            ];
        }
    }

    /**
     * Validate payment data structure
     */
    public function validatePaymentData($data)
    {
        $required = [
            'conversation_id', 'price', 'paid_price', 'basket_id',
            'card', 'buyer', 'shipping_address', 'billing_address', 'basket_items'
        ];

        foreach ($required as $field) {
            if (!isset($data[$field])) {
                return ['valid' => false, 'error' => "Missing required field: {$field}"];
            }
        }

        // Validate card data
        $cardRequired = ['holder_name', 'number', 'expire_month', 'expire_year', 'cvc'];
        foreach ($cardRequired as $field) {
            if (!isset($data['card'][$field])) {
                return ['valid' => false, 'error' => "Missing required card field: {$field}"];
            }
        }

        return ['valid' => true];
    }
}
