<?php
// ─── Coupon Validation ───────────────────────────────────────────────────────
// Single source of truth for coupon rules — used by both the checkout preview
// (orders.php@coupon) and actual order creation (orders.php@checkout), so the
// two can never disagree. No hardcoded codes/discounts anywhere; everything
// comes from h_coupon / h_coupon_usage.
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
    header('HTTP/1.0 403 Forbidden', true, 403);
    exit;
}

function validate_coupon($code, $pid, $price, $uid) {
    global $conn;
    $codeSafe = mysqli_real_escape_string($conn, strtoupper(trim($code)));
    if ($codeSafe === '') return ['ok' => false, 'message' => 'Please enter a coupon code.'];

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM h_coupon WHERE code='$codeSafe' AND status='1'"));
    if (!$row) return ['ok' => false, 'message' => 'Invalid coupon code.'];

    $today = date('Y-m-d');
    if ($row['start_date'] && $today < $row['start_date']) return ['ok' => false, 'message' => 'This coupon is not active yet.'];
    if ($row['end_date'] && $today > $row['end_date']) return ['ok' => false, 'message' => 'This coupon has expired.'];

    if (!empty($row['applicable_products'])) {
        $ids = array_map('trim', explode(',', $row['applicable_products']));
        if (!in_array((string)$pid, $ids, true)) return ['ok' => false, 'message' => 'This coupon does not apply to the selected plan.'];
    }

    if ((float)$price < (float)$row['min_order_amount']) {
        return ['ok' => false, 'message' => 'This coupon requires a minimum order of $' . number_format((float)$row['min_order_amount'], 2) . '.'];
    }

    if ($row['max_uses'] !== null) {
        $used = (int) mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) c FROM h_coupon_usage WHERE coupon_id='{$row['id']}'"))['c'];
        if ($used >= (int)$row['max_uses']) return ['ok' => false, 'message' => 'This coupon has reached its usage limit.'];
    }

    if ($row['per_user_limit'] !== null && $uid) {
        $usedByUser = (int) mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) c FROM h_coupon_usage WHERE coupon_id='{$row['id']}' AND uid='$uid'"))['c'];
        if ($usedByUser >= (int)$row['per_user_limit']) return ['ok' => false, 'message' => 'You have already used this coupon the maximum number of times.'];
    }

    $discounted = ($row['type'] === 'fixed')
        ? round(max(0, (float)$price - (float)$row['value']), 2)
        : round((float)$price * (1 - (float)$row['value'] / 100), 2);

    $label = $row['type'] === 'percent'
        ? number_format((float)$row['value'], 0) . '% off'
        : '$' . number_format((float)$row['value'], 2) . ' off';

    return [
        'ok' => true,
        'coupon_id' => $row['id'],
        'discounted_price' => $discounted,
        'message' => "Coupon applied: $label",
    ];
}

function record_coupon_usage($couponId, $uid, $oid) {
    global $conn, $now;
    mysqli_query($conn, "INSERT INTO h_coupon_usage (coupon_id, uid, oid, date) VALUES ('$couponId','$uid','$oid','$now')");
}
