<?php

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

$name        = $_POST['name'];
$address      = $_POST['address'];
$image     = $_POST['image'];
$cover = $_POST['cover'];
$userid = $_POST['userid']; // মনে হচ্ছে Android কোডে "profile_userid" এর পরিবর্তে "userid" পাঠানো হচ্ছে
$time        = $_POST['time'];
$key         = $_POST['key'];

$security_key = decrypData($key);

header('Content-Type: text/plain'); // Text response রাখছি যাতে Android এ সহজে চেক করা যায়

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

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();

    // Generate unique page ID
    $pageid = str_pad(mt_rand(0, 999999999), 9, '0', STR_PAD_LEFT);
    
    // Default image paths
    $imagePath = "0";
    $coverPath = "0";
    
    // Process profile image
    if ($image !== "0" && !empty($image)) {
        $decodedImage = base64_decode($image);
        if ($decodedImage !== false) {
            $fileName = time() . '_profile_' . rand(1000, 9999) . '.jpg';
            $filePath = 'images/' . $fileName;  
            file_put_contents($filePath, $decodedImage);
            $imagePath = $filePath;
        }
    }
    
    // Process cover image
    if ($cover !== "0" && !empty($cover)) {
        $decodedCover = base64_decode($cover);
        if ($decodedCover !== false) {
            $fileNameCover = time() . '_cover_' . rand(1000, 9999) . '.jpg';
            $filePathCover = 'images/' . $fileNameCover;  
            file_put_contents($filePathCover, $decodedCover);
            $coverPath = $filePathCover;
        }
    }
    
    // Insert into database
    $stmt = $con->prepare("INSERT INTO page_table (userid, name, image, cover, address, profile_userid, time) 
                           VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssss", $pageid, $name, $imagePath, $coverPath, $address, $userid, $time);
    
    if ($stmt->execute()) {
        // Update user's page status
        $sql = "UPDATE signup SET page = 'Yes' WHERE userid = '$userid'";
        mysqli_query($con, $sql);
        
        echo "Successfully";
    } else {
        echo "Database Error: " . $stmt->error;
    }

    $stmt->close();
    $con->close();
} else {
    echo "Security key mismatch";
}
?>