<?php
/**
 * inc/payment_helpers.php
 * Shared utilities for the payment system:
 *   - normalizeCountry()
 *   - resolvePricing()
 *   - getCurrencySymbol()
 *   - logPaymentError()
 *   - renderError()
 *
 * No DB access here — pure helpers.
 */

// ── Currency symbol map ───────────────────────────────────────────────────────
function getCurrencySymbol(string $currency): string {
    return [
        'INR' => '₹',  'BDT' => '৳',  'TRY' => '₺',  'PKR' => 'Rs ',
        'NGN' => '₦',  'KES' => 'KSh ','PHP' => '₱',  'MYR' => 'RM ',
        'IDR' => 'Rp ', 'LKR' => 'රු ','USD' => '$',   'ETB' => 'Br ',
        'TZS' => 'TSh ','ZMW' => 'ZK ', 'ZAR' => 'R ',  'VND' => '₫ ',
        'CNY' => '¥ ', 'GHS' => '₵ ', 'NPR' => 'Rs ', 'AFN' => 'Af ',
        'SSP' => '£',  'HUF' => 'Ft ', 'ARS' => 'AR$ ','CHF' => 'CHF ',
        'EUR' => '€',  'GBP' => '£',
    ][$currency] ?? '$';
}

// ── Normalize country string ──────────────────────────────────────────────────
function normalizeCountry(string $raw): string {
    return strtolower(trim(preg_replace('/\s+/', ' ', $raw)));
}

/**
 * resolvePricing()
 * Returns array:
 *   amount, currency, symbol, paypal_amount,
 *   show_paypal, show_razorpay, show_stripe
 *
 * Base fee: $35 USD  (IJLTEMAS / CGBL-discounted journals → $30 USD)
 * India: ₹1500 INR  (Razorpay only)
 */
function resolvePricing(string $country, string $journal_name): array {
    // Journals with reduced base fee
    $reduced_journals = ['IJLTEMAS', 'CGBL-LITE'];
    $is_reduced = false;
    foreach ($reduced_journals as $j) {
        if (stripos($journal_name, $j) !== false) { $is_reduced = true; break; }
    }

    $base_usd = $is_reduced ? 30.00 : 35.00;

    // Countries that get $30 regardless of journal
    $discount_countries = ['nigeria', 'uganda', 'ethiopia'];
    if (in_array($country, $discount_countries)) {
        $base_usd = 30.00;
    }

    // Default result (USD)
    $result = [
        'amount'        => number_format($base_usd, 2, '.', ''),
        'currency'      => 'USD',
        'symbol'        => '$',
        'paypal_amount' => number_format($base_usd, 2, '.', ''),
        'show_paypal'   => true,
        'show_razorpay' => true,
        'show_stripe'   => true,
    ];

    // India — INR only via Razorpay
    if ($country === 'india') {
        $result['amount']        = '1500.00';
        $result['currency']      = 'INR';
        $result['symbol']        = '₹';
        $result['paypal_amount'] = number_format($base_usd, 2, '.', '');
        $result['show_paypal']   = false;
        $result['show_stripe']   = false;
        return $result;
    }

    // Per-country local currency amounts
    // Keys = normalized country name, Values = [currency, amount_35, amount_30]
    $local = [
        'bangladesh'   => ['BDT', 4240.00,  3640.00],
        'turkey'       => ['TRY', 1460.00,  1250.00],
        'pakistan'     => ['PKR', 9870.00,  8460.00],
        'nigeria'      => ['NGN', 41495.00, 41495.00],
        'kenya'        => ['KES', 4520.00,  3880.00],
        'philippines'  => ['PHP', 2048.00,  1756.00],
        'malaysia'     => ['MYR', 144.00,   123.00],
        'indonesia'    => ['IDR', 582749.00,499680.00],
        'sri lanka'    => ['LKR', 10749.00, 9271.00],
        'ethiopia'     => ['ETB', 4637.00,  4637.00],
        'tanzania'     => ['TZS', 86127.00, 73935.00],
        'zambia'       => ['ZMW', 799.00,   689.00],
        'south africa' => ['ZAR', 597.00,   512.00],
        'vietnam'      => ['VND', 922810.00,791310.00],
        'china'        => ['CNY', 247.00,   212.00],
        'ghana'        => ['GHS', 397.00,   340.00],
        'nepal'        => ['NPR', 2404.00,  2404.00],
        'afghanistan'  => ['AFN', 2323.00,  1991.00],
        'south sudan'  => ['SSP', 4559.00,  3907.00],
        'hungary'      => ['HUF', 11472.00, 9833.00],
        'argentina'    => ['ARS', 50794.00, 43538.00],
        'uganda'       => ['USD', 30.00,    30.00],
        'tunisia'      => ['USD', 35.00,    30.00],
    ];

    if (isset($local[$country])) {
        [$curr, $amt_35, $amt_30] = $local[$country];
        $amt = $is_reduced ? $amt_30 : $amt_35;
        $result['amount']   = number_format($amt, 2, '.', '');
        $result['currency'] = $curr;
        $result['symbol']   = getCurrencySymbol($curr);
        // PayPal always USD
        $result['paypal_amount'] = number_format($base_usd, 2, '.', '');
    }

    return $result;
}

// ── Logging ───────────────────────────────────────────────────────────────────
function logPaymentError(string $msg, string $tc = '', string $level = 'error'): void {
    // Works from any depth: author/, author/ajax/, etc.
    $log = dirname(__DIR__) . '/logs/payment.log';
    // Fallback: same dir as helpers file
    if (!is_dir(dirname($log))) {
        $log = __DIR__ . '/../../logs/payment.log';
    }
    $line = '[' . date('Y-m-d H:i:s') . '] [' . strtoupper($level) . '] '
          . ($tc ? "[$tc] " : '') . $msg . PHP_EOL;
    @file_put_contents($log, $line, FILE_APPEND | LOCK_EX);
}

// ── Render a standalone error page ────────────────────────────────────────────
function renderError(string $msg): void {
    http_response_code(400);
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8">'
       . '<title>Payment Error</title>'
       . '<style>body{font-family:sans-serif;max-width:500px;margin:80px auto;padding:20px}'
       . '.box{background:#fee2e2;border:1px solid #fca5a5;border-radius:8px;padding:20px;color:#991b1b}'
       . '</style></head><body>'
       . '<div class="box"><strong>⚠ Error</strong><p>' . htmlspecialchars($msg) . '</p>'
       . '<a href="javascript:history.back()">← Go back</a></div>'
       . '</body></html>';
}