<?php

ini_set('log_errors', 1);
ini_set('display_errors', 1);
ini_set('error_log', __DIR__ . '/../../error.log');
error_reporting(E_ALL);
require_once __DIR__ . '/../../common/journal_config_new.php';

$tracking_code = isset($_GET['tracking_code']) ? trim($_GET['tracking_code']) : '';
if (!$tracking_code) { die("Invalid request: Tracking Code required"); }

try {
    // Join submissions with authors and journals to get all necessary data
    $stmt = $pdo->prepare("
        SELECT s.*, a.email, a.country, j.name as journal_name 
        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) { die("Wrong link: Tracking Code not found"); }

    // Check if already paid
    if ($submission['fee_paid'] == 1) {
        die("This submission has already been paid. Please contact us if you believe this is an error.");
    }

    $title = htmlspecialchars($submission['title']);
    
    // Parse authors JSON
    // $authors_data = json_decode($submission['authors'], true);
    // $first_author = isset($authors_data[0]['name']) ? htmlspecialchars($authors_data[0]['name']) : 'Author';
    
    // $email = htmlspecialchars($submission['email']);
    // $journal = htmlspecialchars($submission['journal_name']);
    // $country = strtolower(trim($submission['country']));
    
    // Parse authors JSON safely
$authors_raw = $submission['authors'] ?? '[]';
$authors_data = json_decode($authors_raw, true);

// First author
$first_author = isset($authors_data[0]['name']) 
    ? htmlspecialchars($authors_data[0]['name'] ?? '') 
    : 'Author';

// Safe values with NULL fallback
$email   = htmlspecialchars($submission['email'] ?? '');
$journal = htmlspecialchars($submission['journal_name'] ?? '');
$country = strtolower(trim($submission['country'] ?? ''));

    
    // No need to close PDO - it auto-closes
    $stmt = null;
    
} catch (Exception $e) { 
    die("Database error: " . $e->getMessage()); 
}

/* ---------- Payment amount / currency logic ---------- */
$amount = "35.00"; 
$currency = "USD";
$show_paypal = $show_razorpay = $show_stripe = true;
$paypal_amount = ($journal === 'IJLTEMAS') ? "30.00" : "35.00";

$country_currencies = ['bangladesh'=>'BDT','turkey'=>'TRY','pakistan'=>'PKR','nigeria'=>'NGN'];

if (strcasecmp($country, 'India') === 0){
    $amount = ($journal === 'IJRISS') ? "3068.00" : "1500.00";
    $currency = "INR";
    $show_paypal = false; 
    $show_stripe = false;
} else {
    $base_usd = ($journal === 'IJLTEMAS') ? 30.00 : 35.00;
    if (isset($country_currencies[$country])) {
        $currency = $country_currencies[$country];
        $amount = match($country){
            'bangladesh'=> ($journal === 'IJLTEMAS') ? "3640.00" : "4240.00",
            'nigeria'   => ($journal === 'IJLTEMAS') ? "43890.00" : "51100.00",
            'turkey'    => ($journal === 'IJLTEMAS') ? "1250.00" : "1460.00",
            'pakistan'  => ($journal === 'IJLTEMAS') ? "8460.00" : "9870.00",
        };
    } else {
        $currency = "USD";
        $amount   = number_format($base_usd,2,'.','');
    }
}
$invoice_no = "RSIS-".$tracking_code;
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Pay Publication Fee - <?php echo htmlspecialchars($tracking_code); ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <style>
    :root{
      --primary:#0070ba;
      --dark:#0D276E;
      --light-blue:#e3f2fd;
      --yellow:#fff8e1;
      --border:#dee2e6;
      --gap:16px;
    }
    *{box-sizing:border-box;margin:0;padding:0;}
    body{
      font-family:'Segoe UI',Tahoma,sans-serif;
      background:#f8f9fa;
      color:#333;
      line-height:1.4;
      margin:0;
      padding:0;
    }

    .container{
      width:100%;
      max-width:100%;
      margin:0 auto;
      background:#fff;
      min-height:100vh;
      display:flex;
      flex-direction:column;
    }

    .header{
      background:var(--dark);
      color:#fff;
      padding:16px 20px;
      display:flex;
      align-items:center;
      gap:12px;
      font-weight:600;
      width:100%;
    }
    .header img{height:60px;}
    .header span{font-size:1.4rem;font-weight:700;}

    .content{
      padding:20px;
      flex:1;
      width:100%;
    }

    .info-grid{
      display:grid;
      grid-template-columns:1fr 1fr 1fr;
      gap:var(--gap);
      margin-bottom:var(--gap);
      padding:var(--gap);
      background:#f8f9fa;
      border-radius:10px;
      border:1px dashed #ccc;
      font-size:0.9rem;
    }
    .info-item strong{
      display:block;
      color:#666;
      text-transform:uppercase;
      font-size:0.75rem;
      margin-bottom:2px;
    }
    .info-item span{font-weight:600;color:#222;}

    .amount-box{
      background:var(--light-blue);
      border:2px dashed #90caf9;
      border-radius:10px;
      padding:14px;
      text-align:center;
      font-size:1.4rem;
      font-weight:700;
      color:var(--primary);
      margin:16px 0;
      width:100%;
    }

    .notice{
      background:var(--yellow);
      border-left:4px solid #ffb300;
      padding:12px;
      border-radius:8px;
      font-size:0.9rem;
      color:#856404;
      margin:16px 0 0;
      line-height:1.5;
    }

    .payment-methods h3{
      font-size:1.1rem;
      margin:16px 0 10px;
      display:flex;
      align-items:center;
      gap:6px;
      color:#222;
    }
    .method-grid{
      display:grid;
      grid-template-columns:repeat(auto-fit, minmax(220px, 1fr));
      gap:var(--gap);
      margin-bottom:0;
    }
    .method-card{
      border:2px solid #e0e0e0;
      border-radius:10px;
      padding:14px;
      cursor:pointer;
      transition:all .2s;
      background:#fafafa;
      position:relative;
      display:flex;
      align-items:center;
      gap:12px;
      font-size:0.95rem;
      width:100%;
    }
    .method-card:hover{
      border-color:var(--primary);
      background:#f0f8ff;
      box-shadow:0 3px 8px rgba(0,112,186,.15);
    }
    .method-card input{position:absolute;opacity:0;}
    .method-card.selected{
      border-color:var(--primary);
      background:#e3f2fd;
      box-shadow:0 0 0 2px rgba(0,112,186,.2);
    }
    .method-card .icon{font-size:1.6rem;color:var(--primary);}
    .method-card .text{flex:1;}
    .method-card .title{font-weight:600;font-size:1rem;}
    .method-card .price{font-size:0.85rem;color:#555;}

    .btn-pay{
      width:100%;
      background:var(--primary);
      color:#fff;
      padding:14px;
      border-radius:10px;
      border:none;
      cursor:pointer;
      font-size:1.1rem;
      font-weight:600;
      margin:16px 0 0;
      transition:.2s;
    }
    .btn-pay:hover{background:#005a94;}

    #paypal-button-container{margin-top:16px;display:none;}

    #result{
      margin-top:16px;
      padding:12px;
      border-radius:8px;
      display:none;
      font-size:0.9rem;
      font-weight:500;
    }
    #result.success{background:#d4edda;color:#155724;border:1px solid #c3e6cb;}
    #result.error{background:#f8d7da;color:#721c24;border:1px solid #f5c6cb;}

    .bank-details{
      background:#f8f9fa;
      border:1px solid var(--border);
      border-radius:10px;
      padding:16px;
      margin-top:16px;
      font-family:'Courier New',monospace;
      font-size:0.9rem;
      line-height:1.6;
      display:none;
      width:100%;
    }
    .bank-details.show{display:block;}
    .bank-details h4{font-size:1rem;margin-bottom:10px;color:#222;}
    .bank-details p{margin:6px 0;}
    .bank-details strong{color:#222;}
    .notes{
      background:var(--light-blue);
      padding:12px;
      border-radius:8px;
      margin:12px 0;
      border-left:4px solid var(--primary);
      font-size:0.9rem;
    }
    .notes strong{color:#1565c0;}

    .section{
      margin:0 20px 20px;
      padding:20px;
      background:#fff;
      border-radius:10px;
      border:1px solid var(--border);
      box-shadow:0 3px 10px rgba(0,0,0,.05);
      display:none;
    }
    .section.show{display:block;}
    .section h2{
      font-size:1.3rem;
      margin-bottom:14px;
      text-align:center;
      position:relative;
    }
    .section h2::after{
      content:'';
      width:50px;
      height:2px;
      background:var(--primary);
      display:block;
      margin:8px auto 0;
      border-radius:1px;
    }
    .table{
      width:100%;
      border-collapse:collapse;
      margin:14px 0;
      font-size:0.9rem;
    }
    .table th{
      background:#333;
      color:#fff;
      padding:10px;
      text-align:left;
    }
    .table td{
      padding:10px;
      border:1px solid #ddd;
    }
    .table tr:nth-child(even){background:#f9f9f9;}

    footer{
      text-align:center;
      padding:16px;
      background:#111;
      color:#aaa;
      font-size:0.8rem;
      width:100%;
    }

    @media(max-width:640px){
      .info-grid{grid-template-columns:1fr;}
      .method-grid{grid-template-columns:1fr;}
      .header{flex-direction:column;text-align:center;gap:8px;}
      .header span{font-size:1.3rem;}
      .content{padding:16px;}
      .section{margin:0 16px 20px;}
    }
  </style>

  <script src="https://js.stripe.com/v3/"></script>
  <?php if($show_paypal): ?>
  <script src="https://www.paypal.com/sdk/js?client-id=AS0SV3-_cSltPKuxk4YvK1mVtOlpyUg-Da_3KnHigG9rsnL25zXKwmKqxldguo9-bDUrbfeXCt3C10nH"></script>
  <?php endif; ?>
  <?php if($show_razorpay): ?>
  <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
  <?php endif; ?>
</head>
<body>

  <div class="container">
    <div class="header">
      <img src="https://rsis.international/articles/rsis_logo.png" alt="RSIS">
      <span>Publication Fee Payment</span>
    </div>

    <div class="content">
      <div class="info-grid">
        <div class="info-item"><strong>Tracking Code</strong><span><?php echo $tracking_code; ?></span></div>
        <div class="info-item"><strong>Invoice No.</strong><span><?php echo $invoice_no; ?></span></div>
        <div class="info-item"><strong>Journal</strong><span><?php echo $journal; ?></span></div>
      </div>

      <div class="amount-box">
        <?php
        $sym = $currency==='INR'?'₹':($currency==='BDT'?'৳':($currency==='TRY'?'₺':($currency==='PKR'?'Rs ':($currency==='NGN'?'₦':'$'))));
        echo $sym.$amount.' '.$currency;
        ?>
      </div>

      <div class="notice">
        <strong>Important:</strong> After successful payment, upload Author Declaration, Final Paper, and Payment Proof via the Final Submission System.
      </div>

      <div class="payment-methods">
        <h3><i class="fas fa-credit-card"></i> Select Payment Method</h3>
        <div class="method-grid">
          <?php if($show_paypal): ?>
          <label class="method-card" data-method="paypal">
            <input type="radio" name="payment_method" value="paypal">
            <div class="icon"><i class="fab fa-paypal"></i></div>
            <div class="text">
              <div class="title">PayPal</div>
              <div class="price">$<?php echo $paypal_amount; ?> USD</div>
            </div>
          </label>
          <?php endif; ?>

          <?php if($show_stripe): ?>
          <label class="method-card" data-method="stripe">
            <input type="radio" name="payment_method" value="stripe">
            <div class="icon"><i class="fab fa-stripe"></i></div>
            <div class="text">
              <div class="title">Stripe</div>
              <div class="price"><?php echo $sym.$amount.' '.$currency; ?></div>
            </div>
          </label>
          <?php endif; ?>

          <?php if($show_razorpay): ?>
          <label class="method-card" data-method="razorpay">
            <input type="radio" name="payment_method" value="razorpay" <?php echo (!$show_paypal && !$show_stripe)?'checked':''; ?>>
            <div class="icon"><i class="fas fa-bolt"></i></div>
            <div class="text">
              <div class="title">Razorpay</div>
              <div class="price"><?php echo $sym.$amount.' '.$currency; ?></div>
            </div>
          </label>
          <?php endif; ?>

          <label class="method-card" data-method="bank">
            <input type="radio" name="payment_method" value="bank">
            <div class="icon"><i class="fas fa-university"></i></div>
            <div class="text">
              <div class="title">Bank Transfer</div>
              <div class="price">
                <?php echo (strcasecmp($country, 'India') === 0) ? 'via UPI or Net Banking' : 'International Wire'; ?>
              </div>
            </div>
          </label>
        </div>

        <button id="payNowBtn" class="btn-pay">Pay Now</button>
        <div id="paypal-button-container"></div>

        <!-- BANK DETAILS -->
        <div id="bankDetails" class="bank-details">
          <h4><i class="fas fa-info-circle"></i> Bank Transfer Details</h4>
          <p><strong>Bank Name:</strong> Axis Bank</p>
          <p><strong>Account Name:</strong> RSIS International</p>
          <p><strong>Account Number:</strong> 922020064564426</p>
          <p><strong>SWIFT Code:</strong> AXISINBBXXX</p>
          <p><strong>IFSC Code:</strong> UTIB0005029</p>
          <p><strong>UPI ID:</strong> rsisinter@ybl</p>
          <p><strong>Bank Address:</strong> Axis Bank Ground Floor, Shop No. 86, 87, and 88, Emerald Plaza, Sector 65, Gurgaon, Haryana, 122018, India</p>

          <div class="notes">
            <p><strong>Important Notes:</strong></p>
            <ul style="margin:8px 0;padding-left:18px;">
              <?php if(strcasecmp($country, 'India') === 0): ?>
                <li>You can pay using UPI and Net Banking.</li>
                <li>Payments can be made by family, friends, or colleagues.</li>
                <li>Email us at editorialoffice@rsis-international.org for help.</li>
              <?php else: ?>
                <li>Bank Transfer- You may transfer your local currency to our bank account via a standard bank transfer. This method allows you to initiate an international bank transfer from your local bank account to our designated account.</li>
                <li>Here's a step-by-step guide on how to proceed:</li>
                <ol style="margin:6px 0;padding-left:18px;">
                  <li>Provide our bank details, including the SWIFT/BIC code, account number, and any other necessary information required by your bank for international transfers.</li>
                  <li>Initiate the transfer from your local bank, ensuring all required information is accurately provided.</li>
                  <li>Upon completion of the transfer, the funds will be sent to our account in the designated currency.</li>
                  <li><strong>Kindly ensure that the Beneficiary Name is accurately entered as "RSIS International" in the SWIFT application form.</strong></li>
                  <li><strong>Please mention the Payment Purpose in the SWIFT form as: "Online Publication Fees RSIS International".</strong></li>
                  <li>Important: Make sure that your bank processes the transfer using the SWIFT Code: AXISINBBXXX.</li>
                </ol>
              <?php endif; ?>
            </ul>
          </div>
        </div>
      </div>

      <div id="result"></div>
      
    </div>
    
    <!-- NIGERIA CARD RECOMMENDATION -->
    <div id="nigeriaSection" class="section" style="display:<?php echo ($country === 'nigeria') ? 'block' : 'none'; ?>;margin-top:0;">
      <h2>Card Recommendations for Nigeria</h2>
      <p>We recommend using a card from the following banks for smooth international payments:</p>
      <table class="table">
        <thead><tr><th>Card Type</th><th>Bank Name</th><th>Card Category</th></tr></thead>
        <tbody>
          <tr><td>Mastercard</td><td>Providus Bank Limited</td><td>Debit Card</td></tr>
          <tr><td>Mastercard</td><td>Guaranty Trust Bank PLC (GTBank)</td><td>Debit Card</td></tr>
          <tr><td>Mastercard</td><td>Sterling Bank PLC</td><td>Debit Card</td></tr>
          <tr><td>Visa</td><td>United Bank for Africa PLC (UBA)</td><td>Prepaid Card</td></tr>
          <tr><td>Visa</td><td>Standard Chartered Nigeria Bank</td><td>Debit Card</td></tr>
          <tr><td>Visa</td><td>Access Bank PLC</td><td>Debit Card</td></tr>
        </tbody>
      </table>
      <div class="notes">
        <p><strong>Notes:</strong></p>
        <ul>
          <li>These cards support Naira & USD, $100/month limit, work well with Stripe.</li>
          <li>Providus Mastercard is ideal for small payments.</li>
          <li>Apply online or visit the bank.</li>
        </ul>
      </div>
      <h3>Payment Steps</h3>
      <ol>
        <li>Obtain the Card</li><li>Fund Your Account</li><li>Activate the Card</li>
        <li>Link to Stripe/PayPal</li><li>Send Payment</li><li>Share receipt with us</li>
      </ol>
      <p style="margin-top:20px;"><strong>Need help?</strong> Email: <a href="mailto:editorialoffice@rsis-international.org">editorialoffice@rsis-international.org</a></p>
    </div>
  </div>

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

<script>
const TRACKING_CODE = <?php echo json_encode($tracking_code); ?>;
const AMOUNT = <?php echo json_encode($amount); ?>;
const CURRENCY = <?php echo json_encode($currency); ?>;
const PAYPAL_AMOUNT = <?php echo json_encode($paypal_amount); ?>;
const AUTHOR_EMAIL = <?php echo json_encode($email); ?>;
const AUTHOR_NAME = <?php echo json_encode($first_author); ?>;
const SHOW_PAYPAL = <?php echo $show_paypal?'true':'false'; ?>;
const SHOW_RAZORPAY = <?php echo $show_razorpay?'true':'false'; ?>;
const SHOW_STRIPE = <?php echo $show_stripe?'true':'false'; ?>;
const IS_NIGERIA = <?php echo ($country === 'nigeria') ? 'true' : 'false'; ?>;
const IS_INDIA = <?php echo (strcasecmp($country, 'India') === 0) ? 'true' : 'false'; ?>;

const payNowBtn = document.getElementById('payNowBtn');
const paypalContainer = document.getElementById('paypal-button-container');
const bankDetails = document.getElementById('bankDetails');
const nigeriaSection = document.getElementById('nigeriaSection');
let paypalButtonsRendered = false;

function showResult(msg, success) {
  const r = document.getElementById('result');
  r.className = success ? 'success' : 'error';
  r.innerHTML = msg;
  r.style.display = 'block';
  r.scrollIntoView({behavior: 'smooth'});
}

function resetPaymentUI() {
  paypalContainer.style.display = 'none';
  paypalContainer.innerHTML = '';
  bankDetails.classList.remove('show');
  payNowBtn.style.display = 'block';
  payNowBtn.disabled = false;
  payNowBtn.textContent = 'Pay Now';
  paypalButtonsRendered = false;
}

document.querySelectorAll('.method-card').forEach(c => {
  c.addEventListener('click', function() {
    document.querySelectorAll('.method-card').forEach(x => x.classList.remove('selected'));
    this.classList.add('selected');
    this.querySelector('input').checked = true;

    resetPaymentUI();

    if (this.dataset.method === 'bank') {
      bankDetails.classList.add('show');
      if (IS_NIGERIA) nigeriaSection.style.display = "block";
    } else {
      bankDetails.classList.remove('show');
      nigeriaSection.style.display = IS_NIGERIA ? "block" : "none";
    }
  });
});

payNowBtn.addEventListener('click', function() {
  const sel = document.querySelector('input[name="payment_method"]:checked')?.value;
  if (!sel) { showResult('Please select a payment method.', false); return; }
  if (sel === 'paypal' && SHOW_PAYPAL) startPayPal();
  else if (sel === 'razorpay' && SHOW_RAZORPAY) startRazorpay();
  else if (sel === 'stripe' && SHOW_STRIPE) startStripe();
  else if (sel === 'bank') {
    showResult('Please follow the bank details above and send proof to <strong>editorialoffice@rsis-international.org</strong>', true);
  }
});

function startPayPal() {
  if (paypalButtonsRendered) return;
  paypalButtonsRendered = true;
  paypalContainer.style.display = 'block';
  payNowBtn.style.display = 'none';
  paypal.Buttons({
    style: { layout: 'vertical', color: 'blue', shape: 'rect', label: 'paypal', height: 45 },
    createOrder: () => fetch('create_order.php', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({tracking_code:TRACKING_CODE,amount:PAYPAL_AMOUNT,currency:'USD'})
    }).then(r=>r.json()).then(d=>d.id),
    onApprove: (data) => fetch('capture_order.php', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({orderID:data.orderID,tracking_code:TRACKING_CODE})
    }).then(r=>r.json()).then(resp=>{
      if(resp.success)window.location.href=`stripe_success.php?session_id=${data.orderID}&tracking_code=${TRACKING_CODE}&method=paypal`;
      else showResult('Payment failed.',false);
    }).catch(()=>showResult('Error.',false)),
    onError: () => { showResult('PayPal error.', false); resetPaymentUI(); }
  }).render('#paypal-button-container');
}

function startRazorpay() {
  payNowBtn.disabled = true; payNowBtn.textContent = 'Processing...';
  fetch('razorpay_order.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({tracking_code:TRACKING_CODE,amount:AMOUNT,currency:CURRENCY})
  })
  .then(r=>r.json()).then(data=>{
    payNowBtn.disabled=false;
    payNowBtn.textContent='Pay Now';
    if(!data.success||!data.order_id){showResult('Failed to create order.',false);return;}
    new Razorpay({
      key:"rzp_test_RQdQEoWp7dPLEG",
      amount:data.amount,
      currency:data.currency,
      name:"RSIS International",
      description:"Publication Fee - "+TRACKING_CODE,
      order_id:data.order_id,
      handler:(resp)=>{
        fetch('razorpay_capture.php',{
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body:JSON.stringify({
            tracking_code:TRACKING_CODE,
            razorpay_payment_id:resp.razorpay_payment_id,
            razorpay_order_id:resp.razorpay_order_id,
            razorpay_signature:resp.razorpay_signature
          })
        })
        .then(r=>r.json()).then(r=>{
          if(r.success)window.location.href=`stripe_success.php?session_id=${resp.razorpay_payment_id}&tracking_code=${TRACKING_CODE}&method=razorpay`;
          else showResult('Failed.',false);
        });
      },
      prefill:{email:AUTHOR_EMAIL,name:AUTHOR_NAME},
      theme:{color:"#3399cc"},
      modal:{ondismiss:()=>{payNowBtn.disabled=false;payNowBtn.textContent='Pay Now';}}
    }).open();
  }).catch(()=>{payNowBtn.disabled=false;payNowBtn.textContent='Pay Now';showResult('Failed.',false);});
}

const stripe = Stripe('pk_test_51MUPOkSDX9TVziH5BM4KzMyIwqYw9IEqNxzOLXiLsbiIPoQNseHzSfXWxa8GKpWEmI83ohTMpdQNfXBxXodVnFJ0000jEtY1JU');
function startStripe() {
  payNowBtn.disabled = true; payNowBtn.textContent = 'Redirecting...';
  fetch('stripe_checkout.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({tracking_code:TRACKING_CODE,amount:AMOUNT,currency:CURRENCY})
  })
  .then(r=>r.json()).then(data=>{
    if(data.session_id)stripe.redirectToCheckout({sessionId:data.session_id});
    else{payNowBtn.disabled=false;payNowBtn.textContent='Pay Now';showResult('Stripe error.',false);}
  })
  .catch(()=>{payNowBtn.disabled=false;payNowBtn.textContent='Pay Now';showResult('Failed.',false);});
}
</script>
</body>
</html>