<?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';

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);

$code = strtoupper(str_replace(['-', ' '], '', trim($input['code'] ?? '')));

if (empty($code) || strlen($code) < 8) {
    jsonResponse(['error' => 'Invalid gift card code'], 400);
}

// Find gift card
$giftCard = db()->fetch(
    "SELECT * FROM gift_cards WHERE code = :code AND is_active = 1",
    ['code' => $code]
);

if (!$giftCard) {
    jsonResponse(['error' => 'Gift card not found or already used'], 404);
}

if ($giftCard['current_balance'] <= 0) {
    jsonResponse(['error' => 'This gift card has no remaining balance'], 400);
}

if ($giftCard['expires_at'] && strtotime($giftCard['expires_at']) < time()) {
    jsonResponse(['error' => 'This gift card has expired'], 400);
}

$amount = $giftCard['current_balance'];

try {
    // Start transaction
    db()->query("START TRANSACTION");

    // Update gift card balance to 0
    db()->query(
        "UPDATE gift_cards SET current_balance = 0, is_active = 0, updated_at = NOW() WHERE gift_card_id = :id",
        ['id' => $giftCard['gift_card_id']]
    );
    
    // Log gift card transaction
    db()->insert('gift_card_transactions', [
        'gift_card_id' => $giftCard['gift_card_id'],
        'amount' => -$amount,
        'balance_after' => 0,
        'type' => 'redeem',
        'description' => 'Redeemed by customer: ' . $customer['email']
    ]);
    
    // Add to customer wallet
    $newWalletBalance = ($customer['wallet_balance'] ?? 0) + $amount;
    
    db()->query(
        "UPDATE customers SET wallet_balance = :balance, updated_at = NOW() WHERE customer_id = :id",
        ['balance' => $newWalletBalance, 'id' => $customer['customer_id']]
    );
    
    // Log wallet transaction
    db()->insert('wallet_transactions', [
        'transaction_id' => generateId('wt_'),
        'customer_id' => $customer['customer_id'],
        'amount' => $amount,
        'balance_after' => $newWalletBalance,
        'type' => 'gift_card',
        'description' => 'Gift card redeemed: ' . $code
    ]);
    
    db()->query("COMMIT");
    
    jsonResponse([
        'success' => true,
        'amount' => $amount,
        'new_balance' => $newWalletBalance,
        'message' => formatCurrency($amount) . ' has been added to your wallet!'
    ]);
    
} catch (Exception $e) {
    db()->query("ROLLBACK");
    jsonResponse(['error' => 'Failed to redeem gift card. Please try again.'], 500);
}
