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

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

$session_id = $_GET['session_id'] ?? '';
$tracking_code = $_GET['tracking_code'] ?? '';
$method = $_GET['method'] ?? 'stripe'; // Default to stripe

if (!$session_id || !$tracking_code) {
    die("Invalid request - Missing session ID or Tracking Code");
}

$payment_saved = false;
$error_message = '';
$payment_details = [];
$journal_info = null;

// Journal configuration
$journals = [
    'IJRISS' => [
        'name' => 'International Journal of Research and Innovation in Social Science (IJRISS)',
        'issn' => '2454-6186',
        'doi' => '10.47772/IJRISS',
        'final_link' => 'https://rsisinternational.org/journals/ijriss/final-manuscript-submission/',
        'declaration_link' => 'https://rsisinternational.org/journals/ijriss/wp-content/uploads/2018/08/Author-s-Declaration.pdf'
    ],
    'IJRIAS' => [
        'name' => 'International Journal of Research and Innovation in Applied Science (IJRIAS)',
        'issn' => '2454-6194',
        'doi' => '10.51584/IJRIAS',
        'final_link' => 'https://rsisinternational.org/journals/ijrias/final-manuscript-submission/',
        'declaration_link' => 'https://rsisinternational.org/journals/ijrias/images/Author%20(s)%20Declaration.pdf'
    ],
    'IJRSI' => [
        'name' => 'International Journal of Research and Scientific Innovation (IJRSI)',
        'issn' => '2321-2705',
        'doi' => '10.51244/IJRSI',
        'final_link' => 'https://rsisinternational.org/journals/ijrsi/final-manuscript-submission/',
        'declaration_link' => 'https://rsisinternational.org/journals/ijrsi/wp-content/uploads/2018/01/Author-s-Declaration.pdf'
    ],
    'IJLTEMAS' => [
        'name' => 'International Journal of Latest Technology in Engineering, Management & Applied Science (IJLTEMAS)',
        'issn' => '2278-2540',
        'doi' => '10.51583/IJLTEMAS',
        'final_link' => 'https://www.ijltemas.in/final-manuscript-submission/',
        'declaration_link' => 'https://www.ijltemas.in/images/Author(s)Declaration.pdf'
    ]
];

try {
    // Verify submission exists
    $check_submission = $pdo->prepare("
        SELECT s.*, j.name as journal_name, j.journal_code as journal_code
        FROM submissions s
        LEFT JOIN journals j ON s.journal_id = j.id
        WHERE s.tracking_code = ? LIMIT 1
    ");
    $check_submission->execute([$tracking_code]);
    $submission = $check_submission->fetch(PDO::FETCH_ASSOC);
    
    if (!$submission) {
        throw new Exception("Submission not found for tracking code: " . $tracking_code);
    }
    
    $journal_code = $submission['journal_code'] ?? '';
    if (isset($journals[$journal_code])) {
        $journal_info = $journals[$journal_code];
    }
    
    if ($method === 'stripe') {
        // Retrieve the checkout session
        $checkout_session = \Stripe\Checkout\Session::retrieve($session_id);
        
        // Check if payment was successful
        if ($checkout_session->payment_status !== 'paid') {
            throw new Exception("Payment not completed. Status: " . $checkout_session->payment_status);
        }
        
        // Retrieve payment intent for full details
        $payment_intent = \Stripe\PaymentIntent::retrieve($checkout_session->payment_intent);
        
        // Check if payment already recorded
        $check_stmt = $pdo->prepare("SELECT id FROM paypal_payments WHERE transaction_id = ?");
        $check_stmt->execute([$payment_intent->id]);
        
        if ($check_stmt->rowCount() == 0) {
            // Payment not yet recorded, insert it
            $invoice_no = "RSIS-" . $tracking_code;
            $payment_method = "stripe";
            $status = $payment_intent->status === 'succeeded' ? 'COMPLETED' : strtoupper($payment_intent->status);
            $payer_email = $checkout_session->customer_details->email ?? $checkout_session->customer_email ?? '';
            $payer_name = $checkout_session->customer_details->name ?? '';
            $amount = $checkout_session->amount_total / 100; // Convert from cents
            $currency = strtoupper($checkout_session->currency);
            
            $raw_response = json_encode([
                'checkout_session' => json_decode(json_encode($checkout_session), true),
                'payment_intent' => json_decode(json_encode($payment_intent), true)
            ]);
            
            $insert_stmt = $pdo->prepare("
                INSERT INTO paypal_payments 
                (tracking_code, invoice_no, payment_method, session_id, transaction_id, status, 
                 payer_email, payer_name, amount, currency, raw_response, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $insert_stmt->execute([
                $tracking_code,
                $invoice_no,
                $payment_method,
                $session_id,
                $payment_intent->id,
                $status,
                $payer_email,
                $payer_name,
                $amount,
                $currency,
                $raw_response
            ]);
            
            // Update submissions table - mark as paid
            $update_submission = $pdo->prepare("
                UPDATE submissions 
                SET fee_paid = 1, payment_date = NOW(), updated_at = NOW()
                WHERE tracking_code = ?
            ");
            $update_submission->execute([$tracking_code]);
            
            $payment_saved = true;
        } else {
            // Payment already recorded
            $payment_saved = true;
        }
        
        // Store payment details for display
        $payment_details = [
            'tracking_code' => $tracking_code,
            'invoice_no' => 'RSIS-' . $tracking_code,
            'amount' => number_format($checkout_session->amount_total / 100, 2),
            'currency' => strtoupper($checkout_session->currency),
            'payment_id' => $payment_intent->id,
            'session_id' => $session_id,
            'status' => $payment_intent->status === 'succeeded' ? 'COMPLETED' : strtoupper($payment_intent->status),
            'method' => 'Stripe',
            'payer_email' => $checkout_session->customer_details->email ?? '',
            'payer_name' => $checkout_session->customer_details->name ?? '',
            'title' => $submission['title'] ?? ''
        ];
        
    } else if ($method === 'paypal' || $method === 'razorpay') {
        // For PayPal and Razorpay, fetch from database as payment is already saved
        $stmt = $pdo->prepare("
        SELECT * FROM paypal_payments 
        WHERE (order_id = ? OR capture_id = ? OR transaction_id = ?) 
        AND tracking_code = ? 
        ORDER BY id DESC LIMIT 1
    ");
    $stmt->execute([$session_id, $session_id, $session_id, $tracking_code]);
        $payment_row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$payment_row) {
            throw new Exception("Payment record not found in database");
        }
        
        $payment_saved = true;
        
        // Store payment details for display
        $payment_details = [
            'tracking_code' => $tracking_code,
            'invoice_no' => 'RSIS-' . $tracking_code,
            'amount' => number_format($payment_row['amount'], 2),
            'currency' => strtoupper($payment_row['currency']),
        'payment_id' => $payment_row['transaction_id'] ?? $payment_row['capture_id'],
            'session_id' => $session_id,
            'status' => $payment_row['status'],
            'method' => ucfirst($method),
            'payer_email' => $payment_row['payer_email'] ?? '',
            'payer_name' => $payment_row['payer_name'] ?? '',
            'title' => $submission['title'] ?? ''
        ];
    }
    
} catch (Exception $e) {
    error_log("Payment success page error: " . $e->getMessage());
    $error_message = $e->getMessage();
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Payment <?php echo $payment_saved ? 'Successful' : 'Status'; ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    body{
      font-family:Arial,Helvetica,sans-serif;
      background:#f5f7fb;
      padding:20px;
      margin:0;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
    }
    .card{
      max-width:600px;
      margin: 20px auto;
      background:#fff;
      padding:40px;
      border-radius:8px;
      border:1px solid #e1e5ea;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      text-align: center;
    }
    .success-icon{
      width: 80px;
      height: 80px;
      background: #28a745;
      border-radius: 50%;
      margin: 0 auto 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 48px;
      color: white;
    }
    .error-icon{
      width: 80px;
      height: 80px;
      background: #dc3545;
      border-radius: 50%;
      margin: 0 auto 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 48px;
      color: white;
    }
    h1{
      color: #28a745;
      margin-bottom: 10px;
    }
    h1.error{
      color: #dc3545;
    }
    p{
      line-height: 1.6;
      margin: 10px 0;
    }
    .details{
      background: #f8f9fa;
      padding: 20px;
      border-radius: 6px;
      margin: 20px 0;
      text-align: left;
    }
    .details strong{
      display: block;
      color: #333;
      margin-bottom: 5px;
    }
    .details div{
      margin-bottom: 10px;
    }
    .btn{
      display: inline-block;
      background: #635bff;
      color: white;
      padding: 12px 30px;
      border-radius: 6px;
      text-decoration: none;
      margin: 10px 5px;
      font-weight: 600;
    }
    .btn:hover{
      background: #4f46e5;
    }
    .btn-success{
      background: #28a745;
    }
    .btn-success:hover{
      background: #218838;
    }
    .warning{
      background: #fff3cd;
      border: 1px solid #ffc107;
      padding: 15px;
      border-radius: 6px;
      margin: 20px 0;
      color: #856404;
      text-align: left;
    }
    .error-box{
      background: #f8d7da;
      border: 1px solid #f5c6cb;
      padding: 15px;
      border-radius: 6px;
      margin: 20px 0;
      color: #721c24;
      text-align: left;
    }
    .payment-badge{
      display: inline-block;
      padding: 5px 12px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      margin-left: 8px;
    }
    .badge-stripe{
      background: #635bff;
      color: white;
    }
    .badge-paypal{
      background: #0070ba;
      color: white;
    }
    .badge-razorpay{
      background: #3399cc;
      color: white;
    }
    .journal-info{
      background: #e3f2fd;
      padding: 15px;
      border-radius: 6px;
      margin: 20px 0;
      border-left: 4px solid #0070ba;
    }
    footer{
      text-align: center;
      padding: 20px;
      background: #111;
      color: #aaa;
      font-size: 14px;
      margin-top: 40px;
    }
  </style>
</head>
<body>
  <div class="card">
    <?php if ($payment_saved && !$error_message): ?>
      <div class="success-icon">✓</div>
      <h1>Payment Successful!</h1>
      <p>
        Thank you for your payment. Your transaction has been completed successfully 
        <span class="payment-badge badge-<?php echo strtolower($payment_details['method']); ?>">
          <?php echo htmlspecialchars($payment_details['method']); ?>
        </span>
      </p>
      <button class="btn" id="downloadReceipt">⬇ Download Receipt</button>

      <div class="details">
        <div>
          <strong>Tracking Code:</strong>
          <?php echo htmlspecialchars($payment_details['tracking_code']); ?>
        </div>
        <div>
          <strong>Invoice No:</strong>
          <?php echo htmlspecialchars($payment_details['invoice_no']); ?>
        </div>
        <?php if (!empty($payment_details['title'])): ?>
        <div>
          <strong>Paper Title:</strong>
          <?php echo htmlspecialchars($payment_details['title']); ?>
        </div>
        <?php endif; ?>
        <div>
          <strong>Amount:</strong>
          <?php 
          $curr = $payment_details['currency'];
          if ($curr === 'INR') {
              echo '₹';
          } else if ($curr === 'BDT') {
              echo '৳';
          } else if ($curr === 'TRY') {
              echo '₺';
          } else if ($curr === 'PKR') {
              echo 'Rs ';
          } else if ($curr === 'NGN') {
              echo '₦';
          } else {
              echo '$';
          }
          echo htmlspecialchars($payment_details['amount']) . ' ' . htmlspecialchars($curr);
          ?>
        </div>
        <div>
          <strong>Payment Method:</strong>
          <?php echo htmlspecialchars($payment_details['method']); ?>
        </div>
        <div>
          <strong>Transaction ID:</strong>
          <?php echo htmlspecialchars($payment_details['payment_id']); ?>
        </div>
        <?php if (!empty($payment_details['payer_email'])): ?>
        <div>
          <strong>Payer Email:</strong>
          <?php echo htmlspecialchars($payment_details['payer_email']); ?>
        </div>
        <?php endif; ?>
        <div>
          <strong>Status:</strong>
          <span style="color: #28a745; font-weight: bold;">✓ <?php echo htmlspecialchars($payment_details['status']); ?></span>
        </div>
      </div>
      
      <?php if ($journal_info): ?>
      <div class="journal-info">
        <strong>📘 Journal Information:</strong><br>
        <p style="margin: 10px 0;"><?php echo htmlspecialchars($journal_info['name']); ?></p>
        <p style="margin: 5px 0; font-size: 14px;">ISSN: <?php echo htmlspecialchars($journal_info['issn']); ?> | DOI: <?php echo htmlspecialchars($journal_info['doi']); ?></p>
      </div>
      <?php endif; ?>
      
      <div class="warning">
        <strong>⚠️ Important - Next Steps:</strong><br>
        Please upload the following documents via the final submission system:
        <ul style="margin: 10px 0;">
          <li>Author Declaration</li>
          <li>Final Paper</li>
          <li>Payment Proof/Receipt</li>
        </ul>
      </div>
      
      <?php if ($journal_info): ?>
      <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #ffc107;">
        <a href="<?php echo htmlspecialchars($journal_info['final_link']); ?>" class="btn btn-success" target="_blank">
          📤 Submit Final Manuscript
        </a>
        <a href="<?php echo htmlspecialchars($journal_info['declaration_link']); ?>" class="btn" target="_blank">
          📄 Download Declaration Form
        </a>
      </div>
      <?php endif; ?>

      <p style="font-size: 13px; color: #999; margin-top: 20px;">
        Your payment has been recorded in our system. Save this page or take a screenshot for your records.
      </p>
      
    <?php else: ?>
      <div class="error-icon">✕</div>
      <h1 class="error">Payment Processing Issue</h1>
      <p>We encountered an issue while processing your payment details.</p>
      
      <div class="error-box">
        <strong>Error Details:</strong><br>
        <?php echo htmlspecialchars($error_message); ?>
      </div>
      
      <div class="details">
        <div>
          <strong>Tracking Code:</strong>
          <?php echo htmlspecialchars($tracking_code); ?>
        </div>
        <div>
          <strong>Session ID:</strong>
          <?php echo htmlspecialchars($session_id); ?>
        </div>
        <div>
          <strong>Payment Method:</strong>
          <?php echo htmlspecialchars(ucfirst($method)); ?>
        </div>
      </div>
      
      <p><strong>Please contact support with the above information at: editorialoffice@rsis-international.org</strong></p>
    <?php endif; ?>
    
    <a href="https://rsis.international" class="btn">Return to Home</a>
  </div>

  <footer>
    <p>Copyright © 2025 RSIS International</p>
  </footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
document.getElementById("downloadReceipt")?.addEventListener("click", function (e) {
  e.preventDefault();

  const { jsPDF } = window.jspdf;
  const doc = new jsPDF();

  const receiptData = {
    tracking_code: "<?php echo htmlspecialchars($payment_details['tracking_code'] ?? ''); ?>",
    invoice_no: "<?php echo htmlspecialchars($payment_details['invoice_no'] ?? ''); ?>",
    title: "<?php echo htmlspecialchars($payment_details['title'] ?? ''); ?>",
    amount: "<?php echo htmlspecialchars($payment_details['amount'] ?? ''); ?>",
    currency: "<?php echo htmlspecialchars($payment_details['currency'] ?? ''); ?>",
    payment_id: "<?php echo htmlspecialchars($payment_details['payment_id'] ?? ''); ?>",
    status: "<?php echo htmlspecialchars($payment_details['status'] ?? ''); ?>",
    method: "<?php echo htmlspecialchars($payment_details['method'] ?? ''); ?>",
    payer_email: "<?php echo htmlspecialchars($payment_details['payer_email'] ?? ''); ?>",
    payer_name: "<?php echo htmlspecialchars($payment_details['payer_name'] ?? ''); ?>"
  };

  // Title
  doc.setFont("helvetica", "bold");
  doc.setFontSize(20);
  doc.text("RSIS International - Payment Receipt", 105, 20, { align: "center" });

  // Line
  doc.setLineWidth(0.5);
  doc.line(20, 25, 190, 25);

  // Payment details
  doc.setFontSize(12);
  let y = 40;
  doc.setFont("helvetica", "normal");

  const fields = [
    ["Tracking Code", receiptData.tracking_code],
    ["Invoice No", receiptData.invoice_no],
    ["Amount", receiptData.amount + " " + receiptData.currency],
    ["Payment Method", receiptData.method],
    ["Transaction ID", receiptData.payment_id],
    ["Status", receiptData.status]
  ];
  
  if (receiptData.title) {
    fields.splice(2, 0, ["Paper Title", receiptData.title]);
  }
  
  if (receiptData.payer_email) {
    fields.push(["Payer Email", receiptData.payer_email]);
  }

  fields.forEach(([label, value]) => {
    doc.setFont("helvetica", "bold");
    doc.text(`${label}:`, 25, y);
    doc.setFont("helvetica", "normal");
    doc.text(value, 80, y);
    y += 10;
  });

  y += 10;
  doc.setFont("helvetica", "italic");
  doc.setFontSize(10);
  doc.text("Thank you for your payment. Please keep this receipt for your records.", 25, y);

  y += 10;
  doc.text("Next steps: Submit Author Declaration, Final Paper, and Payment Proof", 25, y);

  y += 15;
  doc.setFont("helvetica", "normal");
  doc.setFontSize(9);
  doc.text("© 2025 RSIS International | https://rsis.international", 25, y);

  // Download file
  doc.save(`RSIS_Receipt_${receiptData.tracking_code}.pdf`);
});
</script>

</body>
</html>