<?php

$PLANS = [
    'trial_1m' => ['name'=>'Trial — 1 Month',  'price'=>0.99,  'durationDays'=>30,  'isTrial'=>true,  'displayPrice'=>'$0.99'],
    '1m'       => ['name'=>'1 Month',           'price'=>1.49,  'durationDays'=>30,  'isTrial'=>false, 'displayPrice'=>'$1.49'],
    '3m'       => ['name'=>'3 Months',          'price'=>2.60,  'durationDays'=>90,  'isTrial'=>false, 'displayPrice'=>'$2.60'],
    '6m'       => ['name'=>'6 Months',          'price'=>3.90,  'durationDays'=>180, 'isTrial'=>false, 'displayPrice'=>'$3.90'],
    '1y'       => ['name'=>'1 Year',            'price'=>4.90,  'durationDays'=>365, 'isTrial'=>false, 'displayPrice'=>'$4.90'],
];

function getPlan($id) {
    global $PLANS;
    return $PLANS[$id] ?? null;
}

function subPlans($p = null) {
    global $PLANS;
    $list = [];
    foreach ($PLANS as $id => $plan) {
        $list[] = array_merge(['id' => $id], $plan);
    }
    respond($list);
}

function subStatus($p = null) {
    $user = requireAuth();
    $u    = queryOne('SELECT * FROM users WHERE id=?', [$user['id']]);
    $days = $u['sub_end'] ? max(0, ceil((strtotime($u['sub_end']) - time()) / 86400)) : 0;
    respond([
        'status'      => $u['sub_status'],
        'plan'        => $u['sub_plan'],
        'startDate'   => $u['sub_start'],
        'endDate'     => $u['sub_end'],
        'isActive'    => isSubActive($u),
        'trialUsed'   => (bool)$u['trial_used'],
        'daysRemaining' => $days,
    ]);
}

function subCheckout($p = null) {
    $user   = requireAuth();
    requireSubscription($user); // must be verified
    $planId = get('planId');
    $plan   = getPlan($planId);
    if (!$plan) error('Invalid plan');

    $u = queryOne('SELECT * FROM users WHERE id=?', [$user['id']]);
    if ($plan['isTrial'] && $u['trial_used']) error('Trial already used. Please choose a paid plan.');

    // If Stripe is configured use it, otherwise manual payment
    if (getenv('STRIPE_SECRET_KEY') && str_starts_with(getenv('STRIPE_SECRET_KEY'), 'sk_')) {
        stripeCheckout($u, $planId, $plan);
    } else {
        // No Stripe — return payment pending info
        respond([
            'message'    => 'Manual payment required',
            'plan'       => $plan['name'],
            'price'      => $plan['displayPrice'],
            'contact'    => 'Please contact admin to activate your subscription.',
        ]);
    }
}

function stripeCheckout($user, $planId, $plan) {
    // Simple Stripe integration using cURL
    $secretKey = getenv('STRIPE_SECRET_KEY');
    $frontendUrl = getenv('FRONTEND_URL');

    // Get or create Stripe customer
    $customerId = $user['stripe_customer_id'];
    if (!$customerId) {
        $ch = curl_init('https://api.stripe.com/v1/customers');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_USERPWD        => $secretKey . ':',
            CURLOPT_POSTFIELDS     => http_build_query([
                'email'          => $user['email'],
                'name'           => $user['name'],
                'metadata[userId]' => $user['id'],
            ]),
        ]);
        $res = json_decode(curl_exec($ch), true);
        curl_close($ch);
        $customerId = $res['id'];
        execute('UPDATE users SET stripe_customer_id=? WHERE id=?', [$customerId, $user['id']]);
    }

    // Create checkout session
    $ch = curl_init('https://api.stripe.com/v1/checkout/sessions');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_USERPWD        => $secretKey . ':',
        CURLOPT_POSTFIELDS     => http_build_query([
            'customer'                                => $customerId,
            'payment_method_types[]'                  => 'card',
            'mode'                                    => 'payment',
            'line_items[0][price_data][currency]'     => 'usd',
            'line_items[0][price_data][product_data][name]' => 'Numerology — ' . $plan['name'],
            'line_items[0][price_data][unit_amount]'  => (int)($plan['price'] * 100),
            'line_items[0][quantity]'                 => 1,
            'metadata[userId]'                        => $user['id'],
            'metadata[planId]'                        => $planId,
            'metadata[isTrial]'                       => $plan['isTrial'] ? 'true' : 'false',
            'success_url'                             => $frontendUrl . '/payment-success?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url'                              => $frontendUrl . '/pricing',
        ]),
    ]);
    $session = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (!isset($session['url'])) error('Payment session creation failed');
    respond(['sessionId' => $session['id'], 'url' => $session['url']]);
}

function subVerify($p = null) {
    subVerifySession($p);
}

function subVerifySession($sessionId = null) {
    $user = requireAuth();
    if (!$sessionId) $sessionId = $_GET['session_id'] ?? null;
    if (!$sessionId) error('Session ID required');

    $secretKey = getenv('STRIPE_SECRET_KEY');
    $ch = curl_init('https://api.stripe.com/v1/checkout/sessions/' . urlencode($sessionId));
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_USERPWD => $secretKey . ':']);
    $session = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (!$session || $session['payment_status'] !== 'paid') error('Payment not completed');

    $u = queryOne('SELECT * FROM users WHERE id=?', [$user['id']]);
    respond(['status' => 'paid', 'subscription' => ['status' => $u['sub_status'], 'endDate' => $u['sub_end']]]);
}

// Stripe webhook — called by Stripe server
function stripeWebhook() {
    $payload   = file_get_contents('php://input');
    $sig       = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
    $secret    = getenv('STRIPE_WEBHOOK_SECRET');

    // Verify signature
    $parts     = explode(',', $sig);
    $ts = $v1 = '';
    foreach ($parts as $part) {
        if (str_starts_with($part, 't=')) $ts = substr($part, 2);
        if (str_starts_with($part, 'v1=')) $v1 = substr($part, 3);
    }
    $expected = hash_hmac('sha256', $ts . '.' . $payload, $secret);
    if (!hash_equals($expected, $v1)) { http_response_code(400); exit; }

    $event = json_decode($payload, true);
    if ($event['type'] === 'checkout.session.completed') {
        $session = $event['data']['object'];
        if ($session['payment_status'] !== 'paid') { respond(['received' => true]); }

        $userId = $session['metadata']['userId'] ?? null;
        $planId = $session['metadata']['planId'] ?? null;
        $isTrial = ($session['metadata']['isTrial'] ?? 'false') === 'true';
        $plan   = getPlan($planId);
        if (!$plan || !$userId) { respond(['received' => true]); }

        $start  = date('Y-m-d H:i:s');
        $end    = date('Y-m-d H:i:s', time() + $plan['durationDays'] * 86400);
        $status = $isTrial ? 'trial' : 'active';

        execute(
            'UPDATE users SET sub_status=?,sub_plan=?,sub_start=?,sub_end=?,trial_used=IF(?,1,trial_used) WHERE id=?',
            [$status, $planId, $start, $end, $isTrial, $userId]
        );
        execute(
            'INSERT INTO payments (user_id,stripe_session_id,stripe_payment_id,amount,currency,plan,status) VALUES (?,?,?,?,?,?,?)',
            [$userId, $session['id'], $session['payment_intent'], $session['amount_total'], $session['currency'], $planId, 'succeeded']
        );
    }
    respond(['received' => true]);
}
