<?php
namespace App\Services;

class PaymentService
{
    private string $apiKey;
    private string $secretKey;
    private string $baseUrl;

    public function __construct()
    {
        $settings = \App\Models\Settings::all();
        $this->apiKey    = trim($settings['iyzico_api_key'] ?? '');
        $this->secretKey = trim($settings['iyzico_secret_key'] ?? '');
        
        $mode = $settings['iyzico_mode'] ?? 'sandbox';
        $this->baseUrl = $mode === 'production'
            ? 'https://api.iyzipay.com'
            : 'https://sandbox-api.iyzipay.com';
    }

    public function isConfigured(): bool
    {
        return !empty($this->apiKey) && !empty($this->secretKey);
    }

    public function pay(array $cardData, array $orderData): array
    {
        if (!$this->isConfigured()) {
            return [
                'success' => false,
                'message' => 'Ödeme sistemi henüz yapılandırılmamış. Lütfen yöneticiyle iletişime geçin.',
                'payment_id' => null,
                'raw' => []
            ];
        }

        // Initialize SDK Options
        $options = new \Iyzipay\Options();
        $options->setApiKey($this->apiKey);
        $options->setSecretKey($this->secretKey);
        $options->setBaseUrl($this->baseUrl);

        // Create Payment Request
        $request = new \Iyzipay\Request\CreatePaymentRequest();
        $request->setLocale(\Iyzipay\Model\Locale::TR);
        $request->setConversationId('EVR' . time() . rand(1000, 9999));
        
        $totalPrice = number_format((float)$orderData['total'], 2, '.', '');
        $request->setPrice($totalPrice);
        $request->setPaidPrice($totalPrice);
        $request->setCurrency(\Iyzipay\Model\Currency::TL);
        $request->setInstallment(1);
        $request->setBasketId('B' . time());
        $request->setPaymentChannel(\Iyzipay\Model\PaymentChannel::WEB);
        $request->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);

        // Payment Card
        $paymentCard = new \Iyzipay\Model\PaymentCard();
        $paymentCard->setCardHolderName($cardData['holder_name']);
        $paymentCard->setCardNumber(preg_replace('/\D/', '', $cardData['card_number']));
        $paymentCard->setExpireMonth(str_pad($cardData['expire_month'], 2, '0', STR_PAD_LEFT));
        $paymentCard->setExpireYear(strlen($cardData['expire_year']) === 2 ? '20' . $cardData['expire_year'] : $cardData['expire_year']);
        $paymentCard->setCvc($cardData['cvc']);
        $paymentCard->setRegisterCard(0);
        $request->setPaymentCard($paymentCard);

        // Buyer
        $names = $this->splitName($orderData['customer_name'] ?? '');
        $buyer = new \Iyzipay\Model\Buyer();
        $buyer->setId('BY' . time());
        $buyer->setName($names['first']);
        $buyer->setSurname($names['last']);
        $buyer->setGsmNumber($this->formatPhone($orderData['customer_phone'] ?? ''));
        $buyer->setEmail($orderData['customer_email'] ?? 'test@example.com');
        $buyer->setIdentityNumber('74300864791');
        $buyer->setLastLoginDate(date('Y-m-d H:i:s'));
        $buyer->setRegistrationDate(date('Y-m-d H:i:s'));
        $buyer->setRegistrationAddress($orderData['customer_address'] ?? 'Teslimat Adresi');
        $buyer->setIp($orderData['customer_ip'] ?? '85.34.78.112');
        $buyer->setCity('Mugla'); 
        $buyer->setCountry('Turkey');
        $buyer->setZipCode('48400');
        $request->setBuyer($buyer);

        // Shipping Address
        $shippingAddress = new \Iyzipay\Model\Address();
        $shippingAddress->setContactName($orderData['customer_name']);
        $shippingAddress->setCity('Mugla');
        $shippingAddress->setCountry('Turkey');
        $shippingAddress->setAddress($orderData['customer_address'] ?? 'Teslimat Adresi');
        $shippingAddress->setZipCode('48400');
        $request->setShippingAddress($shippingAddress);

        // Billing Address
        $billingAddress = new \Iyzipay\Model\Address();
        $billingAddress->setContactName($orderData['customer_name']);
        $billingAddress->setCity('Mugla');
        $billingAddress->setCountry('Turkey');
        $billingAddress->setAddress($orderData['customer_address'] ?? 'Teslimat Adresi');
        $billingAddress->setZipCode('48400');
        $request->setBillingAddress($billingAddress);

        // Basket Items
        $basketItems = [];
        
        foreach ($orderData['items'] as $item) {
            $basketItem = new \Iyzipay\Model\BasketItem();
            $basketItem->setId((string)($item['product_id'] ?? 'ITEM'));
            $basketItem->setName(mb_substr($item['name'] ?? 'Urun', 0, 100));
            $basketItem->setCategory1("Genel");
            $basketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
            $basketItem->setPrice(number_format((float)($item['subtotal'] ?? 0), 2, '.', ''));
            $basketItems[] = $basketItem;
        }

        if (!empty($orderData['shipping_cost']) && (float)$orderData['shipping_cost'] > 0) {
            $basketItem = new \Iyzipay\Model\BasketItem();
            $basketItem->setId('SHIPPING');
            $basketItem->setName("Kargo Ucreti");
            $basketItem->setCategory1("Kargo");
            $basketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
            $basketItem->setPrice(number_format((float)$orderData['shipping_cost'], 2, '.', ''));
            $basketItems[] = $basketItem;
        }

        if (!empty($orderData['payment_fee']) && (float)$orderData['payment_fee'] > 0) {
            $basketItem = new \Iyzipay\Model\BasketItem();
            $basketItem->setId('PAYMENTFEE');
            $basketItem->setName("Islem Ucreti");
            $basketItem->setCategory1("Ucret");
            $basketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
            $basketItem->setPrice(number_format((float)$orderData['payment_fee'], 2, '.', ''));
            $basketItems[] = $basketItem;
        }

        $request->setBasketItems($basketItems);

        // Make the call
        $payment = \Iyzipay\Model\Payment::create($request, $options);
        
        $raw = json_decode($payment->getRawResult(), true);

        if ($payment->getStatus() === 'success') {
            return [
                'success' => true,
                'message' => 'Ödeme başarıyla alındı.',
                'payment_id' => $payment->getPaymentId(),
                'raw' => $raw
            ];
        }

        $errorMessage = $payment->getErrorMessage() ?? 'Ödeme işlemi başarısız oldu.';
        $errorCode = $payment->getErrorCode() ?? '';
        
        return [
            'success' => false,
            'message' => $this->translateError($errorCode, $errorMessage),
            'payment_id' => null,
            'raw' => $raw
        ];
    }

    private function splitName(string $fullName): array
    {
        $parts = preg_split('/\s+/', trim($fullName), 2);
        return [
            'first' => $parts[0] ?? 'Ad',
            'last'  => $parts[1] ?? 'Soyad',
        ];
    }

    private function formatPhone(string $phone): string
    {
        $phone = preg_replace('/\D/', '', $phone);
        if (strlen($phone) === 10 && str_starts_with($phone, '5')) {
            return '+90' . $phone;
        }
        if (strlen($phone) === 11 && str_starts_with($phone, '0')) {
            return '+9' . substr($phone, 1);
        }
        if (!str_starts_with($phone, '+')) {
            return '+90' . $phone; // Default prefix if absolutely stripped
        }
        return '+' . $phone;
    }

    private function translateError(string $code, string $defaultMessage): string
    {
        $translations = [
            '10051' => 'Kart limiti yetersiz. Lütfen bankanızla iletişime geçin.',
            '10005' => 'İşlem onaylanmadı. Lütfen kart bilgilerinizi kontrol edin.',
            '10012' => 'Geçersiz kart numarası. Lütfen kontrol edin.',
            '10054' => 'Kartınızın süresi dolmuş.',
            '10057' => 'Kart sahibi bu işlemi yapamaz.',
            '10058' => 'Bu işlem terminalinize tanımlı değil.',
            '10034' => 'Dolandırıcılık şüphesi nedeniyle kart bloke.',
            '12'    => 'Geçersiz işlem.',
        ];

        return $translations[$code] ?? $defaultMessage;
    }
}
