<?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'] ?? '');
$amount   = (float)($_POST['amount'] ?? 0);
$notes    = trim($_POST['notes']     ?? '');

if (!$cardCode)    jsonResponse(['success'=>false,'error'=>'Card code missing.']);
if ($amount <= 0)  jsonResponse(['success'=>false,'error'=>'Amount must be greater than zero.']);

$member = getMemberByCard($cardCode);
if (!$member)         jsonResponse(['success'=>false,'error'=>'Card not found.']);
if (!$member['name']) jsonResponse(['success'=>false,'error'=>'Member not registered. Please register the card first.']);
if ($member['status'] !== 'active') jsonResponse(['success'=>false,'error'=>'This member account is inactive.']);

$points   = calculatePoints($amount);
$memberId = (int)$member['id'];

$db = getDB();
$stmt = $db->prepare("
    INSERT INTO transactions (member_id, amount, points, type, notes, cashier_id, created_at)
    VALUES (?, ?, ?, 'earn', ?, ?, NOW())
");
$stmt->execute([$memberId, $amount, $points, $notes ?: null, $_SESSION['user_id']]);

$newBalance = getMemberBalance($memberId);

jsonResponse([
    'success'       => true,
    'points_earned' => $points,
    'new_balance'   => $newBalance,
    'message'       => "Purchase of ₱" . number_format($amount, 2) . " recorded. Earned {$points} point(s).",
]);
