<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/helpers.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header('Location: dashboard.php'); exit; }
if (empty($_POST['csrf']) || $_POST['csrf'] !== ($_SESSION['csrf'] ?? '')) {
  flash_err('Invalid request token.'); header('Location: dashboard.php'); exit;
}

// Ensure the user has a card; if not, create it first
$st = $pdo->prepare("SELECT id, is_active FROM cards WHERE user_id=:id LIMIT 1");
$st->execute([':id'=>$_SESSION['uid']]);
$card = $st->fetch();

if (!$card) {
  $ins = $pdo->prepare("INSERT INTO cards (user_id, card_number, cvv, exp_month, exp_year, is_active)
                        VALUES (:uid, :num, :cvv, :m, :y, 0)");
  $ins->execute([
    ':uid'=>$_SESSION['uid'],
    ':num'=>gen_card_number(),
    ':cvv'=>gen_cvv(),
    ':m'=>gen_expiry_month(),
    ':y'=>gen_expiry_year(),
  ]);
}

// Activate it
$upd = $pdo->prepare("UPDATE cards SET is_active=1 WHERE user_id=:id");
$upd->execute([':id'=>$_SESSION['uid']]);

flash_ok('Your virtual card is now active.');
header('Location: dashboard.php'); exit;
