<?php
/**
 * Tom's Java Jive - Redeem Gift Card API
 */

header('Content-Type: application/json');

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/loyalty.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

if (!CustomerAuth::isLoggedIn()) {
    jsonResponse(['error' => 'Please log in to redeem a gift card'], 401);
}

$customer = CustomerAuth::getFullUser();
$input = json_decode(file_get_contents('php://input'), true);

$result = loyalty()->redeemGiftCardToWallet($customer['customer_id'], $input['code'] ?? '');

if (!$result['success']) {
    jsonResponse(['error' => $result['error']], 400);
}

jsonResponse([
    'success'     => true,
    'amount'      => $result['amount'],
    'new_balance' => $result['new_balance'],
    'message'     => formatCurrency($result['amount']) . ' has been added to your wallet!'
]);
