<?php
/**
 * GET /api/campaign/checkout-summary?cid=X
 *
 * Returns the campaign + plan + computed price breakdown for the
 * checkout page. Verifies the campaign belongs to the publisher and
 * is still in draft state (status_admin = 0).
 */

declare(strict_types=1);
require_once dirname(__DIR__, 2) . '/config/bootstrap.php';

$user = Auth::apiRequireLogin();
$pid  = (int)$user['publisher_id'];

$cid = (int)($_GET['cid'] ?? 0);
if ($cid <= 0) jsonError('Invalid campaign id.');

$pdo = db();
$stmt = $pdo->prepare("
    SELECT id, app_logo, app_icon_path, app_title, app_developername, app_pkg, app_des,
           plan_name, plan_testing_days, per_user_coins, total_users,
           status_admin, created_at
    FROM pub_purchase_history
    WHERE id = ? AND publisher_id = ?
    LIMIT 1
");
$stmt->execute([$cid, $pid]);
$c = $stmt->fetch();
if (!$c) jsonError('Campaign not found.', 404);

if ((int)$c['status_admin'] !== 0) {
    jsonError('This campaign has already been submitted.', 409, [
        'redirect' => '/dashboard/campaigns/' . $cid,
    ]);
}

// Plan lookup
$planStmt = $pdo->prepare("
    SELECT plan_name,
           COALESCE(price_inr, 0) AS price_inr,
           COALESCE(price_usd, 0) AS price_usd
    FROM tester_pkg_plans
    WHERE LOWER(plan_name) = LOWER(?)
    LIMIT 1
");
$planStmt->execute([$c['plan_name']]);
$plan = $planStmt->fetch();
if (!$plan) jsonError('Plan not found.', 404);

// Currency selection — based on publisher country
$currency  = strtoupper((string)($_GET['currency'] ?? ((string)($user['country'] ?? 'India') === 'India' ? 'INR' : env('DEFAULT_CURRENCY', 'INR'))));
$subtotal  = $currency === 'INR' ? (float)$plan['price_inr'] : (float)$plan['price_usd'];
$gstRate   = (float)env('GST_RATE', 0.18);
$gst       = ($currency === 'INR' && (string)($user['country'] ?? '') === 'India')
                ? round($subtotal * $gstRate, 2)
                : 0;
$platform  = $currency === 'INR'
                ? (float)env('PLATFORM_FEE_INR', 2)
                : (float)env('PLATFORM_FEE_USD', 0.5);
$total     = round($subtotal + $gst + $platform, 2);

// Available gateways for this currency
$gateways = [];
$gatewayMeta = [
    'cashfree' => ['label' => 'Cashfree',  'icon' => '💳', 'desc' => 'UPI / Card / Netbanking', 'currencies' => ['INR', 'USD']],
    'razorpay' => ['label' => 'Razorpay',  'icon' => '🏦', 'desc' => 'UPI / Card / Netbanking', 'currencies' => ['INR', 'USD']],
    'phonepe'  => ['label' => 'PhonePe',   'icon' => '📱', 'desc' => 'UPI Payments',            'currencies' => ['INR']],
    'stripe'   => ['label' => 'Stripe',    'icon' => '💳', 'desc' => 'International Card',       'currencies' => ['USD', 'EUR', 'GBP']],
    'paypal'   => ['label' => 'PayPal',    'icon' => '🅿️', 'desc' => 'PayPal balance / Card',   'currencies' => ['USD', 'EUR', 'GBP']],
];
foreach ($gatewayMeta as $key => $meta) {
    $envKey = 'PAYMENT_' . strtoupper($key) . '_ENABLED';
    if ((int)env($envKey, 0) === 1 && in_array($currency, $meta['currencies'], true)) {
        $gateways[] = [
            'key'    => $key,
            'label'  => $meta['label'],
            'icon'   => $meta['icon'],
            'desc'   => $meta['desc'],
        ];
    }
}

jsonSuccess('OK', [
    'campaign' => [
        'id'                => (int)$c['id'],
        'app_title'         => $c['app_title'],
        'app_developer'     => $c['app_developername'],
        'app_pkg'           => $c['app_pkg'],
        'app_des'           => $c['app_des'],
        'app_logo'          => $c['app_icon_path'] ? '/uploads/app-icons/' . $c['app_icon_path'] : null,
        'plan_name'         => $c['plan_name'],
        'plan_testing_days' => (int)$c['plan_testing_days'],
        'per_user_coins'    => (int)$c['per_user_coins'],
        'total_users'       => (int)$c['total_users'],
    ],
    'pricing' => [
        'currency'        => $currency,
        'currency_symbol' => $currency === 'INR' ? '₹' : '$',
        'subtotal'        => (float)$subtotal,
        'gst_amount'      => (float)$gst,
        'platform_fee'    => (float)$platform,
        'total'           => (float)$total,
        'gst_label'       => 'GST (' . (int)($gstRate * 100) . '%)',
    ],
    'publisher' => [
        'name'         => $user['name'],
        'email'        => $user['email'],
        'phone'        => $user['phone'] ?? '',
        'country'      => $user['country'],
    ],
    'gateways' => $gateways,
]);
