<?php
/**
 * Coupon API - AJAX Endpoints
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';

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

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'apply':
        handle_apply_coupon();
        break;
    
    case 'remove':
        handle_remove_coupon();
        break;
    
    case 'validate':
        handle_validate_coupon();
        break;
    
    default:
        json_response(['success' => false, 'message' => 'Invalid action']);
}

function handle_apply_coupon() {
    global $pdo;
    
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        json_response(['success' => false, 'message' => 'Invalid request']);
    }
    
    $code = sanitize(strtoupper($_POST['code'] ?? ''));
    
    if (empty($code)) {
        json_response(['success' => false, 'message' => 'Please enter a coupon code']);
    }
    
    // Get cart total
    $cart_total = get_cart_total();
    
    if ($cart_total <= 0) {
        json_response(['success' => false, 'message' => 'Your cart is empty']);
    }
    
    // Validate coupon
    $result = validate_coupon($code, $cart_total);
    
    if (!$result['valid']) {
        json_response(['success' => false, 'message' => $result['message']]);
    }
    
    $coupon = $result['coupon'];
    $discount = calculate_coupon_discount($coupon, $cart_total);
    
    // Store coupon in session
    $_SESSION['applied_coupon'] = $code;
    
    json_response([
        'success' => true,
        'message' => 'Coupon applied successfully!',
        'coupon' => [
            'code' => $coupon['code'],
            'discount_type' => $coupon['discount_type'],
            'discount_value' => $coupon['discount_value']
        ],
        'discount' => $discount,
        'discount_formatted' => format_price($discount),
        'new_total' => $cart_total - $discount,
        'new_total_formatted' => format_price($cart_total - $discount)
    ]);
}

function handle_remove_coupon() {
    global $pdo;
    
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        json_response(['success' => false, 'message' => 'Invalid request']);
    }
    
    unset($_SESSION['applied_coupon']);
    
    $cart_total = get_cart_total();
    
    json_response([
        'success' => true,
        'message' => 'Coupon removed',
        'cart_total' => $cart_total,
        'cart_total_formatted' => format_price($cart_total)
    ]);
}

function handle_validate_coupon() {
    global $pdo;
    
    $code = sanitize(strtoupper($_GET['code'] ?? ''));
    $cart_total = (float)($_GET['cart_total'] ?? get_cart_total());
    
    if (empty($code)) {
        json_response(['success' => false, 'message' => 'Please enter a coupon code']);
    }
    
    $result = validate_coupon($code, $cart_total);
    
    if (!$result['valid']) {
        json_response(['success' => false, 'message' => $result['message']]);
    }
    
    $coupon = $result['coupon'];
    $discount = calculate_coupon_discount($coupon, $cart_total);
    
    json_response([
        'success' => true,
        'coupon' => [
            'code' => $coupon['code'],
            'name' => $coupon['name'],
            'discount_type' => $coupon['discount_type'],
            'discount_value' => $coupon['discount_value']
        ],
        'discount' => $discount,
        'discount_formatted' => format_price($discount),
        'new_total' => $cart_total - $discount,
        'new_total_formatted' => format_price($cart_total - $discount)
    ]);
}
