<?php
namespace App\Controllers;

use CodeIgniter\Controller;

class Payment extends BaseController
{
    public function initiate()
{
    $post = $this->request->getPost();

    $order_id = $post['order_id'];
    $amount   = $post['amount'];
    $name     = $post['name'];
    $email    = $post['email'];
    $phone    = $post['phone'];

    $requestData = [
        "merchantId"        => "100000000007164",
        "aggregatorID"      => "A100000000007164",
        "merchantTxnNo"     => "ORD".$order_id.time(),
        "amount"            => number_format($amount, 2, '.', ''),
        "currencyCode"      => "356",
        "payType"           => "0",
        "customerEmailID"   => $email,
        "transactionType"   => "SALE",
        "returnURL"         => base_url('payment/response'),
        "txnDate"           => date('YmdHis'),
        "customerMobileNo"  => $phone,
        "customerName"      => $name,
        "addlParam1"        => "000",
        "addlParam2"        => "111"
    ];

    // 🔐 Secure Hash (ORDER MATTERS)
    $plainText =
        $requestData['addlParam1'] .
        $requestData['addlParam2'] .
        $requestData['aggregatorID'] .
        $requestData['amount'] .
        $requestData['currencyCode'] .
        $requestData['customerEmailID'] .
        $requestData['customerMobileNo'] .
        $requestData['customerName'] .
        $requestData['merchantId'] .
        $requestData['merchantTxnNo'] .
        $requestData['payType'] .
        $requestData['returnURL'] .
        $requestData['transactionType'] .
        $requestData['txnDate'];

    $secretKey = 'ae85111d-7cc7-4f75-b0dd-6ebd33f8a86f';
    $requestData['secureHash'] = hash_hmac('sha256', $plainText, $secretKey);

    // 🔁 CURL call to ICICI
    $ch = curl_init("https://pgpayuat.icicibank.com/tsp/pg/api/v2/initiateSale");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => json_encode($requestData),
    ]);

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

    $res = json_decode($response, true);

    if (!isset($res['redirectURI'], $res['tranCtx'])) {
        echo "ICICI Error:<pre>".$response."</pre>";
        exit;
    }

    // ✅ Redirect customer
    return redirect()->to(
        $res['redirectURI'] . '?tranCtx=' . $res['tranCtx']
    );
}


    public function response()
    {
        $post = $this->request->getPost();
        // Handle ICICI response here and update payment status
    }
}
