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

require_once("config.php");
require_once("user/protect.php");
require_once("user/user-lib.php");

$db = new PDO(
      "mysql:host=".USER_DB_HOST.";dbname=".USER_DB_NAME.";charset=".USER_DB_CHARSET,
      USER_DB_USER, USER_DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);


$projectid=$_POST["projectid"];
$postmode=$_POST["postmode"];
$postdate=$_POST["postdate"];
$imagefilename=$_POST["imagefilename"];
$title=$_POST["title"];
$sendwithpost=$_POST["sendwithpost"];
$postmode=$_POST["postmode"];
$p1_content = urldecode(base64_decode($_POST['p1_content']));
$whichblog=$_POST["whichblog"];

$fields = [];
for ($i = 1; $i <= 12; $i++) {
    $fields[] = "user_bloglink" . $i;
}

$sql = "SELECT " . implode(", ", $fields) . " FROM users WHERE user_id = :user_id";
$stmt = $db->prepare($sql);
$stmt->bindParam(':user_id', $userid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if ($result) {
    $keyName = "user_bloglink" . $whichblog;
    
    if (isset($result[$keyName])) {
        $decodedValue = base64_decode($result[$keyName]);
        
        $blog_key = substr($decodedValue, 0, 16);
        $blog_url = substr($decodedValue, 16);

        if (empty(trim($blog_url))) {
            echo "ERROR: blog not linked";
            exit();
        }
    }
}




if ($postmode=="draft"){
	$post_status="draft";
} else if ($postmode=="now" || $postmode=="later"){
	$post_status="publish";
}

switch ($postmode) {
	
	case "draft":
		$db_postmode=0;
		break;
	case "now":
		$db_postmode=1;
		break;
	case "later":
		$db_postmode=2;
		break;
	
}

// Check image exists if called for 

$image_path="";
if($sendwithpost==1 && $imagefilename!==""){
	$image_path = "image_store/".$userid."/"; 
	if (file_exists($image_path.$imagefilename)){
		$image_path.=$imagefilename; 
	}
}

$wp_endpoint = $blog_url.'/wp-json/crpc/v1/createpost';


// Post data
$post_data = array(
    'title'   => $title,
    'content' => $p1_content,
    'status'  => $post_status,
    'date'    => $postdate
);

if (!empty($image_path)) {
    $post_data['featured_image'] = new CURLFile($image_path, 'image/jpeg');
	
}

// Initialize cURL session
$ch = curl_init($wp_endpoint);

// Set cURL options
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.0.0 Safari/537.36');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	'Content-Type: multipart/form-data',
    'X-Custom-Secret: ' . $blog_key
));

// Execute the cURL session and fetch the response
$response = curl_exec($ch);

if ($imagefilename!=="") {
	$image_path = "image_store/".$userid."/"; 
	if (file_exists($image_path.$imagefilename)){
		$image_path.=$imagefilename;
		@unlink($image_path);
	}
    
}


$info = curl_getinfo($ch);

// Check for cURL errors
if (curl_errno($ch)) {
    echo 'Request Error:' . curl_error($ch);
} else {

}

// Close the cURL session
curl_close($ch);

// Update user DB


try {
    $sql = "UPDATE projects SET isposted = 1, dateposted = NOW(), imageprompt = '', imagefile = '', postmode = :postmode, whichblog=:whichblog ";
    if (!empty($postdate)) {
        $sql .= ", publishdate = :publishdate ";
    }
    $sql .= "WHERE id = :project_id";
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':project_id', $projectid, PDO::PARAM_INT);
    $stmt->bindParam(':postmode', $db_postmode, PDO::PARAM_INT);
    $stmt->bindParam(':whichblog', $blog_url);
    if (!empty($postdate)) {
        $stmt->bindParam(':publishdate', $postdate, PDO::PARAM_STR);
    }

    $stmt->execute();

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

echo "SUCCESS";
exit();

?>
