<?php

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

include '../db_connect.php';

$id = $_POST['id'];
$image = $_POST['image'];
$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();

    $baseUrl = 'https://votfinity.appnestbd.top/vota/update/';

    // 🔹 পুরানো ইমেজ বের করা হচ্ছে
    if ($type == 'Profile') {
        $oldSql = "SELECT image FROM singup_table WHERE id = '$id'";
    } else if ($type == 'Cover') {
        $oldSql = "SELECT cover FROM singup_table WHERE id = '$id'";
    }
    $oldResult = mysqli_query($con, $oldSql);
    $oldRow = mysqli_fetch_assoc($oldResult);

    $oldImagePath = $oldRow ? $oldRow[array_key_first($oldRow)] : null;

    // 🔹 নতুন ইমেজ সেভ
    $decodedImage = base64_decode($image);
    $fileName = time() . '_' . rand(1000, 10000) . '.jpg';
    $filePath = 'images/' . $fileName; // ✅ শুধু relative path
    $imageUrl = $baseUrl . $filePath;  // ✅ full URL

    if (file_put_contents($filePath, $decodedImage)) {

        // 🔹 পুরানো ইমেজ ডিলিট (যদি থাকে)
        if ($oldImagePath && $oldImagePath != "0") {
            // আগের ইমেজ যদি পুরো URL হয়, তাহলে শুধু পাথটা বের করা
            $localPath = str_replace($baseUrl, '', $oldImagePath);
            if (file_exists($localPath)) {
                unlink($localPath);
            }
        }

        if ($type == 'Profile') {

            // ✅ ১. singup_table এ শুধু file path যাবে
            $sql = "UPDATE singup_table SET image = '$filePath' WHERE id = '$id'";
            $result = mysqli_query($con, $sql);

            // ✅ ২. post_table এ full URL যাবে
            $sql1 = "UPDATE post_table SET profile = '$imageUrl' WHERE userid = '$id'";
            $result1 = mysqli_query($con, $sql1);

            // ✅ ৩. comment_table এ full URL যাবে
            $sql2 = "UPDATE comment_table SET profile = '$imageUrl' WHERE userid = '$id'";
            $result2 = mysqli_query($con, $sql2);

        } else if ($type == 'Cover') {

            // ✅ শুধু singup_table আপডেট (Cover এর জন্য)
            $sql = "UPDATE singup_table SET cover = '$filePath' WHERE id = '$id'";
            $result = mysqli_query($con, $sql);
        }
    }

    // 🔹 রেজাল্ট চেক
    if (isset($result) && $result) {
        echo "Successfully";
    } else {
        echo "Query Error";
    }

    mysqli_close($con);
    
    
} 



?>
