<?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 card exists
$st = $pdo->prepare("SELECT id, status FROM cards WHERE user_id=:id");
$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, status)
                        VALUES (:uid, :num, :cvv, :m, :y, 'inactive')");
  $ins->execute([
    ':uid'=>$_SESSION['uid'],
    ':num'=>gen_card_number(),
    ':cvv'=>gen_cvv(),
    ':m'=>gen_expiry_month(),
    ':y'=>gen_expiry_year(),
  ]);
}

// Move to pending (only if currently inactive)
$upd = $pdo->prepare("UPDATE cards SET status='pending' WHERE user_id=:id AND status='inactive'");
$upd->execute([':id'=>$_SESSION['uid']]);

flash_ok('Card activation requested. Waiting for admin approval.');
header('Location: dashboard.php'); exit;
