<?php
//exit;
/**
 * DirectPay Card Onboard - PHP script / CodeIgniter-friendly controller
 *
 * Simplified: no HTML form, customer details are set programmatically.
 *
 * Notes:
 *  - Replace MERCHANT_ID and SECRET with values from DirectPay.
 *  - Call this script programmatically (via include or HTTP) to trigger onboarding.
 */

// Configuration
define('DIRECTPAY_ENV', 'test'); // 'test' or 'prod'
define('DIRECTPAY_MERCHANT_ID', 'LH16047');
define('DIRECTPAY_SECRET', 'aee0c8db6ab7b09e9b10c7b21fedd61bd4b0307dd79f0e766626de9483271083');

// Hardcoded / programmatic customer details (replace dynamically as needed)
$customer = [
    'first_name' => '',
    'last_name' => '',
    'email' => '',
    'phone' => '',
    'do_initial_payment' => 0,
];

// Endpoints
$DIRECTPAY_ENDPOINTS = [
    'test' => 'https://test-gateway.directpay.lk/api/v3/create-session',
    'prod' => 'https://gateway.directpay.lk/api/v3/create-session',
];

// Generate order id
$order_id = $_GET['jobid'];

// Payload
$payload = [
    'merchant_id' => DIRECTPAY_MERCHANT_ID,
    'amount' => '10.00', // required; use small dummy if do_initial_payment=0
    'type' => 'CARD_ADD',
    'order_id' => $order_id,
    'currency' => 'LKR',
    'response_url' => url_origin() . '/response.php?jobid='.$order_id,
    'return_url' => url_origin() . '/card-return.php?jobid='.$order_id,
    'first_name' => $customer['first_name'],
    'last_name' => $customer['last_name'],
    'email' => $customer['email'],
    'phone' => $customer['phone'],
    'description' => 'Card onboarding',
    'logo' => '',
    'do_initial_payment' => (string)$customer['do_initial_payment'],
];

$endpoint = $DIRECTPAY_ENDPOINTS[DIRECTPAY_ENV];
$response = send_create_session($endpoint, $payload);

header('Content-Type: application/json');
echo json_encode($response);

/**
 * Sends create-session to DirectPay
 */
function send_create_session(string $url, array $payload): array
{
    $json = json_encode($payload);
    $base64 = base64_encode($json);
    $signature_hash = hash_hmac('sha256', $base64, DIRECTPAY_SECRET);
    $signature = 'hmac ' . $signature_hash;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $base64);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: text/plain',
        'Authorization: ' . $signature,
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $curl_err = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    
    
    $logFile = __DIR__ . '/xresponse_log.txt';
    $logEntry  = "===== " . date('Y-m-d H:i:s') . " =====\n";
    $logEntry .= print_r($response, true) . "\n";
    $logEntry .= str_repeat("-", 50) . "\n\n"; // full flat line break
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        


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

    $decoded = json_decode($response, true);

    return [
        'ok' => true,
        'http_code' => $http_code,
        'raw' => $response,
        'json' => $decoded,
    ];
}

/**
 * Verify incoming DirectPay request (server -> your response_url)
 */
function verify_directpay_request(): array
{
    $body = file_get_contents('php://input');
    $auth = $_SERVER['HTTP_AUTHORIZATION'] ?? null;
    if (!$auth && function_exists('getallheaders')) {
        $headers = getallheaders();
        $auth = $headers['Authorization'] ?? $headers['authorization'] ?? null;
    }
    if (!$auth) return ['ok' => false, 'message' => 'No Authorization header'];

    $parts = explode(' ', $auth);
    if (count($parts) !== 2) return ['ok' => false, 'message' => 'Malformed Authorization header'];
    $received_hash = $parts[1];

    $generated = hash_hmac('sha256', $body, DIRECTPAY_SECRET);
    if (!hash_equals($generated, $received_hash)) return ['ok' => false, 'message' => 'Signature mismatch'];

    $decoded_base = base64_decode($body, true);
    if ($decoded_base === false) return ['ok' => false, 'message' => 'Base64 decode failed'];
    $payload = json_decode($decoded_base, true);
    if ($payload === null) return ['ok' => false, 'message' => 'JSON decode failed'];

    return ['ok' => true, 'message' => 'verified', 'payload' => $payload];
}

/**
 * Helper: current origin
 */
function url_origin()
{
    $s = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? 'localhost');
    return $s . '://' . $host;
}
?>
