<?php

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

$userid = $_POST[ 'userid' ];
$postid = $_POST[ 'postid' ];
$text = $_POST[ 'text' ];
$time = $_POST[ 'time' ];
$key = $_POST[ 'key' ];

$security_key = decrypData($key);

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

if ($security_key == SECURITY_KEY_PLAIN) {
    $response = array();
    $con = dbConnect();

    // প্রথমে কমেন্ট ইনসার্ট করুন
    $sql = "INSERT INTO comment_table (userid, postid, text, time) 
            VALUES ('$userid', '$postid', '$text', '$time')";
            
    $result = mysqli_query($con, $sql);

    if ($result) {
        // কমেন্ট সফলভাবে ইনসার্ট হলে, এখন সেই পোস্টের মোট কমেন্ট সংখ্যা গণনা করুন
        $count_sql = "SELECT COUNT(*) as total_comments FROM comment_table WHERE postid = '$postid'";
        $count_result = mysqli_query($con, $count_sql);
        
        if ($count_result) {
            $count_row = mysqli_fetch_assoc($count_result);
            $response['status'] = 'success';
            $response['message'] = 'Successfully';
            $response['total_comments'] = (int)$count_row['total_comments'];
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Failed to count comments';
        }
    } else {
        $response['status'] = 'error';
        $response['message'] = 'Query Error: ' . mysqli_error($con);
    }

    mysqli_close($con);
    echo json_encode($response);
}

?>