<?php

include_once __DIR__ . '/../secrets.php';
header('Content-Type: application/json; charset=utf-8');
include '../db_connect.php';

// ============================
// GET JSON DATA FROM POST
// ============================
$json = file_get_contents('php://input');
$data = json_decode($json, true);

if (!$data) {
    echo json_encode(['error' => 'Invalid input']);
    exit;
}

$key = $data['key'] ?? null;
$postid = $data['postid'] ?? null;

if (!$key || !$postid) {
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

// ============================
// DECRYPT SECURITY KEY
// ============================
$security_key = decrypData($key);
if ($security_key === false || $security_key != SECURITY_KEY_PLAIN) {
    echo json_encode(['error' => 'Invalid encryption data']);
    exit;
}

// ============================
// DATABASE CONNECTION
// ============================
$con = dbConnect();
if (!$con) {
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

$postid = mysqli_real_escape_string($con, $postid);

// ============================
// GET REACTION COUNTS
// ============================
$reactionList = [];
$stmt = $con->prepare("SELECT reaction_type, COUNT(*) AS total FROM post_reactions WHERE post_id = ? GROUP BY reaction_type");
$stmt->bind_param("s", $postid);
$stmt->execute();
$result = $stmt->get_result();
while ($r = $result->fetch_assoc()) {
    $reactionList[] = [
        'reaction' => $r['reaction_type'],
        'count' => (int)$r['total']
    ];
}
$stmt->close();

// ============================
// GET USERS WITH REACTIONS
// ============================
$url = 'https://app.bpluspro.xyz/social/';
$userList = [];

// First, get all reactions for the post
$stmt = $con->prepare("SELECT user_id, reaction_type FROM post_reactions WHERE post_id = ?");
$stmt->bind_param("s", $postid);
$stmt->execute();
$result = $stmt->get_result();

while ($reaction = $result->fetch_assoc()) {
    $user_id = $reaction['user_id'];
    $reaction_type = $reaction['reaction_type'];
    
    // Check the length of user_id
    $user_id_length = strlen($user_id);
    
    if ($user_id_length == 8) {
        // Get user info from signup table for 8-digit IDs
        $userStmt = $con->prepare("SELECT name, image, bpay FROM signup WHERE userid = ?");
        $userStmt->bind_param("s", $user_id);
        $userStmt->execute();
        $userResult = $userStmt->get_result();
        
        if ($user = $userResult->fetch_assoc()) {
            $userList[] = [
                'userid' => $user_id,
                'name' => $user['name'] ?? '',
                'image' => !empty($user['image']) ? $url . $user['image'] : '',
                'bpay' => $user['bpay'] ?? '',
                'reaction' => $reaction_type,
                'type' => 'user' // Optional: to identify user type
            ];
        }
        $userStmt->close();
    } 
    elseif ($user_id_length == 9) {
        // Get page info from page_table for 9-digit IDs
        $pageStmt = $con->prepare("SELECT name, image, bpay FROM page_table WHERE userid = ?");
        $pageStmt->bind_param("s", $user_id);
        $pageStmt->execute();
        $pageResult = $pageStmt->get_result();
        
        if ($page = $pageResult->fetch_assoc()) {
            $userList[] = [
                'userid' => $user_id,
                'name' => $page['name'] ?? '',
                'image' => !empty($page['image']) ? $url . $page['image'] : '',
                'bpay' => $page['bpay'] ?? '',
                'reaction' => $reaction_type,
                'type' => 'page' // Optional: to identify user type
            ];
        }
        $pageStmt->close();
    }
}
$stmt->close();
$con->close();

// ============================
// SEND JSON RESPONSE
// ============================
$response = [
    'reactions' => $reactionList,
    'users' => $userList
];

echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
?>