<?php
require_once 'config.php';
require_once 'discount_engine.php';
require_once 'plan_price_helper.php';
header('Content-Type: application/json; charset=utf-8');

$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$userId = (int)($input['user_id'] ?? 0);
$code = gemacc_normalize_discount_code($input['code'] ?? '');
$planId = (int)($input['plan_id'] ?? 0);
$paymentMethod = strtolower(trim((string)($input['payment_method'] ?? 'all')));

if (!$userId || !$code) {
    echo json_encode(['ok' => false, 'error' => 'اطلاعات ناقص'], JSON_UNESCAPED_UNICODE);
    exit;
}

$purchaseAmount = 0;
if ($planId > 0) {
    $stmt = $pdo->prepare("SELECT p.*, pc.service_type AS category_service_type, pc.months AS category_months FROM plans p LEFT JOIN plan_categories pc ON pc.id=p.category_id WHERE p.id = ? AND p.is_active=1");
    $stmt->execute([$planId]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    $purchaseAmount = $plan ? gemacc_plan_effective_sale_price($plan) : 0;
}

try {
    $res = gemacc_discount_preview($pdo, $userId, $code, $purchaseAmount, $planId, $paymentMethod);
    unset($res['discount']);
    if (empty($res['valid'])) { $res['message'] = 'کد تخفیف نداری توی جشنواره بعدی حتما واست ارسال میشه❤️'; }
    echo json_encode(['ok' => true, 'data' => $res], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    echo json_encode(['ok' => true, 'data' => ['valid' => false, 'message' => 'سیستم کد تخفیف فعال نیست']], JSON_UNESCAPED_UNICODE);
}
