<?php
session_start();
include("config/db.php");
require_once("config/paystack.php"); // defines PAYSTACK_SECRET and PAYSTACK_PUBLIC

// ── Auth guard ───────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    header("Location: signin.php?redirect=" . urlencode($_SERVER['REQUEST_URI']));
    exit;
}
$uid = (int)$_SESSION['user_id'];

// ── Fetch wallet & user ──────────────────────────────────────────────────────
$wb = $conn->prepare("SELECT balance FROM wallets WHERE user_id=? AND wallet_type='customer' LIMIT 1");
$wb->bind_param("i", $uid); $wb->execute();
$wallet_row     = $wb->get_result()->fetch_assoc();
$wallet_balance = $wallet_row ? (float)$wallet_row['balance'] : 0.00;

$ue = $conn->prepare("SELECT name, email, phone FROM users WHERE id=? LIMIT 1");
$ue->bind_param("i", $uid); $ue->execute();
$user = $ue->get_result()->fetch_assoc();

$error   = "";
$success = "";
$step    = "form";

// ────────────────────────────────────────────────────────────────────────────
// STEP A — AJAX: Save pending reference before popup opens (no cURL needed)
// ────────────────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_ref') {
    header('Content-Type: application/json');
    $ref    = preg_replace('/[^A-Za-z0-9_]/', '', $_POST['ref'] ?? '');
    $amount = (float)($_POST['amount'] ?? 0);

    if (!$ref || $amount < 100) {
        echo json_encode(['ok' => false, 'msg' => 'Invalid data']);
        exit;
    }
    // Avoid duplicate inserts on retry
    $chk = $conn->prepare("SELECT id FROM paystack_transactions WHERE reference=? LIMIT 1");
    $chk->bind_param("s", $ref); $chk->execute();
    if ($chk->get_result()->num_rows === 0) {
        $ins = $conn->prepare("INSERT INTO paystack_transactions (user_id, reference, amount, status) VALUES (?,?,?,'pending')");
        $ins->bind_param("isd", $uid, $ref, $amount);
        $ins->execute();
    }
    echo json_encode(['ok' => true]);
    exit;
}

// ────────────────────────────────────────────────────────────────────────────
// STEP B — Verify after Paystack redirects back (?verify=1&ref=...)
// ────────────────────────────────────────────────────────────────────────────
if (isset($_GET['verify'], $_GET['ref'])) {
    $ref  = preg_replace('/[^A-Za-z0-9_]/', '', $_GET['ref']);
    $step = "verify";

    $pt = $conn->prepare("SELECT * FROM paystack_transactions WHERE reference=? AND user_id=? LIMIT 1");
    $pt->bind_param("si", $ref, $uid); $pt->execute();
    $txn = $pt->get_result()->fetch_assoc();

    if (!$txn) {
        $error = "Transaction reference not found. Please contact support.";
        $step  = "form";

    } elseif ($txn['status'] === 'success') {
        // Already credited — idempotent, just show success
        $success        = number_format((float)$txn['amount'], 0);
        $step           = "done";

    } else {
        // Verify with Paystack API via cURL
        $ch = curl_init("https://api.paystack.co/transaction/verify/" . rawurlencode($ref));
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTPHEADER     => [
                "Authorization: Bearer " . PAYSTACK_SECRET,
                "Cache-Control: no-cache"
            ]
        ]);
        $result   = curl_exec($ch);
        $curl_err = curl_error($ch);
        curl_close($ch);

        if ($curl_err || !$result) {
            $error = "Could not verify payment. Contact support with reference: <strong>$ref</strong>";
            $step  = "form";
        } else {
            $response = json_decode($result, true);

            if ($response && $response['status'] === true && $response['data']['status'] === 'success') {
                $paid_amount = (int)$response['data']['amount'] / 100;

                $conn->begin_transaction();
                try {
                    $upd = $conn->prepare("UPDATE paystack_transactions SET status='success', response=? WHERE reference=?");
                    $resp_str = json_encode($response['data']);
                    $upd->bind_param("ss", $resp_str, $ref); $upd->execute();

                    $credit = $conn->prepare("UPDATE wallets SET balance=balance+?, updated_at=NOW() WHERE user_id=? AND wallet_type='customer'");
                    $credit->bind_param("di", $paid_amount, $uid); $credit->execute();

                    $wt_desc = "Wallet funded via Paystack";
                    $wt = $conn->prepare("INSERT INTO wallet_transactions (user_id, wallet_type, amount, type, reference, description, status) VALUES (?, 'customer', ?, 'credit', ?, ?, 'success')");
                    $wt->bind_param("idss", $uid, $paid_amount, $ref, $wt_desc); $wt->execute();

                    $conn->commit();

                    $wb2 = $conn->prepare("SELECT balance FROM wallets WHERE user_id=? AND wallet_type='customer' LIMIT 1");
                    $wb2->bind_param("i", $uid); $wb2->execute();
                    $wallet_balance = (float)$wb2->get_result()->fetch_assoc()['balance'];
                    $success        = number_format($paid_amount, 0);
                    $step           = "done";

                } catch (Exception $e) {
                    $conn->rollback();
                    $error = "Payment received but wallet credit failed. Contact support: <strong>$ref</strong>";
                    $step  = "form";
                }

            } else {
                $conn->prepare("UPDATE paystack_transactions SET status='failed' WHERE reference=?")
                     ->bind_param("s", $ref);
                $error = "Payment was not completed or was cancelled. Please try again.";
                $step  = "form";
            }
        }
    }

    // Refresh balance for display
    if ($step !== 'done') {
        $wb->execute();
        $wallet_balance = (float)($wb->get_result()->fetch_assoc()['balance'] ?? 0);
    }
}

$proto         = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$callback_base = $proto . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

$page_title = 'Top Up Wallet';
$active_nav = 'wallet';
include("includes/header.php");
?>

<!-- Paystack Inline JS — opens a popup, NO server-side cURL needed to start payment -->
<script src="https://js.paystack.co/v1/inline.js"></script>

<div style="max-width:480px;margin:0 auto">

  <div style="margin-bottom:24px">
    <a href="javascript:history.back()"
       style="display:inline-flex;align-items:center;gap:6px;font-size:.82rem;color:var(--text-muted);font-weight:600;margin-bottom:14px">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
        <path d="M19 12H5m0 0l7 7M5 12l7-7"/>
      </svg>
      Back
    </a>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Top Up Wallet</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Fund your Dabil wallet to place orders</p>
  </div>

  <!-- Balance card -->
  <div style="background:linear-gradient(135deg,#1a3dbd,var(--primary) 55%,#4f79ea);border-radius:18px;padding:22px 24px;margin-bottom:24px;color:#fff">
    <div style="font-size:.72rem;font-weight:700;opacity:.72;text-transform:uppercase;letter-spacing:.1em;margin-bottom:5px">Current Balance</div>
    <div style="font-size:2rem;font-weight:800;letter-spacing:-.02em">
      ₦<?php echo number_format($wallet_balance, 2); ?>
    </div>
    <div style="font-size:.78rem;opacity:.7;margin-top:4px"><?php echo htmlspecialchars($user['name']); ?></div>
  </div>

  <?php if ($error): ?>
  <div class="alert alert-error" style="margin-bottom:20px">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" style="flex-shrink:0;width:18px;height:18px">
      <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
    </svg>
    <?php echo $error; ?>
  </div>
  <?php endif; ?>

  <?php if ($step === 'done'): ?>
  <!-- SUCCESS -->
  <div class="card" style="padding:48px 32px;text-align:center">
    <div style="width:68px;height:68px;background:var(--success-bg);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 18px;border:3px solid var(--success)">
      <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2.5" stroke-linecap="round">
        <path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>
      </svg>
    </div>
    <h2 style="font-size:1.4rem;font-weight:800;margin-bottom:8px">Wallet Funded! 🎉</h2>
    <p style="color:var(--text-muted);font-size:.875rem;margin-bottom:4px">
      <strong style="color:var(--primary);font-size:1.15rem">₦<?php echo $success; ?></strong> added to your wallet
    </p>
    <p style="color:var(--text-muted);font-size:.82rem;margin-bottom:28px">
      New balance: <strong>₦<?php echo number_format($wallet_balance, 2); ?></strong>
    </p>
    <div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap">
      <a href="javascript:history.back()" class="btn btn-primary btn-md">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
        Continue Order
      </a>
      <a href="fund_wallet.php" class="btn btn-secondary btn-md">Top Up More</a>
    </div>
  </div>

  <?php else: ?>
  <!-- TOP-UP FORM -->
  <div class="card">
    <div class="card-header"><h3>Enter Amount</h3></div>
    <div class="card-body">

      <!-- Quick preset chips -->
      <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:20px">
        <?php foreach ([500, 1000, 2000, 5000, 10000] as $preset): ?>
        <button type="button"
                onclick="setAmount(<?php echo $preset; ?>)"
                class="preset-chip"
                style="padding:7px 16px;border-radius:20px;border:1.5px solid var(--border);background:var(--white);font-size:.82rem;font-weight:700;cursor:pointer;transition:all .2s;color:var(--text)">
          ₦<?php echo number_format($preset, 0); ?>
        </button>
        <?php endforeach; ?>
      </div>

      <!-- Amount input -->
      <div class="form-group" style="margin-bottom:20px">
        <label style="font-weight:700;margin-bottom:8px;display:block">Amount (₦)</label>
        <div style="position:relative">
          <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-weight:800;font-size:1rem;color:var(--primary)">₦</span>
          <input type="number"
                 id="amountInput"
                 class="form-control"
                 placeholder="0"
                 min="100"
                 step="50"
                 style="padding-left:32px;font-size:1.15rem;font-weight:700"
                 oninput="onAmountChange(this.value)">
        </div>
        <div style="font-size:.72rem;color:var(--text-muted);margin-top:5px">Minimum ₦100 · Secured by Paystack</div>
      </div>

      <!-- Live preview -->
      <div id="payPreview" style="display:none;background:var(--bg);border-radius:10px;padding:13px 16px;margin-bottom:20px">
        <div style="display:flex;justify-content:space-between;margin-bottom:5px">
          <span style="font-size:.82rem;color:var(--text-muted)">Adding to wallet</span>
          <span style="font-size:.9rem;font-weight:800;color:var(--primary)" id="previewAmt">₦0</span>
        </div>
        <div style="display:flex;justify-content:space-between">
          <span style="font-size:.82rem;color:var(--text-muted)">New balance will be</span>
          <span style="font-size:.82rem;font-weight:700" id="previewNew">₦0</span>
        </div>
      </div>

      <!-- Pay button -->
      <button id="payBtn"
              onclick="startPayment()"
              class="btn btn-primary btn-lg"
              style="width:100%;justify-content:center;opacity:.5;cursor:not-allowed"
              disabled>
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round">
          <path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/>
          <path d="M3 5v14a2 2 0 002 2h16v-5"/>
          <path d="M18 12a2 2 0 000 4h4v-4z"/>
        </svg>
        Pay with Paystack
      </button>

      <div style="display:flex;align-items:center;justify-content:center;gap:6px;margin-top:12px">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" stroke-width="2" stroke-linecap="round">
          <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/>
        </svg>
        <span style="font-size:.72rem;color:var(--text-muted)">256-bit SSL · Secured by Paystack</span>
      </div>

    </div>
  </div>
  <?php endif; ?>

</div>

<script>
const PAYSTACK_PK   = <?php echo json_encode(PAYSTACK_PUBLIC); ?>;
const USER_EMAIL    = <?php echo json_encode($user['email']); ?>;
const USER_NAME     = <?php echo json_encode($user['name']); ?>;
const USER_PHONE    = <?php echo json_encode($user['phone'] ?? ''); ?>;
const CALLBACK_BASE = <?php echo json_encode($callback_base); ?>;
const CURRENT_BAL   = <?php echo $wallet_balance; ?>;

let currentAmount = 0;

function fmt(n) {
  return '₦' + Number(n).toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

function setAmount(val) {
  document.getElementById('amountInput').value = val;
  onAmountChange(val);
  document.querySelectorAll('.preset-chip').forEach(b => {
    const chipVal = parseInt(b.textContent.replace(/[₦,\s]/g, ''));
    b.style.borderColor = chipVal === val ? 'var(--primary)' : 'var(--border)';
    b.style.background  = chipVal === val ? 'var(--primary-bg)' : 'var(--white)';
    b.style.color       = chipVal === val ? 'var(--primary)' : 'var(--text)';
  });
}

function onAmountChange(val) {
  currentAmount = parseFloat(val) || 0;
  const btn     = document.getElementById('payBtn');
  const preview = document.getElementById('payPreview');

  if (currentAmount >= 100) {
    btn.disabled          = false;
    btn.style.opacity     = '1';
    btn.style.cursor      = 'pointer';
    preview.style.display = 'block';
    document.getElementById('previewAmt').textContent = fmt(currentAmount);
    document.getElementById('previewNew').textContent = fmt(CURRENT_BAL + currentAmount);
  } else {
    btn.disabled          = true;
    btn.style.opacity     = '.5';
    btn.style.cursor      = 'not-allowed';
    preview.style.display = 'none';
  }
}

function generateRef() {
  return 'DABIL_' + Date.now() + Math.floor(Math.random() * 90 + 10);
}

function startPayment() {
  if (currentAmount < 100) return;

  const ref = generateRef();
  const btn = document.getElementById('payBtn');

  // Show spinner immediately
  btn.disabled      = true;
  btn.style.opacity = '.7';
  btn.innerHTML     = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
    style="animation:spin .8s linear infinite"><circle cx="12" cy="12" r="10" stroke-dasharray="30 70"/></svg> Opening payment…`;

  // Save ref to DB via AJAX, then open Paystack popup
  fetch('fund_wallet.php', {
    method:  'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body:    'action=save_ref&ref=' + encodeURIComponent(ref) + '&amount=' + currentAmount
  })
  .then(r => r.json())
  .then(data => {
    if (!data.ok) {
      showError('Could not initialise transaction. Please try again.');
      resetBtn();
      return;
    }

    // ── Open Paystack inline popup ──────────────────────────────────────────
    const handler = PaystackPop.setup({
      key:      PAYSTACK_PK,
      email:    USER_EMAIL,
      amount:   Math.round(currentAmount * 100), // naira → kobo
      ref:      ref,
      currency: 'NGN',
      label:    'Dabil Wallet Top-Up',
      metadata: {
        custom_fields: [{
          display_name: 'Customer', variable_name: 'customer', value: USER_NAME
        }]
      },
      callback: function(response) {
        // Payment completed — redirect to verify
        window.location.href = CALLBACK_BASE + '?verify=1&ref=' + encodeURIComponent(response.reference);
      },
      onClose: function() {
        // User dismissed popup without paying
        resetBtn();
      }
    });

    handler.openIframe();
  })
  .catch(function() {
    showError('Network error. Please check your internet connection and try again.');
    resetBtn();
  });
}

function resetBtn() {
  const btn = document.getElementById('payBtn');
  btn.disabled      = false;
  btn.style.opacity = '1';
  btn.style.cursor  = 'pointer';
  btn.innerHTML = `<svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round">
    <path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/>
    <path d="M3 5v14a2 2 0 002 2h16v-5"/>
    <path d="M18 12a2 2 0 000 4h4v-4z"/>
  </svg> Pay with Paystack`;
}

function showError(msg) {
  const old = document.getElementById('jsError');
  if (old) old.remove();
  const div = document.createElement('div');
  div.id        = 'jsError';
  div.className = 'alert alert-error';
  div.style.marginBottom = '16px';
  div.innerHTML = `<svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"
    style="flex-shrink:0;width:18px;height:18px"><circle cx="12" cy="12" r="10"/>
    <line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> ${msg}`;
  document.querySelector('.card')?.before(div);
  window.scrollTo({top: 0, behavior: 'smooth'});
}
</script>
<style>@keyframes spin { to { transform: rotate(360deg); } }</style>

<?php include("includes/footer.php"); ?>
