<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/banking.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

$conn = require __DIR__ . '/../../app/config/database.php';
require_login();
$u = current_user();

/* ===============================
   CREATE CARD REQUEST
================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_card'])) {
    try {
        if (user_pending_card_requests($conn, (int)$u['id']) > 0) {
            throw new Exception('You already have a pending request.');
        }

        create_card_request(
            $conn,
            (int)$u['id'],
            $_POST['network'],
            $_POST['tier'],
            $_POST['note'] ?? null
        );

        flash('success','Card request submitted.');
        redirect('cards.php');

    } catch(Throwable $e){
        flash('error',$e->getMessage());
        redirect('cards.php');
    }
}

$cards   = get_user_virtual_cards($conn,(int)$u['id']);
$pending = user_pending_card_requests($conn,(int)$u['id']);

include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

<style>
.preview-card{
  border-radius:20px;
  padding:20px;
  color:#fff;
  background:#1e40af;
  min-height:200px;
  transition:.3s transform,.3s box-shadow;
}
.preview-card.premium{box-shadow:0 0 25px gold}
.preview-card:hover{transform:rotateX(4deg) rotateY(-4deg)}
.progress{height:8px}
.sim-box{border:1px dashed #e5e7eb;border-radius:14px;padding:14px}
.result-ok{color:#16a34a;font-weight:700}
.result-bad{color:#dc2626;font-weight:700}
</style>

<main style="margin-left:240px">
<div class="container-fluid py-4">
<div class="row g-4">

<!-- LEFT COLUMN -->
<div class="col-lg-7">

<h5 class="fw-bold mb-2">Your Virtual Cards</h5>
<div class="row g-3">
<?php foreach($cards as $c): ?>
<div class="col-md-6">
  <div class="preview-card">
    <div><?= strtoupper(e($c['network'])) ?></div>
    <div class="fs-5 my-2">•••• •••• •••• <?= e($c['last4']) ?></div>
    <small><?= e($c['cardholder_name'] ?? 'Card Holder') ?></small>
  </div>
</div>
<?php endforeach ?>
</div>

<!-- SIMULATION -->
<div class="mt-4">
<h6 class="fw-bold">Transaction Simulation</h6>
<div class="sim-box">
  <div class="mb-2">
    <label>Merchant</label>
    <input id="merchant" class="form-control" value="Amazon Store">
  </div>
  <div class="mb-2">
    <label>Amount (₵)</label>
    <input id="amount" type="number" class="form-control" value="50">
  </div>
  <button type="button" onclick="simulate()" class="btn btn-outline-primary btn-sm">
    Simulate
  </button>
  <div id="simResult" class="mt-2"></div>
</div>
</div>

</div>

<!-- RIGHT COLUMN -->
<div class="col-lg-5">
<div class="card p-4">

<?php if($pending): ?>
<div class="alert alert-warning">Pending request exists</div>
<?php else: ?>

<form method="post">
<input type="hidden" name="request_card" value="1">

<h6 class="fw-bold">Live Card Preview</h6>

<div id="preview" class="preview-card mb-3">
  <div class="d-flex justify-content-between align-items-center">
    <span id="tierBadge">STANDARD</span>
    <img id="brandLogo" src="../assets/cards/visa.png" height="26" alt="Brand">
  </div>
  <div class="fs-5 my-3">•••• •••• •••• 1234</div>
  <small><?= e($u['full_name'] ?? $u['username'] ?? $u['email'] ?? 'Card Holder') ?></small>
</div>

<label>Card Type</label>
<select name="network" id="network" class="form-select mb-2">
  <option value="visa">Visa</option>
  <option value="mastercard">Mastercard</option>
</select>

<label>Tier</label>
<select name="tier" id="tier" class="form-select mb-3">
  <option value="standard">Standard</option>
  <option value="premium">Premium</option>
</select>

<h6 class="fw-bold">Spending Limits</h6>

<label>Daily Limit (₵)</label>
<input type="number" name="daily_limit" class="form-control mb-1" value="500">

<label>Monthly Limit (₵)</label>
<input type="number" name="monthly_limit" class="form-control mb-3" value="5000">

<textarea name="note" class="form-control mb-3" placeholder="Optional note"></textarea>

<button class="btn ab-btn w-100 text-white">Submit Request</button>
</form>

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

</div>
</div>
</main>

<script>
document.addEventListener('DOMContentLoaded', () => {

  const preview    = document.getElementById('preview');
  const brandLogo  = document.getElementById('brandLogo');
  const tierBadge  = document.getElementById('tierBadge');
  const networkSel = document.getElementById('network');
  const tierSel    = document.getElementById('tier');
  const amountInp  = document.getElementById('amount');
  const simResult  = document.getElementById('simResult');

  let dailyLimit = 500;

  networkSel.addEventListener('change', () => {
    brandLogo.src = '../assets/cards/' + networkSel.value + '.png';
  });

  tierSel.addEventListener('change', () => {
    if (tierSel.value === 'premium') {
      preview.classList.add('premium');
      tierBadge.innerText = 'PREMIUM';
    } else {
      preview.classList.remove('premium');
      tierBadge.innerText = 'STANDARD';
    }
  });

  window.simulate = function () {
    const amt = parseFloat(amountInp.value || 0);
    simResult.innerHTML = amt > dailyLimit
      ? '<div class="result-bad">DECLINED – Limit Exceeded</div>'
      : '<div class="result-ok">APPROVED ✔</div>';
  };

});
</script>

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
