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

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

// POST বা GET উভয়ই সাপোর্ট করবে
$cid = isset($_POST['cid']) ? $_POST['cid'] : (isset($_GET['cid']) ? $_GET['cid'] : '');
$key = isset($_POST['key']) ? $_POST['key'] : (isset($_GET['key']) ? $_GET['key'] : '');

$security_key = decrypData($key);

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

if ($security_key == SECURITY_KEY_PLAIN && strlen($cid) > 0) {
    $con = dbConnect();
    

    // SQL Injection প্রতিরোধ
    $cid = $con->real_escape_string($cid);

    $sql = "SELECT * FROM messages WHERE conversation_id IN ('$cid')";
    $result = $con->query($sql);

    $data = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        echo json_encode(['status' => 'success', 'data' => $data]);
    } else {
        echo json_encode(['status' => 'success', 'data' => []]);
    }
    
    $con->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid parameters']);
}
?>