<?php

namespace App\Services;

use App\Models\EventRegistration;

class PayUService
{
    /**
     * PayU Merchant Key
     *
     * @var string
     */
    protected $merchantKey;

    /**
     * PayU Merchant Salt
     *
     * @var string
     */
    protected $merchantSalt;

    /**
     * PayU Environment (test or live)
     *
     * @var string
     */
    protected $environment;

    /**
     * PayU Gateway URL
     *
     * @var string
     */
    protected $gatewayUrl;

    public function __construct()
    {
        $this->merchantKey = config('services.payu.merchant_key');
        $this->merchantSalt = config('services.payu.merchant_salt');
        $this->environment = config('services.payu.env', 'test');
        
        $this->gatewayUrl = $this->environment === 'live' 
            ? config('services.payu.url_live')
            : config('services.payu.url_test');
    }

    /**
     * Generate PayU payment form data
     *
     * @param EventRegistration $registration
     * @return array
     */
    public function generatePaymentData($registration)
    {
        $txnid = $registration->reg_id . '_' . time();

        $paymentData = [
            'key' => $this->merchantKey,
            'txnid' => $txnid,
            'amount' => number_format($registration->amount, 2, '.', ''),
            'productinfo' => 'Event Registration - ' . $registration->event->Name,
            'firstname' => $registration->name,
            'email' => $registration->email,
            'phone' => $registration->phone,
            'surl' => route('payment.success'),
            'furl' => route('payment.failure'),
            'udf1' => $registration->reg_id,
            'udf2' => $registration->eventid,
            'udf3' => '',
            'udf4' => '',
            'udf5' => '',
        ];

        // Generate hash
        $paymentData['hash'] = $this->generateHash($paymentData);

        return $paymentData;
    }

    /**
     * Generate PayU Hash
     *
     * @param array $data
     * @return string
     */
    public function generateHash($data)
    {
        $hashString = $data['key'] . '|' .
                     $data['txnid'] . '|' .
                     $data['amount'] . '|' .
                     $data['productinfo'] . '|' .
                     $data['firstname'] . '|' .
                     $data['email'] . '|' .
                     $data['udf1'] . '|' .
                     $data['udf2'] . '|' .
                     $data['udf3'] . '|' .
                     $data['udf4'] . '|' .
                     $data['udf5'] . '|' .
                     $this->merchantSalt;

        return hash('sha512', $hashString);
    }

    /**
     * Verify PayU response hash
     *
     * @param array $response
     * @return boolean
     */
    public function verifyHash($response)
    {
        // PayU response hash includes additional status field
        $hashString = $response['status'] . '|' .
                     $response['txnid'] . '|' .
                     $response['amount'] . '|' .
                     $response['productinfo'] . '|' .
                     $response['firstname'] . '|' .
                     $response['email'] . '|' .
                     $response['udf1'] . '|' .
                     $response['udf2'] . '|' .
                     $response['udf3'] . '|' .
                     $response['udf4'] . '|' .
                     $response['udf5'] . '|' .
                     $this->merchantSalt;

        $calculatedHash = hash('sha512', $hashString);
        
        return hash_equals($calculatedHash, $response['hash'] ?? '');
    }

    /**
     * Get gateway URL
     *
     * @return string
     */
    public function getGatewayUrl()
    {
        return $this->gatewayUrl;
    }

    /**
     * Check if environment is test
     *
     * @return boolean
     */
    public function isTestMode()
    {
        return $this->environment === 'test';
    }

    /**
     * Process PayU callback response
     *
     * @param array $response
     * @return array
     */
    public function processCallback($response)
    {
        // Verify hash
        if (!$this->verifyHash($response)) {
            return [
                'success' => false,
                'message' => 'Hash verification failed.',
                'status' => 'failed',
            ];
        }

        // Find registration by reg_id (stored in udf1)
        $registration = EventRegistration::where('reg_id', $response['udf1'] ?? '')
                                        ->first();

        if (!$registration) {
            return [
                'success' => false,
                'message' => 'Registration not found.',
                'status' => 'failed',
            ];
        }

        // Check if payment was successful
        if ($response['status'] === 'success' || strtolower($response['status']) === 'captured') {
            $registration->markAsPaid($response['txnid'], 'PAYU');
            
            return [
                'success' => true,
                'message' => 'Payment successful.',
                'registration' => $registration,
                'status' => 'success',
            ];
        } else {
            $registration->markAsFailed($response['txnid']);
            
            return [
                'success' => false,
                'message' => 'Payment failed: ' . ($response['error_Message'] ?? 'Unknown error'),
                'registration' => $registration,
                'status' => 'failed',
            ];
        }
    }

    /**
     * Validate amount
     *
     * @param mixed $amount
     * @return boolean
     */
    public function validateAmount($amount)
    {
        // PayU minimum amount is usually 1
        return $amount >= 0.01;
    }
}
