=0 = capped. * The counter resets automatically when a trial starts or a paid subscription * activates (see ?action=start-trial and the Daraja callback handler). * * The subscription payload carries a `prompts_breakdown` (success / failed / * cancelled / pending) and a `prompts_used` total, both computed live from * the `transactions` table for every business owned by the account — so the * numbers match reality even for accounts created before the counter existed. */ require_once __DIR__ . '/config.php'; require_once __DIR__ . '/subconfig.php'; require_once __DIR__ . '/helpers.php'; require_once __DIR__ . '/db.php'; set_headers(); $action = $_GET['action'] ?? ''; $method = $_SERVER['REQUEST_METHOD']; // Extract Safaricom's real transaction time from raw_callback function extract_mpesa_paid_at($rawCallback) { if (empty($rawCallback)) return null; $raw = json_decode($rawCallback, true); if (!is_array($raw)) return null; $items = $raw['Body']['stkCallback']['CallbackMetadata']['Item'] ?? []; if (!is_array($items)) return null; foreach ($items as $item) { if (($item['Name'] ?? '') === 'TransactionDate' && !empty($item['Value'])) { $s = (string)$item['Value']; if (strlen($s) === 14 && ctype_digit($s)) { return substr($s, 0, 4) . '-' . substr($s, 4, 2) . '-' . substr($s, 6, 2) . ' ' . substr($s, 8, 2) . ':' . substr($s, 10, 2) . ':' . substr($s, 12, 2); } } } return null; } // ============================================================ // Helpers // ============================================================ function sub_effective_plan(array $acc): string { $now = time(); $plan = $acc['plan'] ?? 'trial'; if ($plan === 'trial') { if (!empty($acc['trial_ends_at']) && strtotime($acc['trial_ends_at']) >= $now) { return 'trial'; } return 'expired'; } if (!empty($acc['plan_expires_at']) && strtotime($acc['plan_expires_at']) >= $now) { return $plan; } return 'expired'; } function subscription_payload(PDO $pdo, array $acc): array { $eff = sub_effective_plan($acc); $stmt = $pdo->prepare(" SELECT * FROM subscriptions WHERE owner_id = ? AND status = 'active' ORDER BY ends_at DESC LIMIT 1 "); $stmt->execute([$acc['id']]); $active = $stmt->fetch() ?: null; $stmt = $pdo->prepare(" SELECT id, plan, period, amount, phone, mpesa_code, status, result_desc, created_at, updated_at FROM subscription_transactions WHERE owner_id = ? ORDER BY id DESC LIMIT 10 "); $stmt->execute([$acc['id']]); $txs = $stmt->fetchAll(); $trialEnds = $acc['trial_ends_at'] ?? null; $trialDaysLeft = null; if ($eff === 'trial' && $trialEnds) { $trialDaysLeft = max(0, (int)ceil((strtotime($trialEnds) - time()) / 86400)); } $cancelsAt = $acc['cancels_at'] ?? null; // ---- Prompt usage: total + breakdown + limit ---- // All three read from the transactions table so the numbers are always // consistent and reflect every prompt ever sent on the owner's businesses, // not just ones after the accounts.prompts_used counter was added. // ---- Prompt usage: total + breakdown + limit ---- $promptsBreakdown = [ 'success' => 0, 'failed' => 0, 'cancelled' => 0, 'pending' => 0, 'total' => 0, ]; $promptsUsed = 0; $promptsLimit = -1; try { $stmt = $pdo->prepare(" SELECT t.status, COUNT(*) AS c FROM transactions t JOIN businesses b ON b.id = t.business_id WHERE b.owner_id = ? GROUP BY t.status "); $stmt->execute([(int)$acc['id']]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { $s = strtolower((string)$row['status']); $c = (int)$row['c']; if (array_key_exists($s, $promptsBreakdown)) { $promptsBreakdown[$s] = $c; } $promptsBreakdown['total'] += $c; } $promptsUsed = $promptsBreakdown['total']; } catch (Throwable $e) { error_log('[subscription_payload] prompts count failed: ' . $e->getMessage()); $promptsUsed = (int)($acc['prompts_used'] ?? 0); } // Read the limit live from the plans table try { if ($acc['plan'] === 'trial') { $row = $pdo->query(" SELECT trial_prompt_limit FROM plans WHERE is_trial = 1 LIMIT 1 ")->fetch(PDO::FETCH_ASSOC); $promptsLimit = (int)($row['trial_prompt_limit'] ?? 0); } else { $stmt = $pdo->prepare(" SELECT prompt_limit FROM plans WHERE plan_key = ? AND is_active = 1 LIMIT 1 "); $stmt->execute([$acc['plan']]); $pl = $stmt->fetchColumn(); if ($pl !== false) $promptsLimit = (int)$pl; } } catch (Throwable $e) {} return [ 'plan' => $acc['plan'] ?? 'trial', 'effective_plan' => $eff, 'plan_expires_at' => $acc['plan_expires_at'] ?? null, 'cancels_at' => $cancelsAt, 'trial_ends_at' => $trialEnds, 'trial_days_left' => $trialDaysLeft, 'is_trial' => $eff === 'trial', 'is_expired' => $eff === 'expired', 'is_cancelling' => !empty($cancelsAt), 'prompts_used' => $promptsUsed, 'prompts_limit' => $promptsLimit, 'prompts_remaining' => $promptsLimit < 0 ? null : max(0, $promptsLimit - $promptsUsed), 'prompts_breakdown' => $promptsBreakdown, 'active_subscription' => $active, 'recent_transactions' => $txs, ]; } function sub_daraja_token() { // Reuse a cached token when possible — Safaricom tokens last ~1 hour. $cacheFile = sys_get_temp_dir() . '/daraja_token_' . md5(DARAJA_CONSUMER_KEY) . '.json'; if (is_readable($cacheFile)) { $cached = json_decode(file_get_contents($cacheFile), true); if (!empty($cached['token']) && !empty($cached['expires_at']) && $cached['expires_at'] > time() + 300) { return $cached['token']; } } $ch = curl_init(daraja_auth_url()); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Basic ' . base64_encode(DARAJA_CONSUMER_KEY . ':' . DARAJA_CONSUMER_SECRET)], CURLOPT_TIMEOUT => 15, ]); $body = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($code !== 200) { error_log("Daraja auth failed: $code $body"); return null; } $d = json_decode($body, true); $token = $d['access_token'] ?? null; if ($token) { @file_put_contents($cacheFile, json_encode([ 'token' => $token, 'expires_at' => time() + 3000, // token lives ~3600s, refresh at 50min ]), LOCK_EX); } return $token; } function sub_daraja_post($url, $token, $payload) { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . $token, 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode($payload), CURLOPT_TIMEOUT => 30, ]); $body = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $data = json_decode($body, true); if (!is_array($data)) return ['errorMessage' => "HTTP $code — invalid response"]; return $data; } // ============================================================ // AFFILIATE — award commission when a sub payment succeeds. // Rate is read LIVE from settings. NO FALLBACK. // Safe to call multiple times (UNIQUE on subscription_tx_id). // ============================================================ function award_affiliate_commission(PDO $pdo, int $txId, int $referredId, string $plan, string $period, float $amount): void { try { // 1. Is the payer a referred user? $stmt = $pdo->prepare(" SELECT referred_by_account_id, referred_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$referredId]); $payer = $stmt->fetch(); if (!$payer || empty($payer['referred_by_account_id']) || empty($payer['referred_at'])) { error_log("AFF: payer $referredId has no referrer (tx $txId)"); return; } // 2. Get the affiliate's commission window $stmt = $pdo->prepare(" SELECT id, affiliate_commission_months FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$payer['referred_by_account_id']]); $aff = $stmt->fetch(); if (!$aff) { error_log("AFF: referrer {$payer['referred_by_account_id']} not found (tx $txId)"); return; } $months = max(1, (int)$aff['affiliate_commission_months']); $refTime = strtotime($payer['referred_at']); $windowEnd = strtotime("+{$months} months", $refTime); if (time() > $windowEnd) { error_log("AFF: commission window closed for referred $referredId (tx $txId)"); return; } // 3. Read the LIVE rate from settings — NO FALLBACK $stmt = $pdo->prepare("SELECT `value` FROM settings WHERE `key` = 'affiliate_default_rate' LIMIT 1"); $stmt->execute(); $rateVal = $stmt->fetchColumn(); if ($rateVal === false || $rateVal === null || $rateVal === '') { error_log("AFF: settings.affiliate_default_rate is missing — cannot award commission (tx $txId)"); return; } $rate = (float)$rateVal; if ($rate <= 0 || $rate > 100) { error_log("AFF: invalid affiliate_default_rate '$rateVal' (tx $txId)"); return; } $commission = round($amount * $rate / 100, 2); if ($commission <= 0) { error_log("AFF: commission <= 0 for tx $txId (amount=$amount rate=$rate)"); return; } // 4. Insert the commission row (idempotent — UNIQUE on subscription_tx_id) $stmt = $pdo->prepare(" INSERT IGNORE INTO affiliate_commissions (affiliate_account_id, referred_account_id, subscription_tx_id, plan, period, gross_amount, commission_rate, commission_amount, status, earned_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'approved', NOW()) "); $stmt->execute([ $aff['id'], $referredId, $txId, $plan, $period, $amount, $rate, $commission, ]); $inserted = $stmt->rowCount() > 0; error_log("AFF: " . ($inserted ? 'awarded' : 'duplicate') . " KES $commission (rate {$rate}%) to account {$aff['id']} from tx $txId"); // 5. Notify the affiliate if ($inserted) { try { $pdo->prepare(" INSERT INTO notifications (user_type, user_id, title, message, type, link) VALUES ('owner', ?, 'Commission earned', ?, 'success', 'affiliate.html') ")->execute([ $aff['id'], 'You earned KES ' . number_format($commission, 2) . ' from a referral who subscribed to ' . ucfirst($plan) . '.', ]); } catch (Exception $e) {} } } catch (Throwable $e) { error_log('AFF ERROR: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine()); } } // ============================================================ // PROMPTS — quota check + increment // Reads the limit live from the `plans` table, which the admin // edits on the admin Plans page. // -1 = unlimited (never blocks, still counts) // >=0 = capped (blocks when used >= limit) // // NOTE: this uses accounts.prompts_used for the *enforcement* check // (fast, atomic), while the display layer counts from transactions. // Both are kept in sync because every prompt increments the column. // ============================================================ function sub_check_and_increment_prompt(PDO $pdo, int $accountId): array { $stmt = $pdo->prepare(" SELECT id, plan, trial_ends_at, plan_expires_at, prompts_used, prompts_reset_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$accountId]); $acc = $stmt->fetch(PDO::FETCH_ASSOC); if (!$acc) { return ['ok' => false, 'reason' => 'account_not_found']; } $planKey = $acc['plan']; $limit = -1; $expires = null; if ($planKey === 'trial') { $row = $pdo->query(" SELECT trial_prompt_limit FROM plans WHERE is_trial = 1 LIMIT 1 ")->fetch(PDO::FETCH_ASSOC); $limit = (int)($row['trial_prompt_limit'] ?? 0); $expires = $acc['trial_ends_at']; } else { $stmt = $pdo->prepare(" SELECT prompt_limit FROM plans WHERE plan_key = ? AND is_active = 1 LIMIT 1 "); $stmt->execute([$planKey]); $row = $stmt->fetch(PDO::FETCH_ASSOC); if (!$row) { return ['ok' => false, 'reason' => 'no_active_plan']; } $limit = (int)$row['prompt_limit']; $expires = $acc['plan_expires_at']; } if ($expires && strtotime($expires) < time()) { return ['ok' => false, 'reason' => 'expired']; } // Initialise the counter on the very first prompt after register if ($acc['prompts_reset_at'] === null) { // Count existing transactions for this cycle so we don't reset to 0 // mid-way through a trial for accounts that pre-date the counter. $existing = 0; try { $stmt = $pdo->prepare(" SELECT COUNT(*) FROM transactions t JOIN businesses b ON b.id = t.business_id WHERE b.owner_id = ? "); $stmt->execute([$accountId]); $existing = (int)$stmt->fetchColumn(); } catch (Throwable $e) {} $pdo->prepare(" UPDATE accounts SET prompts_used = ?, prompts_reset_at = NOW() WHERE id = ? ")->execute([$existing, $accountId]); $acc['prompts_used'] = $existing; } $used = (int)$acc['prompts_used']; if ($limit === -1) { $pdo->prepare(" UPDATE accounts SET prompts_used = prompts_used + 1 WHERE id = ? ")->execute([$accountId]); return ['ok' => true, 'used' => $used + 1, 'limit' => -1]; } if ($used >= $limit) { return [ 'ok' => false, 'reason' => 'quota_exceeded', 'used' => $used, 'limit' => $limit, ]; } $pdo->prepare(" UPDATE accounts SET prompts_used = prompts_used + 1 WHERE id = ? ")->execute([$accountId]); return ['ok' => true, 'used' => $used + 1, 'limit' => $limit]; } // ============================================================ // ME // ============================================================ if ($action === 'me' && $method === 'GET') { $payload = require_auth(); $pdo = db(); $stmt = $pdo->prepare(" SELECT id, full_name, email, phone, is_active, plan, plan_expires_at, cancels_at, trial_ends_at, prompts_used, prompts_reset_at, last_login_at, created_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$payload['sub']]); $acc = $stmt->fetch(); if (!$acc) fail('Account not found', 404); ok([ 'user' => [ 'id' => (int)$acc['id'], 'name' => $acc['full_name'], 'email' => $acc['email'], 'phone' => $acc['phone'], ], 'subscription' => subscription_payload($pdo, $acc), 'pricing' => sub_pricing(), ]); } // ============================================================ // PLANS — public, DB-driven // ============================================================ if ($action === 'plans' && $method === 'GET') { $pdo = db(); $rows = $pdo->query(" SELECT plan_key, is_trial, name, tagline, price_monthly, price_sixmonth, price_yearly, max_businesses, max_staff, prompt_limit, trial_days, trial_prompt_limit, features, is_popular, sort_order FROM plans WHERE is_active = 1 ORDER BY sort_order ASC, id ASC ")->fetchAll(); $plans = []; $pricing = []; foreach ($rows as $r) { $r['is_trial'] = (bool)(int)$r['is_trial']; $r['is_popular'] = (bool)(int)$r['is_popular']; $r['max_businesses'] = (int)$r['max_businesses']; $r['max_staff'] = (int)$r['max_staff']; $r['prompt_limit'] = (int)$r['prompt_limit']; $r['trial_days'] = (int)$r['trial_days']; $r['trial_prompt_limit'] = (int)$r['trial_prompt_limit']; $r['features'] = $r['features'] ? json_decode($r['features'], true) : []; $plans[] = $r; if (!$r['is_trial']) { $pricing[$r['plan_key']] = [ 'monthly' => (float)$r['price_monthly'], 'sixmonth' => (float)$r['price_sixmonth'], 'yearly' => (float)$r['price_yearly'], ]; } } ok(['plans' => $plans, 'pricing' => $pricing]); } // ============================================================ // START TRIAL // ============================================================ if ($action === 'start-trial' && $method === 'POST') { $payload = require_auth(); $pdo = db(); $trial = sub_get_trial_plan(); if (!$trial) { fail('Free trial is currently unavailable. Please choose a paid plan.', 400); } $trialDays = max(1, (int)$trial['trial_days']); $promptCap = max(0, (int)$trial['trial_prompt_limit']); $stmt = $pdo->prepare(" SELECT id, plan, plan_expires_at, trial_ends_at, created_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$payload['sub']]); $acc = $stmt->fetch(); if (!$acc) fail('Account not found', 404); $now = time(); if (in_array($acc['plan'], ['starter','growing','enterprise'], true) && !empty($acc['plan_expires_at']) && strtotime($acc['plan_expires_at']) > $now) { ok([ 'message' => 'You already have an active paid plan.', 'subscription' => subscription_payload($pdo, $acc), ]); exit; } if ($acc['plan'] === 'trial' && !empty($acc['trial_ends_at']) && strtotime($acc['trial_ends_at']) > $now) { ok([ 'message' => 'Your trial is already active.', 'subscription' => subscription_payload($pdo, $acc), ]); exit; } if (!empty($acc['trial_ends_at'])) { fail('You have already used your free trial. Please choose a paid plan.', 409); } $trialEnds = date('Y-m-d H:i:s', $now + $trialDays * 86400); $pdo->prepare(" UPDATE accounts SET plan = 'trial', trial_ends_at = ?, plan_expires_at = NULL, cancels_at = NULL, prompts_used = 0, prompts_reset_at = NOW() WHERE id = ? ")->execute([$trialEnds, $payload['sub']]); try { $pdo->prepare(" INSERT INTO audit_logs (actor_type, actor_id, action, details, ip_address) VALUES ('owner', ?, 'start_trial', ?, ?) ")->execute([ $payload['sub'], json_encode(['days' => $trialDays, 'prompt_limit' => $promptCap]), $_SERVER['REMOTE_ADDR'] ?? null, ]); } catch (Exception $e) {} $stmt = $pdo->prepare(" SELECT id, full_name, email, phone, is_active, plan, plan_expires_at, cancels_at, trial_ends_at, prompts_used, prompts_reset_at, last_login_at, created_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$payload['sub']]); $fresh = $stmt->fetch(); ok([ 'message' => 'Trial activated', 'subscription' => subscription_payload($pdo, $fresh), 'trial' => [ 'days' => $trialDays, 'prompt_limit' => $promptCap, 'ends_at' => $trialEnds, ], ]); } // ============================================================ // CHECKOUT // ============================================================ if ($action === 'checkout' && $method === 'POST') { $payload = require_auth(); $pdo = db(); $data = body(); $plan = strtolower(clean($data['plan'] ?? '')); $period = strtolower(clean($data['period'] ?? 'monthly')); $phone = clean($data['phone'] ?? ''); if (!sub_validate_period($period)) { fail('Invalid billing period.', 400, 'period'); } $stmt = $pdo->prepare(" SELECT * FROM plans WHERE plan_key = ? AND is_active = 1 AND is_trial = 0 LIMIT 1 "); $stmt->execute([$plan]); $planRow = $stmt->fetch(); if (!$planRow) fail('Unknown or inactive plan.', 400, 'plan'); $priceKey = 'price_' . $period; $amount = (float)$planRow[$priceKey]; if ($amount < 1) fail('Amount must be at least KES 1'); $stmt = $pdo->prepare("SELECT phone FROM accounts WHERE id = ? LIMIT 1"); $stmt->execute([$payload['sub']]); $accRow = $stmt->fetch(); if ($phone === '' && !empty($accRow['phone'])) $phone = $accRow['phone']; if ($phone === '') fail('Phone number is required.', 400, 'phone'); $phone = preg_replace('/\D/', '', $phone); if (strlen($phone) === 10 && $phone[0] === '0') $phone = '254' . substr($phone, 1); elseif (strlen($phone) === 9) $phone = '254' . $phone; if (!preg_match('/^254(7|1)\d{8}$/', $phone)) fail('Invalid Kenyan phone number.', 400, 'phone'); $window = (int)SUB_DUPLICATE_WINDOW_SECONDS; $stmt = $pdo->prepare(" SELECT id FROM subscription_transactions WHERE owner_id = ? AND status = 'pending' AND created_at >= (NOW() - INTERVAL {$window} SECOND) ORDER BY id DESC LIMIT 1 "); $stmt->execute([$payload['sub']]); if ($stmt->fetch()) fail('A payment prompt is already in progress.', 429); $token = sub_daraja_token(); if (!$token) fail('Could not authenticate with Safaricom.', 502); $timestamp = date('YmdHis'); $password = base64_encode(SUB_SHORTCODE . SUB_PASSKEY . $timestamp); $stkPayload = [ 'BusinessShortCode' => SUB_SHORTCODE, 'Password' => $password, 'Timestamp' => $timestamp, 'TransactionType' => SUB_TRANSACTION_TYPE, 'Amount' => (int)round($amount), 'PartyA' => $phone, 'PartyB' => SUB_SHORTCODE, 'PhoneNumber' => $phone, 'CallBackURL' => SUB_CALLBACK_URL, 'AccountReference' => 'Prompter ' . $plan, 'TransactionDesc' => substr('Prompter ' . ucfirst($plan) . ' plan', 0, 13), ]; $response = sub_daraja_post(daraja_stk_url(), $token, $stkPayload); if (!$response || empty($response['CheckoutRequestID'])) { $err = $response['errorMessage'] ?? $response['ResponseDescription'] ?? 'No response'; fail('Safaricom error: ' . $err, 502); } $stmt = $pdo->prepare(" INSERT INTO subscription_transactions (owner_id, plan, period, amount, phone, status, checkout_request_id, merchant_request_id) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?) "); $stmt->execute([ $payload['sub'], $plan, $period, $amount, $phone, $response['CheckoutRequestID'], $response['MerchantRequestID'] ?? null, ]); $txId = (int)$pdo->lastInsertId(); ok([ 'message' => 'Prompt sent to ' . $phone, 'transaction_id' => $txId, 'checkout_request_id' => $response['CheckoutRequestID'], 'plan' => $plan, 'period' => $period, 'amount' => $amount, 'customer_message' => $response['CustomerMessage'] ?? null, ]); } // ============================================================ // STATUS // ============================================================ if ($action === 'status' && $method === 'GET') { $payload = require_auth(); $pdo = db(); $txId = (int)($_GET['id'] ?? 0); if ($txId <= 0) fail('Missing transaction id'); $stmt = $pdo->prepare(" SELECT * FROM subscription_transactions WHERE id = ? AND owner_id = ? LIMIT 1 "); $stmt->execute([$txId, $payload['sub']]); $tx = $stmt->fetch(); if (!$tx) fail('Transaction not found', 404); $stmt = $pdo->prepare(" SELECT id, full_name, email, phone, is_active, plan, plan_expires_at, cancels_at, trial_ends_at, prompts_used, prompts_reset_at, last_login_at, created_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$payload['sub']]); $acc = $stmt->fetch(); $planDates = null; if (!empty($tx['subscription_id'])) { $stmt = $pdo->prepare(" SELECT starts_at, ends_at, plan, period FROM subscriptions WHERE id = ? LIMIT 1 "); $stmt->execute([$tx['subscription_id']]); $row = $stmt->fetch(); if ($row && !empty($row['starts_at']) && !empty($row['ends_at'])) { $planDates = [ 'starts_at' => $row['starts_at'], 'ends_at' => $row['ends_at'], 'plan' => $row['plan'], 'period' => $row['period'], ]; } } $tx['mpesa_paid_at'] = extract_mpesa_paid_at($tx['raw_callback'] ?? null); unset($tx['raw_callback']); ok([ 'transaction' => $tx, 'subscription' => subscription_payload($pdo, $acc), 'plan_dates' => $planDates, ]); } // ============================================================ // CANCEL // ============================================================ if ($action === 'cancel' && $method === 'POST') { $payload = require_auth(); $pdo = db(); $stmt = $pdo->prepare(" SELECT id, plan, plan_expires_at, trial_ends_at, cancels_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$payload['sub']]); $acc = $stmt->fetch(); if (!$acc) fail('Account not found', 404); if ($acc['plan'] === 'trial') { fail('You cannot cancel a free trial. Just let it expire or upgrade to a paid plan.', 400); } $expiry = $acc['plan_expires_at'] ?? null; if (!$expiry || strtotime($expiry) <= time()) { fail('You do not have an active paid subscription to cancel.', 400); } if (!empty($acc['cancels_at'])) { fail('Your subscription is already scheduled for cancellation.', 409); } $pdo->prepare("UPDATE accounts SET cancels_at = plan_expires_at WHERE id = ?") ->execute([$payload['sub']]); $pdo->prepare(" UPDATE subscriptions SET cancels_at = ends_at WHERE owner_id = ? AND status = 'active' ")->execute([$payload['sub']]); try { $pdo->prepare(" INSERT INTO audit_logs (actor_type, actor_id, action, ip_address) VALUES ('owner', ?, 'subscription_cancel_requested', ?) ")->execute([$payload['sub'], $_SERVER['REMOTE_ADDR'] ?? null]); } catch (Exception $e) {} ok([ 'message' => 'Subscription will end on ' . date('d M Y', strtotime($expiry)) . '.', 'ends_at' => $expiry, ]); } // ============================================================ // RESUME // ============================================================ if ($action === 'resume' && $method === 'POST') { $payload = require_auth(); $pdo = db(); $stmt = $pdo->prepare(" SELECT id, plan, plan_expires_at, cancels_at FROM accounts WHERE id = ? LIMIT 1 "); $stmt->execute([$payload['sub']]); $acc = $stmt->fetch(); if (!$acc) fail('Account not found', 404); if (empty($acc['cancels_at'])) { fail('This subscription is not scheduled for cancellation.', 400); } $pdo->prepare("UPDATE accounts SET cancels_at = NULL WHERE id = ?") ->execute([$payload['sub']]); $pdo->prepare(" UPDATE subscriptions SET cancels_at = NULL WHERE owner_id = ? AND status = 'active' ")->execute([$payload['sub']]); try { $pdo->prepare(" INSERT INTO audit_logs (actor_type, actor_id, action, ip_address) VALUES ('owner', ?, 'subscription_cancel_resumed', ?) ")->execute([$payload['sub'], $_SERVER['REMOTE_ADDR'] ?? null]); } catch (Exception $e) {} ok(['message' => 'Cancellation withdrawn.']); } fail('Unknown action: ' . $action, 404);