<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header('Access-Control-Allow-Headers: Content-Type');

$dataDir = __DIR__ . '/../data/reactions';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['postId']) || !isset($data['reaction'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        exit;
    }
    
    $postId = $data['postId'];
    $reaction = $data['reaction'];
    $visitorId = isset($data['visitorId']) ? $data['visitorId'] : md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
    
    $filename = $dataDir . '/post_' . $postId . '.json';
    
    // Load existing reactions
    $reactions = [];
    if (file_exists($filename)) {
        $reactions = json_decode(file_get_contents($filename), true) ?: [];
    }
    
    // Initialize reaction counts
    if (!isset($reactions['counts'])) {
        $reactions['counts'] = ['like' => 0, 'love' => 0, 'helpful' => 0];
    }
    
    // Initialize user reactions
    if (!isset($reactions['users'])) {
        $reactions['users'] = [];
    }
    
    // Check if user already reacted
    $userIndex = -1;
    foreach ($reactions['users'] as $index => $user) {
        if ($user['visitorId'] === $visitorId) {
            $userIndex = $index;
            break;
        }
    }
    
    if ($userIndex >= 0) {
        // User already reacted, update their reaction
        $oldReaction = $reactions['users'][$userIndex]['reaction'];
        if ($oldReaction !== $reaction) {
            // Change reaction - decrement old, increment new
            if (isset($reactions['counts'][$oldReaction]) && $reactions['counts'][$oldReaction] > 0) {
                $reactions['counts'][$oldReaction]--;
            }
            if (!isset($reactions['counts'][$reaction])) {
                $reactions['counts'][$reaction] = 0;
            }
            $reactions['counts'][$reaction]++;
            $reactions['users'][$userIndex]['reaction'] = $reaction;
        } else {
            // Same reaction, remove it (toggle off)
            if (isset($reactions['counts'][$reaction]) && $reactions['counts'][$reaction] > 0) {
                $reactions['counts'][$reaction]--;
            }
            unset($reactions['users'][$userIndex]);
            $reactions['users'] = array_values($reactions['users']);
        }
    } else {
        // New reaction
        if (!isset($reactions['counts'][$reaction])) {
            $reactions['counts'][$reaction] = 0;
        }
        $reactions['counts'][$reaction]++;
        $reactions['users'][] = [
            'visitorId' => $visitorId,
            'reaction' => $reaction,
            'timestamp' => time()
        ];
    }
    
    // Ensure all reaction types exist
    if (!isset($reactions['counts']['like'])) $reactions['counts']['like'] = 0;
    if (!isset($reactions['counts']['love'])) $reactions['counts']['love'] = 0;
    if (!isset($reactions['counts']['helpful'])) $reactions['counts']['helpful'] = 0;
    
    // Save reactions
    file_put_contents($filename, json_encode($reactions, JSON_PRETTY_PRINT));
    
    echo json_encode(['success' => true, 'counts' => $reactions['counts']]);
    
} else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Get reactions for a post
    if (!isset($_GET['postId']) || $_GET['postId'] === '') {
        http_response_code(400);
        echo json_encode(['error' => 'Missing postId']);
        exit;
    }
    $postId = $_GET['postId'];
    
    $filename = $dataDir . '/post_' . $postId . '.json';
    
    if (file_exists($filename)) {
        $reactions = json_decode(file_get_contents($filename), true);
        echo json_encode(['success' => true, 'counts' => $reactions['counts'] ?? []]);
    } else {
        echo json_encode(['success' => true, 'counts' => ['like' => 0, 'love' => 0, 'helpful' => 0]]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>
