<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/include_all.inc.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/api/pro_features.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SESSION['user_type'] === 'super') {
    $userId = $_POST['userId'];
    $newStatus = $_POST['newStatus'];
    
    // Get the user's group information
    $stmt = $pdo->prepare("SELECT u.group_id FROM wp_users u WHERE u.id = ?");
    $stmt->execute([$userId]);
    $groupId = $stmt->fetchColumn();
    
    // Check if user is in Demo group
    $stmt = $pdo->prepare("SELECT g.group_name FROM wp_users u JOIN wp_groups g ON u.group_id = g.id WHERE u.id = ?");
	$stmt->execute([$userId]);
	$groupName = $stmt->fetchColumn();

	if ($groupName === 'Demo') {
		echo json_encode(['success' => false, 'error' => 'Cannot change Pro status for Demo users']);
		exit;
	}
    
    // Apply Pro status change
    $query = "UPDATE wp_users SET pro_status = ? WHERE id = ?";
    $stmt = $pdo->prepare($query);
    $result = $stmt->execute([$newStatus, $userId]);
    
    // Add expiration date if upgrading to Pro
    if ($newStatus === 'Pro') {
        $expirationDate = date('Y-m-d', strtotime('+1 year'));
        $query = "UPDATE wp_users SET pro_expiration_date = ? WHERE id = ?";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$expirationDate, $userId]);
    }
    
    if ($result) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database update failed']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request or insufficient permissions']);
}