<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$con = dbConnect();
if(!$con){
    die("DB Error: " . mysqli_connect_error());
}

// POST DATA
$userid  = $_POST['userid'];
$text    = $_POST['text'];
$type    = $_POST['type'];
$time    = $_POST['time'];
$account_type    = $_POST['account_type'];
$key     = $_POST['key'];

$security_key = decrypData($key);

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

if ($security_key != SECURITY_KEY_PLAIN){
    echo "Wrong Key";
    exit;
}

// ----- IMAGE UPLOAD -----

$imagesArr = [];
$uploadDir = __DIR__ . "/uploads/";

// create folder if not exists
if(!is_dir($uploadDir)){
    mkdir($uploadDir, 0777, true);
}

if(isset($_FILES['images'])){
    foreach($_FILES['images']['tmp_name'] as $index => $tmp_name){

        $ext = pathinfo($_FILES['images']['name'][$index], PATHINFO_EXTENSION);
        $newName = uniqid("IMG_", true) . "." . $ext;

        $serverPath = $uploadDir . $newName; // absolute path
        $dbPath = "uploads/" . $newName;     // relative path for DB

        if(move_uploaded_file($tmp_name, $serverPath)){
            $imagesArr[] = $dbPath;
        } else {
            echo "Upload failed for: " . $serverPath;
            exit;
        }
    }
}

// convert to string or NULL
$imagesStr = empty($imagesArr)
    ? "NULL"
    : "'" . mysqli_real_escape_string($con, implode(",", $imagesArr)) . "'";


// ----- INSERT -----

$sql = "
INSERT INTO post_table (userid,text,images,time,type,account_type)
VALUES (
    '$userid',
    '$text',
    $imagesStr,
    '$time',
    '$type',
    '$account_type'
)
";

if(mysqli_query($con, $sql)){
    echo "Success";
}else{
    echo "Error: " . mysqli_error($con) . " | SQL: " . $sql;
}

?>
