<?php
/**
 * Tom's Java Jive - Apply Wallet Credit / Gift Card at Checkout
 *
 * Validates and quotes an amount to apply toward the current order total.
 * Does NOT deduct wallet balance here - that only happens once the Square
 * payment actually succeeds (see markSquarePaymentResult() in
 * includes/square.php), so an abandoned checkout never loses a customer's
 * real wallet money. A gift card code, if given, is redeemed into wallet
 * balance immediately (same as the Wallet page does) since that step is
 * safe/reversible-in-spirit - only the *spending* of wallet balance at
 * checkout is deferred to payment success.
 */

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

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

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

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

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

$orderTotal = (float) ($input['order_total'] ?? 0);
if ($orderTotal <= 0) {
    jsonResponse(['error' => 'Invalid order total'], 400);
}

$giftCardCode = trim($input['gift_card_code'] ?? '');

if (!empty($giftCardCode)) {
    $redeemResult = loyalty()->redeemGiftCardToWallet($customer['customer_id'], $giftCardCode);
    if (!$redeemResult['success']) {
        jsonResponse(['error' => $redeemResult['error']], 400);
    }
    $walletBalance = $redeemResult['new_balance'];
} else {
    $fresh = db()->fetch("SELECT wallet_balance FROM customers WHERE customer_id = :id", ['id' => $customer['customer_id']]);
    $walletBalance = (float) ($fresh['wallet_balance'] ?? 0);
}

$requested   = isset($input['amount']) ? (float) $input['amount'] : $walletBalance;
$applyAmount = max(0, round(min($requested, $walletBalance, $orderTotal), 2));

jsonResponse([
    'success'       => true,
    'apply_amount'  => $applyAmount,
    'wallet_balance' => $walletBalance,
    'new_total'     => round($orderTotal - $applyAmount, 2)
]);
