<?php

include_once __DIR__ . '/../secrets.php';

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

// Receive RAW JSON
$json = file_get_contents('php://input');
$data = json_decode($json, true);

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

$security_key = decrypData($key);

if ($security_key === false) {
    echo json_encode(['error' => 'Invalid encryption data']);
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();
    $profileurl = 'https://app.bpluspro.xyz/social/';

    // First, get all comments for this post
    $sql = "SELECT id, userid, postid, text, time 
            FROM comment_table 
            WHERE postid = '$postid'
            ORDER BY id DESC";
    
    $result = mysqli_query($con, $sql);

    if (!$result) {
        echo json_encode(['error' => 'Database query failed: ' . mysqli_error($con)]);
        exit;
    }

    $comments = [];

    while ($row = mysqli_fetch_assoc($result)) {
        $userid = $row['userid'];
        $user_id_length = strlen($userid);
        
        $name = '';
        $image = '';
        $bpay = '';
        
        // Check userid length and fetch from appropriate table
        if ($user_id_length == 8) {
            // Fetch from signup table
            $userSql = "SELECT name, image, bpay FROM signup WHERE userid = '$userid'";
            $userResult = mysqli_query($con, $userSql);
            
            if ($userRow = mysqli_fetch_assoc($userResult)) {
                $name = $userRow['name'] ?? '';
                $image = $userRow['image'] ?? '';
                $bpay = $userRow['bpay'] ?? '';
            }
        } 
        elseif ($user_id_length == 9) {
            // Fetch from page_table
            // Note: Adjust column names if different in your page_table
            $pageSql = "SELECT name, image, bpay FROM page_table WHERE userid = '$userid'";
            $pageResult = mysqli_query($con, $pageSql);
            
            if ($pageRow = mysqli_fetch_assoc($pageResult)) {
                $name = $pageRow['name'] ?? '';
                $image = $pageRow['image'] ?? '';
                $bpay = $pageRow['bpay'] ?? '';
            }
        }

        $comments[] = [
            'id'      => $row['id'],
            'userid'  => $userid,
            'postid'  => $row['postid'],
            'text'    => $row['text'],
            'time'    => $row['time'],
            'name'    => $name,
            'profile' => $profileurl . $image,
            'bpay'    => $bpay
        ];
    }

    echo json_encode(['comments' => $comments], JSON_UNESCAPED_SLASHES);
}
?>