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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['history_id'])) {
    $historyId = $_POST['history_id'];
    
    $stmt = $pdo->prepare("SELECT * FROM wp_pro_status_history WHERE id = ?");
    $stmt->execute([$historyId]);
    $historyEntry = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($historyEntry) {
        $stmt = $pdo->prepare("
            UPDATE wp_groups 
            SET pro_status = ?, pro_expiration_date = ? 
            WHERE id = ?
        ");
        $success = $stmt->execute([
            $historyEntry['old_status'],
            $historyEntry['old_expiration_date'],
            $historyEntry['group_id']
        ]);
        
        if ($success) {
            // Log this reversion
            $stmt = $pdo->prepare("
                INSERT INTO wp_pro_status_history 
                (group_id, old_status, new_status, old_expiration_date, new_expiration_date, changed_by, notes)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $historyEntry['group_id'],
                $historyEntry['new_status'],
                $historyEntry['old_status'],
                $historyEntry['new_expiration_date'],
                $historyEntry['old_expiration_date'],
                $_SESSION['front_user_id'],
                'Reverted to previous state'
            ]);
            
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Update failed']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'History entry not found']);
    }
}