<?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
    ]);

$id = intval($_POST["id"]); 
if ($id!=""){
	

try {
    $stmt = $db->prepare("SELECT canvas_store FROM projects WHERE user_id = :userid AND id = :id");
    $stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($result) {
        $canvas_store = $result['canvas_store'];

        // Make sure JSON string is correctly formatted without unnecessary trims
        $canvas_data = json_decode($canvas_store, true);
        //file_put_contents("TEMPcanvas_store.txt", "STORE: " . $canvas_store . " - DATA: " . json_encode($canvas_data));

        if (json_last_error() !== JSON_ERROR_NONE) {
            file_put_contents("TEMPJSONerror.txt", "NEW JSON Decode Error: " . json_last_error_msg());
            exit;
        }

        $image_paths = [];
        foreach ($canvas_data['objects'] as $object) {
            if (isset($object['type']) && $object['type'] === 'image' && !empty($object['src'])) {
                $u_img_pos = strpos($object['src'], 'u_img');
                if ($u_img_pos !== false) {
                    $image_path = substr($object['src'], $u_img_pos);
                    $image_paths[] = $image_path;
                }
            }
        }

        foreach ($image_paths as $url) {
            $url = htmlspecialchars($url);
            if (file_exists($url)) {
                unlink($url);
            }
        }

    } else {
        echo "No record found.";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

	

	$sql = "DELETE FROM projects WHERE user_id = :user_id AND id = :id";
	$statement = $db->prepare($sql);
	$statement->bindParam(':user_id', $userid, PDO::PARAM_INT);
	$statement->bindParam(':id', $id, PDO::PARAM_INT);
	$statement->execute();
	$affectedRows = $statement->rowCount();
	if ($affectedRows > 0) {
		echo $id;
	} else {
		echo "ERROR";
	}

}





?>
