<?php
include '../db_connect.php';

$user_id = $_POST['user_id'];
$post_id = $_POST['post_id'];
$key = $_POST['key'];

$security_key = decrypData($key);

if ($security_key == 'Jobayer121415') {

    $con = dbConnect();

    // আগে থেকেই ফেভারিট করা আছে কিনা চেক করুন
    $check_sql = "SELECT * FROM favorite_posts WHERE user_id = '$user_id' AND post_id = '$post_id'";
    $check_result = mysqli_query($con, $check_sql);

    if (mysqli_num_rows($check_result) > 0) {
        // আগে থেকেই ফেভারিট করা আছে → আন-ফেভারিট করুন (ডিলিট)
        $delete_sql = "DELETE FROM favorite_posts WHERE user_id = '$user_id' AND post_id = '$post_id'";
        if (mysqli_query($con, $delete_sql)) {
            echo 'Unfavorited';
        } else {
            echo 'Delete Error';
        }

    } else {
        // না থাকলে → ফেভারিট করুন (ইনসার্ট)
        $insert_sql = "INSERT INTO favorite_posts (user_id, post_id) VALUES ('$user_id', '$post_id')";
        if (mysqli_query($con, $insert_sql)) {
            echo 'Favorited';
        } else {
            echo 'Insert Error';
        }
    }

} else {
    echo "Invalid Key";
}

function decrypData($text) {
    $decoded = base64_decode($text);
    $decrypted = openssl_decrypt($decoded, 'AES-128-ECB', '0175526800812345', OPENSSL_RAW_DATA);
    return $decrypted;
}
?>
