<?php
require_once("./config/db_config.php");
class ICICIOrangePaymentGateway{

public $domainURL;
private $createOrderUrl = '/v2/initiateSale';
private $fetchOrderUrl = '/command'; 
function __construct()
{
    $this->domainURL = domainURL;
}

function getCurrencyCode($currency)
{
    $currencyMap = [
        'INR' => '356',
        'USD' => '840',
        'EUR' => '978',
        'GBP' => '826',
        'AED' => '784',
        'SAR' => '682',
        'KWD' => '414',
        'QAR' => '634',
        'OMR' => '512'
    ];

    $currency = strtoupper(trim($currency));

    return $currencyMap[$currency] ?? '356'; // default INR
}

public function createOrder($data)
    {
        $gatewayJson = json_decode($data['gatewayConfig'], true);

        // Gateway Config
        $merchantId      = $gatewayJson['merchantId'];
        $secretKey       = $gatewayJson['secretKey'];
        $apiUrl          = $gatewayJson['apiUrl'].$this->createOrderUrl;
        $currencyCode    = $this->getCurrencyCode($data['currency'] ?? 'INR');
        $payType         = $gatewayJson['payType'] ?? '0';
        $transactionType = $gatewayJson['transactionType'] ?? 'SALE';

        // Transaction Data
        $merchantTxnNo = $data['txnId']; // unique txn id
        $amount        = number_format((float)$data['amount'], 2, '.', '');
        $email         = $data['email'];
        $mobile        = $data['phoneNo'];
        $returnURL     = $this->domainURL . '/paymentResponse.php';

        $addlParam1 = $data['code'] ?? '';
        $addlParam2 = $data['name'] ?? '';

        $txnDate = date("YmdHis");
        if ($currencyCode !== '356') {
            return [
                'status'  => 'failed',
                'message' => 'Selected currency not supported by payment gateway'
            ];
        }

        // Payload
        $payload = [
            "merchantId"        => $merchantId,
            "merchantTxnNo"     => $merchantTxnNo,
            "amount"            => $amount,
            "currencyCode"      => $currencyCode,
            "payType"           => $payType,
            "transactionType"   => $transactionType,
            "customerEmailID"   => $email,
            "customerMobileNo"  => $mobile,
            "txnDate"           => $txnDate,
            "returnURL"         => $returnURL,
            "addlParam1"        => $addlParam1,
            "addlParam2"        => $addlParam2
        ];

        /**
         * Secure Hash Calculation
         */
        $hashString =
            $payload["addlParam1"] .
            $payload["addlParam2"] .
            $payload["amount"] .
            $payload["currencyCode"] .
            $payload["customerEmailID"] .
            $payload["customerMobileNo"] .
            $payload["merchantId"] .
            $payload["merchantTxnNo"] .
            $payload["payType"] .
            $payload["returnURL"] .
            $payload["transactionType"] .
            $payload["txnDate"];

        $payload["secureHash"] = hash_hmac("sha256", $hashString , $secretKey);

        /**
         * CURL Request
         */
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL            => $apiUrl,
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS     => json_encode($payload)
        ]);

        $response = curl_exec($curl);

        if ($response === false) {
            return [
                'status'  => 'error',
                'message' => curl_error($curl)
            ];
        }

        curl_close($curl);

        $responseObj = json_decode($response, true);

        /**
         * Successful Response → Redirect URL
         */
        if (
            isset($responseObj['responseCode']) &&
            $responseObj['responseCode'] === 'R1000' &&
            !empty($responseObj['redirectURI']) &&
            !empty($responseObj['tranCtx'])
        ) {
            return [
                'status'        => 'success',
                'merchantTxnNo' => $merchantTxnNo,
                'redirectUrl'   => $responseObj['redirectURI'] . '?tranCtx=' . $responseObj['tranCtx'],
                'rawResponse'   => $responseObj
            ];
        }
//         file_put_contents(
//     __DIR__ . '/payphi_debug.log',
//     "---- REQUEST ----\n" .
//     json_encode($payload, JSON_PRETTY_PRINT) .
//     "\n---- RESPONSE ----\n" .
//     $response .
//     "\n\n",
//     FILE_APPEND
// );


        /**
         * Failure Case
         */
        return [
            'status'        => 'failed',
            'message'       => $responseObj['responseDescription']?? $responseObj['respDescription']?? 'Payment initiation failed',
            'responseCode'  => $responseObj['responseCode'] ?? null,
            'rawResponse'   => $responseObj,
            'requestPayload'=> $payload
            ];

    }


public function fetchOrder($data)
{
    $gatewayJson = json_decode($data['gatewayConfig'], true);

    $merchantId  = $gatewayJson['merchantId'];
    $secretKey   = $gatewayJson['secretKey'];
    $apiUrl      = $gatewayJson['apiUrl'].$this->fetchOrderUrl; // should be https://qa.phicommerce.com/pg/api/command

    $merchantTxnNo = $data['txnId'];
    $amount        = number_format((float)$data['amount'], 2, '.', '');

    /**
     * STATUS API payload
     */
    $payload = [
        "merchantId"      => $merchantId,
        "merchantTxnNo"   => $merchantTxnNo,
        "originalTxnNo"   => $merchantTxnNo,
        "amount"          => $amount,
        "transactionType" => "STATUS"
    ];

    /**
     * Secure Hash (PayPhi spec)
     * amount + merchantId + merchantTxnNo + originalTxnNo + transactionType
     */
    $hashString =
        $payload["amount"] .
        $payload["merchantId"] .
        $payload["merchantTxnNo"] .
        $payload["originalTxnNo"] .
        $payload["transactionType"];

    $payload["secureHash"] = hash_hmac("sha256", $hashString, $secretKey);

    /**
     * CURL call
     */
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL            => $apiUrl,
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_TIMEOUT        => 30
    ]);

    $response = curl_exec($curl);

    if ($response === false) {
        return [
            'status'  => 'ERROR',
            'message' => curl_error($curl)
        ];
    }

    curl_close($curl);

    $responseObj = json_decode($response, true);

    /**
     * Normalize response (important for existing receipt logic)
     */
    if (!is_array($responseObj)) {
        return [
            'status'  => 'ERROR',
            'message' => 'Invalid response from gateway'
        ];
    }

    // Success
    if (
        isset($responseObj['txnStatus']) &&
        $responseObj['txnStatus'] === 'SUC'
    ) {
        return [
            'status'           => 'Success',
            'merchantTxnNo'    => $responseObj['merchantTxnNo'],
            'txnStatus'        => $responseObj['txnStatus'],
            'txnAuthID'        => $responseObj['txnAuthID'] ?? '',
            'txnID'            => $responseObj['txnID'] ?? '',
            'paymentMode'      => $responseObj['paymentMode'] ?? '',
            'paymentDateTime'  => $responseObj['paymentDateTime'] ?? '',
            'rawResponse'      => $responseObj
        ];
    }

    // Failed / Not found / Pending
    return [
        'status'        => 'FAILED',
        'txnStatus'     => $responseObj['txnStatus'] ?? '',
        'responseCode'  => $responseObj['responseCode'] ?? '',
        'message'       => $responseObj['respDescription'] ?? 'Transaction not successful',
        'rawResponse'   => $responseObj
    ];
}



}

/*


=====================================================
========================================================================================================
ICICI ORange Fetch Order

$apiUrl = "https://qa.phicommerce.com/pg/api/command";

$merchantId  = "T_03342";
$secretKey   = "abc";

// Replace with original MerchantTxnNo of sale
$merchantTxnNo = "TXN1764751246"; 

$payload = [
    "merchantId"      => $merchantId,
    "merchantTxnNo"   => $merchantTxnNo,
    "originalTxnNo"   => $merchantTxnNo,
    "amount"          => "1.00",
    "transactionType" => "STATUS"
];

// Generate secureHash
$hashString = $payload["amount"] .
              $payload["merchantId"] .
              $payload["merchantTxnNo"] .
              $payload["originalTxnNo"] .
              $payload["transactionType"];

$payload["secureHash"] = hash_hmac("sha256", $hashString , $secretKey);

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $apiUrl,
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($payload)
]);

$response = curl_exec($curl);
curl_close($curl);

echo "<pre>";
echo "Status Response:\n";
print_r(json_decode($response, true));
echo "</pre>";

*/