<?php
header('Content-Type: application/json');
require_once 'auth/session.php';
require_once 'includes/permissions.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
    $data = $_POST;
}

$message_id = $data['message_id'] ?? 0;
$option_index = $data['option_index'] ?? 0;
$user_id = $_SESSION['user_id'];

try {
    $stmt = db()->prepare("SELECT metadata, channel_id FROM messages WHERE id = ?");
    $stmt->execute([$message_id]);
    $msg = $stmt->fetch();

    if (!$msg) {
        echo json_encode(['success' => false, 'error' => 'Sondage non trouvé']);
        exit;
    }

    $meta = json_decode($msg['metadata'], true);
    if (!$meta || empty($meta['is_poll'])) {
        echo json_encode(['success' => false, 'error' => 'Ce message n\'est pas un sondage']);
        exit;
    }

    // Check expiration
    if (!empty($meta['poll_end_date']) && strtotime($meta['poll_end_date']) < time()) {
        echo json_encode(['success' => false, 'error' => 'Ce sondage est terminé']);
        exit;
    }

    // Check permissions
    if (!Permissions::canViewChannel($user_id, $msg['channel_id'])) {
        echo json_encode(['success' => false, 'error' => 'Vous n\'avez pas la permission de voter']);
        exit;
    }

    $choice_type = $meta['poll_choice_type'] ?? 'single';

    if ($choice_type === 'single') {
        // Remove previous votes from this user for this poll
        $stmt = db()->prepare("DELETE FROM poll_votes WHERE message_id = ? AND user_id = ?");
        $stmt->execute([$message_id, $user_id]);
        
        // Add new vote
        $stmt = db()->prepare("INSERT INTO poll_votes (message_id, user_id, option_index) VALUES (?, ?, ?)");
        $stmt->execute([$message_id, $user_id, $option_index]);
    } else {
        // Multiple choice: toggle vote
        $stmt = db()->prepare("SELECT id FROM poll_votes WHERE message_id = ? AND user_id = ? AND option_index = ?");
        $stmt->execute([$message_id, $user_id, $option_index]);
        if ($stmt->fetch()) {
            $stmt = db()->prepare("DELETE FROM poll_votes WHERE message_id = ? AND user_id = ? AND option_index = ?");
            $stmt->execute([$message_id, $user_id, $option_index]);
        } else {
            $stmt = db()->prepare("INSERT INTO poll_votes (message_id, user_id, option_index) VALUES (?, ?, ?)");
            $stmt->execute([$message_id, $user_id, $option_index]);
        }
    }

    // Fetch updated votes
    $stmt = db()->prepare("SELECT option_index, COUNT(*) as vote_count, GROUP_CONCAT(user_id) as user_ids FROM poll_votes WHERE message_id = ? GROUP BY option_index");
    $stmt->execute([$message_id]);
    $votes = $stmt->fetchAll();

    echo json_encode(['success' => true, 'votes' => $votes]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
