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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $groupId = $_POST['groupId'];
    $newStatus = $_POST['newStatus'];
    
    // Get current status before updating
    $stmt = $pdo->prepare("SELECT pro_status, pro_expiration_date FROM wp_groups WHERE id = ?");
    $stmt->execute([$groupId]);
    $oldData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $upgradeDate = null;
    $expirationDate = null;
    
    if ($newStatus === 'Pro') {
        $upgradeDate = date('Y-m-d');
        $expirationDate = date('Y-m-d', strtotime('+1 year'));
    } elseif ($newStatus === 'Expired') {
        $expirationDate = date('Y-m-d');
    }
    
    $query = "UPDATE wp_groups SET pro_status = ?, pro_expiration_date = ? WHERE id = ?";
    $params = [$newStatus, $expirationDate, $groupId];
    
    if ($upgradeDate) {
        $query = "UPDATE wp_groups SET pro_status = ?, pro_upgrade_date = ?, pro_expiration_date = ? WHERE id = ?";
        $params = [$newStatus, $upgradeDate, $expirationDate, $groupId];
    }
    
    $stmt = $pdo->prepare($query);
    $result = $stmt->execute($params);
    
    if ($result) {
        // Log the change in history table
        $historyStmt = $pdo->prepare("INSERT INTO wp_pro_status_history (
            group_id, 
            old_status, 
            new_status, 
            old_expiration_date, 
            new_expiration_date, 
            changed_by, 
            changed_at
        ) VALUES (?, ?, ?, ?, ?, ?, NOW())");
        
        $historyStmt->execute([
            $groupId,
            $oldData['pro_status'],
            $newStatus,
            $oldData['pro_expiration_date'],
            $expirationDate,
            $_SESSION['front_user_id']
        ]);
        
        echo json_encode(['success' => true, 'expirationDate' => $expirationDate, 'upgradeDate' => $upgradeDate]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database update failed']);
    }
}