<?php
/**
 * POST /api/admin/subscriptions_update.php
 * Admin-only. Body (JSON): { user_id, subscription_status?, trial_ends_at?, subscription_notes? }
 * Manual override until real billing exists - e.g. extend a trial, or mark
 * someone active once they've paid outside the platform.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
require_login();
require_role(['admin']);

$input = get_json_input();
$userId = (int) ($input['user_id'] ?? 0);
if ($userId <= 0) {
    send_error('A valid user_id is required.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT user_id FROM business_profiles WHERE user_id = ?');
$stmt->execute([$userId]);
if (!$stmt->fetch()) {
    send_error('Business profile not found.', 404);
}

$set = [];
$params = [];

if (array_key_exists('subscription_status', $input)) {
    if (!in_array($input['subscription_status'], ['trial', 'active', 'expired', 'cancelled'], true)) {
        send_error('Invalid subscription_status.', 422);
    }
    $set[] = 'subscription_status = ?';
    $params[] = $input['subscription_status'];
}
if (array_key_exists('trial_ends_at', $input)) {
    $val = trim((string) $input['trial_ends_at']);
    if ($val !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $val)) {
        send_error('trial_ends_at must be in YYYY-MM-DD format.', 422);
    }
    $set[] = 'trial_ends_at = ?';
    $params[] = $val ?: null;
}
if (array_key_exists('subscription_notes', $input)) {
    $set[] = 'subscription_notes = ?';
    $params[] = trim($input['subscription_notes']) ?: null;
}

if (!$set) {
    send_error('No fields to update.', 422);
}

$params[] = $userId;
$stmt = $pdo->prepare('UPDATE business_profiles SET ' . implode(', ', $set) . ' WHERE user_id = ?');
$stmt->execute($params);

send_json(true, 'Subscription updated.');
