<?php
/**
 * ajax/payment_stripe_create.php
 * POST JSON { tracking_code, amount, currency }
 * Returns  { session_id }  or  { error }
 */
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../inc/payment_helpers.php';
require_once __DIR__ . '/../lib/stripe-php/init.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

$input         = json_decode(file_get_contents('php://input'), true) ?? [];
$tracking_code = trim($input['tracking_code'] ?? '');
$amount        = $input['amount']   ?? '';
$currency      = strtolower($input['currency'] ?? 'usd');

if (!$tracking_code || !$amount) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing parameters']);
    exit;
}

try {
    // Fetch submission details
    $stmt = db()->prepare("
        SELECT s.submission_id, s.user_id, mi.article_title
        FROM submissions s
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        WHERE s.tracking_code = ? LIMIT 1
    ");
    $stmt->execute([$tracking_code]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$sub) { throw new RuntimeException('Submission not found'); }

    // Zero-decimal currencies — no *100 conversion
    $zero_decimal = ['bif','clp','djf','gnf','jpy','kmf','krw','mga','pyg','rwf','ugx','vnd','vuv','xaf','xof','xpf'];
    $unit_amount  = in_array($currency, $zero_decimal)
        ? (int)$amount
        : (int)(round((float)$amount, 2) * 100);

    $title = $sub['article_title'] ?? 'Publication Fee';

    $session = \Stripe\Checkout\Session::create([
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price_data' => [
                'currency'     => $currency,
                'product_data' => [
                    'name'        => 'Article Processing Charge',
                    'description' => 'CGBL-' . $tracking_code . ' — ' . mb_substr($title, 0, 120),
                ],
                'unit_amount' => $unit_amount,
            ],
            'quantity' => 1,
        ]],
        'mode'        => 'payment',
        'success_url' => SITE_URL . '/author/payment_success.php?session_id={CHECKOUT_SESSION_ID}&tracking_code=' . urlencode($tracking_code) . '&method=stripe',
        'cancel_url'  => SITE_URL . '/author/pay.php?tracking_code=' . urlencode($tracking_code),
        'metadata'    => [
            'tracking_code' => $tracking_code,
            'invoice_no'    => 'CGBL-' . $tracking_code,
            'submission_id' => $sub['submission_id'],
        ],
        'customer_email' => null, // will be collected by Stripe if needed
    ]);

    // Save pending record
    db()->prepare("
        INSERT INTO payments
            (submission_id, tracking_code, invoice_no, gateway, gateway_session_id, status, amount, currency, raw_response)
        VALUES (?, ?, ?, 'stripe', ?, 'CREATED', ?, ?, ?)
    ")->execute([
        $sub['submission_id'],
        $tracking_code,
        'CGBL-' . $tracking_code,
        $session->id,
        $amount,
        strtoupper($currency),
        json_encode($session->toArray()),
    ]);

    echo json_encode(['session_id' => $session->id]);

} catch (Throwable $e) {
    logPaymentError('Stripe create: ' . $e->getMessage(), $tracking_code);
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}