<?php

include 'db_connect.php';

$userid = $_POST['userid'];
$name = $_POST['name'];
$profile = $_POST['profile'];
$time = $_POST['time'];
$title = $_POST['title'];
$image1 = $_POST['image1'];
$image2 = $_POST['image2'];
$image3 = $_POST['image3'];
$image4 = $_POST['image4'];
$question1 = $_POST['question1'];
$question2 = $_POST['question2'];
$question3 = $_POST['question3'];
$question4 = $_POST['question4'];
$type = $_POST['type'];
$key = $_POST['key'];

$security_key = decrypData($key);

// ✅ ইমেজ প্রসেস ফাংশন — শুধু file path রিটার্ন করবে (যেমন images/xxxx.jpg)
function processImage($imageData, $imageNamePrefix) {
    if ($imageData == "0") {
        return "0";
    }
    $fileName = time() . '_' . rand(1000, 9999) . '_' . $imageNamePrefix . '.jpg';
    $filePath = 'images/' . $fileName;
    file_put_contents($filePath, base64_decode($imageData));
    return $filePath; // ✅ শুধু path রিটার্ন করছে (domain ছাড়া)
}

if ($security_key == 'Jobayer121415' && strlen($userid) > 0) {

    $con = dbConnect();
    $sql1 = "SELECT * FROM post_table WHERE time LIKE '$time'";
    $result = mysqli_query($con, $sql1);
    $rows = mysqli_num_rows($result);

    if ($rows <= 0) {

        // ✅ সব ইমেজ প্রসেস করা হচ্ছে
        $image1Path = processImage($image1, 'image1');
        $image2Path = processImage($image2, 'image2');
        $image3Path = processImage($image3, 'image3');
        $image4Path = processImage($image4, 'image4');

        $sql = "INSERT INTO post_table (
                    userid, name, profile, online, time, title, 
                    image1, image2, image3, image4, 
                    question1, question2, question3, question4, 
                    likes, loves, cares, wows, type
                ) VALUES (
                    '$userid', '$name', '$profile', 'true', '$time', '$title', 
                    '$image1Path', '$image2Path', '$image3Path', '$image4Path', 
                    '$question1', '$question2', '$question3', '$question4', 
                    '0', '0', '0', '0', '$type'
                )";

        $result = mysqli_query($con, $sql);

        if ($result) {
            echo "Successfully";
        } else {
            echo "Query Error";
        }

    } else {
        echo 'User already available! Change email and try again';
    }

    mysqli_close($con);
}

// ✅ ডিক্রিপশন ফাংশন
function decrypData($text) {
    $decoded = base64_decode($text);
    $decrypted = openssl_decrypt($decoded, 'AES-128-ECB', '0175526800812345', OPENSSL_RAW_DATA);
    return $decrypted;
}

?>
