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

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

$minRedeem = (int)(getSetting('min_redeem') ?: 50);
if ($redeemPts < $minRedeem) {
    jsonResponse(['success'=>false,'error'=>"Minimum redeem is {$minRedeem} points."]);
}

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

$memberId   = (int)$member['id'];
$balance    = getMemberBalance($memberId);

if ($redeemPts > $balance) {
    jsonResponse(['success'=>false,'error'=>"Insufficient points. Balance: {$balance} pts."]);
}

$pesoValue = round($redeemPts * (float)(getSetting('point_peso_value') ?: 1), 2);

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

$newBalance = getMemberBalance($memberId);

jsonResponse([
    'success'          => true,
    'points_redeemed'  => $redeemPts,
    'peso_value'       => $pesoValue,
    'new_balance'      => $newBalance,
]);
