<?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'] ?? '');
$name     = trim($_POST['name']      ?? '');
$address  = trim($_POST['address']   ?? '');
$phone    = trim($_POST['phone']     ?? '');

if (!$cardCode) jsonResponse(['success'=>false,'error'=>'Card code missing.']);
if (!$name)     jsonResponse(['success'=>false,'error'=>'Name is required.']);
if (!$phone)    jsonResponse(['success'=>false,'error'=>'Phone number is required.']);

$member = getMemberByCard($cardCode);
if (!$member) jsonResponse(['success'=>false,'error'=>'Card not found. Generate and save the card first.']);

$db   = getDB();
$isNew = empty($member['name']);

$stmt = $db->prepare("
    UPDATE members
       SET name = ?, address = ?, phone = ?, registered_at = COALESCE(registered_at, NOW())
     WHERE card_code = ?
");
$stmt->execute([$name, $address, $phone, $cardCode]);

jsonResponse([
    'success' => true,
    'message' => $isNew
        ? "Member <strong>{$name}</strong> registered successfully!"
        : "Member <strong>{$name}</strong> updated successfully!",
    'is_new'  => $isNew,
]);
