<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];
$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    if ($action === 'request_card') {
        $cardType  = $_POST['card_type'] ?? 'visa';
        $cardCat   = $_POST['card_category'] ?? 'debit';
        $cardName  = strtoupper(trim($currentUser['first_name'].' '.$currentUser['last_name']));
        // Generate a masked card number (for display only)
        $pan = '4' . rand(100,999) . ' ' . rand(1000,9999) . ' ' . rand(1000,9999) . ' ' . rand(1000,9999);
        $panRaw = str_replace(' ','',$pan);
        $expM = date('m'); $expY = date('Y') + 4;
        $cvv = str_pad((string)rand(0,999),3,'0',STR_PAD_LEFT);
        $pdo->prepare("INSERT INTO cards (user_id,card_number,card_type,card_category,card_name,expiry_month,expiry_year,cvv,status) VALUES (?,?,?,?,?,?,?,'000','active')")->execute([$uid,$panRaw,$cardType,$cardCat,$cardName,$expM,$expY]);
        addNotification($pdo,$uid,'New Card Created',"Your new $cardType $cardCat card has been created.",'success');
        $success = 'Card created successfully.';
    }
    if ($action === 'freeze') {
        $pdo->prepare("UPDATE cards SET status='frozen' WHERE id=? AND user_id=?")->execute([(int)$_POST['card_id'],$uid]);
        $success = 'Card frozen.';
    }
    if ($action === 'unfreeze') {
        $pdo->prepare("UPDATE cards SET status='active' WHERE id=? AND user_id=?")->execute([(int)$_POST['card_id'],$uid]);
        $success = 'Card unfrozen.';
    }
}

$cards = $pdo->prepare("SELECT * FROM cards WHERE user_id=? ORDER BY is_default DESC,created_at DESC");
$cards->execute([$uid]); $cardList = $cards->fetchAll();
$pageTitle = 'My Cards';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container">
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-credit-card me-2 text-danger"></i>My Cards</div>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newCardModal"><i class="fa fa-plus me-1"></i>Request Card</button>
</div>
<?php if ($error): ?><div class="alert alert-danger"><?= sanitize($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= sanitize($success) ?></div><?php endif; ?>

<?php if (empty($cardList)): ?>
<div class="card text-center p-5 text-muted">
  <i class="fa fa-credit-card fa-3x mb-3 d-block text-muted"></i>
  <h5>No Cards Yet</h5>
  <p>Request your first card to get started.</p>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newCardModal">Request Card</button>
</div>
<?php else: ?>
<div class="row g-4">
  <?php foreach ($cardList as $c):
    $cardClass = $c['card_type'];
    $pan = str_replace(' ','',$c['card_number']);
    $masked = '**** **** **** ' . substr($pan,-4);
    $expFmt = str_pad($c['expiry_month'],2,'0',STR_PAD_LEFT) . '/' . substr($c['expiry_year'],-2);
  ?>
  <div class="col-md-6">
    <div class="bank-card <?= $cardClass ?>">
      <div class="d-flex justify-content-between align-items-start">
        <span class="small opacity-75"><?= strtoupper($c['card_category']) ?> CARD</span>
        <?= $c['is_default'] ? '<span class="badge bg-warning text-dark">Default</span>' : '' ?>
        <?= statusBadge($c['status']) ?>
      </div>
      <div class="card-number"><?= sanitize($masked) ?></div>
      <div class="d-flex justify-content-between align-items-end">
        <div>
          <div class="card-holder"><?= sanitize($c['card_name']) ?></div>
          <div class="card-expiry mt-1">Exp: <?= $expFmt ?></div>
        </div>
        <div style="font-size:1.6rem;font-weight:800;font-style:italic;"><?= strtoupper($c['card_type']) ?></div>
      </div>
    </div>
    <div class="d-flex gap-2 mt-2">
      <?php if ($c['status']==='active'): ?>
      <form method="POST" class="flex-fill">
        <?= csrf_field() ?><input type="hidden" name="action" value="freeze"><input type="hidden" name="card_id" value="<?= $c['id'] ?>">
        <button class="btn btn-outline-warning btn-sm w-100"><i class="fa fa-snowflake me-1"></i>Freeze</button>
      </form>
      <?php elseif ($c['status']==='frozen'): ?>
      <form method="POST" class="flex-fill">
        <?= csrf_field() ?><input type="hidden" name="action" value="unfreeze"><input type="hidden" name="card_id" value="<?= $c['id'] ?>">
        <button class="btn btn-outline-success btn-sm w-100"><i class="fa fa-fire me-1"></i>Unfreeze</button>
      </form>
      <?php endif; ?>
      <span class="btn btn-outline-secondary btn-sm flex-fill text-center">
        Daily Limit: <?= money((float)$c['daily_limit'],$currentUser['currency']) ?>
      </span>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>
</div></div>
<?php include 'includes/footer.php'; ?>
<!-- New Card Modal -->
<div class="modal fade" id="newCardModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Request New Card</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="request_card">
    <div class="mb-3"><label class="form-label">Card Network</label>
      <select name="card_type" class="form-select">
        <option value="visa">Visa</option><option value="mastercard">Mastercard</option>
        <option value="verve">Verve</option><option value="amex">American Express</option>
      </select>
    </div>
    <div class="mb-3"><label class="form-label">Card Category</label>
      <select name="card_category" class="form-select">
        <option value="debit">Debit</option><option value="credit">Credit</option><option value="prepaid">Prepaid</option>
      </select>
    </div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary">Request Card</button></div>
  </form>
</div></div></div>
</body></html>
