<?php
/**
 * Stripe Checkout Session Creation
 * Uses tracking_code from submissions table
 */

header('Content-Type: application/json');
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../common/journal_config_new.php';
require_once __DIR__ . '/stripe-php/init.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $tracking_code = $input['tracking_code'] ?? '';
    $amount = $input['amount'] ?? '35.00';
    $currency = $input['currency'] ?? 'USD';
    
    if (!$tracking_code) {
        throw new Exception('Tracking code required');
    }
    
    // Validate and fetch submission details
    $stmt = $pdo->prepare("
        SELECT s.*, a.email, a.name as author_name, j.name as journal_name, j.journal_code
        FROM submissions s
        LEFT JOIN authors a ON s.author_id = a.id
        LEFT JOIN journals j ON s.journal_id = j.id
        WHERE s.tracking_code = ? LIMIT 1
    ");
    $stmt->execute([$tracking_code]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$submission) {
        throw new Exception('Submission not found for tracking code: ' . $tracking_code);
    }
    
    // Check if already paid
    if ($submission['fee_paid'] == 1) {
        throw new Exception('This submission has already been paid');
    }
    
    // Convert amount to cents (Stripe uses smallest currency unit)
    $amount_cents = (int)(floatval($amount) * 100);
    
    // Get customer email
    $customer_email = $submission['email'] ?? '';
    
    // Validate email format
    if (!filter_var($customer_email, FILTER_VALIDATE_EMAIL)) {
        $customer_email = ''; // Don't pass invalid email to Stripe
    }
    
    // Create Checkout Session
    $checkout_session = \Stripe\Checkout\Session::create([
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price_data' => [
                'currency' => strtolower($currency),
                'product_data' => [
                    'name' => 'Article Publication Fee',
                    'description' => 'Paper: ' . substr($submission['title'], 0, 100) . ' | Journal: ' . ($submission['journal_name'] ?? 'RSIS'),
                ],
                'unit_amount' => $amount_cents,
            ],
            'quantity' => 1,
        ]],
        'mode' => 'payment',
        'success_url' => 'https://rsisinternational.org/journals/common/payment/stripe_success.php?session_id={CHECKOUT_SESSION_ID}&tracking_code=' . urlencode($tracking_code) . '&method=stripe',
        'cancel_url' => 'https://rsisinternational.org/journals/common/payment/stripe_cancel.php?tracking_code=' . urlencode($tracking_code),
        'customer_email' => $customer_email,
        'metadata' => [
            'tracking_code' => $tracking_code,
            'invoice_no' => 'RSIS-' . $tracking_code,
            'journal' => $submission['journal_name'] ?? '',
            'author_name' => $submission['author_name'] ?? '',
        ],
    ]);
    
    echo json_encode([
        'success' => true,
        'session_id' => $checkout_session->id
    ]);
    
} catch (Exception $e) {
    error_log("Stripe checkout error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}