<?php

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

include '../db_connect.php';

$sender = $_POST['sender_id'];
$receiver  = $_POST['receiver_id'];
$msg    = $_POST['message'];
$time  = $_POST['time'];
$type    = $_POST['type'];
$key  = $_POST['key'];


$security_key = decrypData($key);

if ($security_key === false) {
    echo 'Invalid encryption data';
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {
    

$con = dbConnect();

// conversation আছে কিনা চেক
$q = mysqli_query($con,
"SELECT id FROM conversations 
 WHERE (user_one='$sender' AND user_two='$receiver')
    OR (user_one='$receiver' AND user_two='$sender')");

if(mysqli_num_rows($q) > 0){

    // conversation already exists
    $row = mysqli_fetch_assoc($q);
    $cid = $row['id'];

}else{

    // create new conversation
    mysqli_query($con,
    "INSERT INTO conversations(user_one,user_two)
     VALUES('$sender','$receiver')");

    $cid = mysqli_insert_id($con);
}

// message insert
mysqli_query($con,
"INSERT INTO messages(conversation_id,sender_id,message,type,time)
 VALUES('$cid','$sender','$msg','$type','$time')");

echo json_encode([
    "status" => "success",
    "cid"    => $cid
]);


}

?>
