<?php
/**
 * ============================================================
 * AJAX: Apply Promo Code
 * ============================================================
 * Validates promo code and returns discount calculation
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be AJAX POST
if (!isAjax() || !isPost()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF
if (!csrf_validate()) {
    Response::csrfError();
}

// Load services
require_once APP_PATH . '/services/cart_service.php';
require_once APP_PATH . '/services/promo_service.php';

// Get promo code
$code = sanitize(post('code'));

if (empty($code)) {
    Response::error('প্রোমো কোড দিন');
}

// Get cart subtotal
$cartService = new CartService();
$cartTotals = $cartService->getTotals();

if ($cartService->isEmpty()) {
    Response::error('কার্ট খালি');
}

// Apply promo code
$result = PromoService::apply($code, $cartTotals['subtotal']);

if ($result['success']) {
    // Store in session for checkout
    $_SESSION['applied_promo'] = [
        'id' => $result['promo']['id'],
        'code' => $result['promo']['code'],
        'discount_amount' => $result['discount_amount']
    ];
    
    Response::success($result['message'], [
        'promo' => $result['promo'],
        'discount_amount' => $result['discount_amount'],
        'subtotal' => $result['subtotal'],
        'vat_amount' => $result['vat_amount'],
        'tax_amount' => $result['tax_amount'],
        'grand_total' => $result['grand_total']
    ]);
} else {
    // Clear any previously applied promo
    unset($_SESSION['applied_promo']);
    Response::error($result['message']);
}
