<?php
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonResponse(['success'=>false,'error'=>'Method not allowed'], 405);

$cardCode = trim($_POST['card_code'] ?? '');
if (!$cardCode) jsonResponse(['success'=>false,'error'=>'No card code provided.']);

$db = getDB();

// Check duplicate
$check = $db->prepare("SELECT id FROM members WHERE card_code = ?");
$check->execute([$cardCode]);
if ($check->fetch()) {
    jsonResponse(['success'=>false,'error'=>'This card code already exists in the database.']);
}

$stmt = $db->prepare("INSERT INTO members (card_code, qr_data, barcode_data, created_at) VALUES (?,?,?,NOW())");
$stmt->execute([$cardCode, $cardCode, $cardCode]);
$id = $db->lastInsertId();

jsonResponse([
    'success'   => true,
    'message'   => "Card <strong>{$cardCode}</strong> saved successfully! (ID: {$id})",
    'member_id' => $id,
]);
