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



extract($_POST, EXTR_SKIP);

$canvas_store=var_export($canvas_store,true);

if ($id == 0) {
    $sql = "
    INSERT INTO projects (
        user_id, project_name, date_created, last_edited, category, canvas_width, canvas_height, palette_store, canvas_store
    ) 
    VALUES (
        :user_id, :project_name, NOW(), NOW(), :category, :canvas_width, :canvas_height, :palette_store, :canvas_store
    )
";
	$stmt = $db->prepare($sql);
	$stmt->bindParam(':user_id', $userid);
	$stmt->bindParam(':project_name', $projectname);
	
	$stmt->bindParam(':category', $category);
	$stmt->bindParam(':canvas_width', $canvas_width);
	$stmt->bindParam(':canvas_height', $canvas_height);
	$stmt->bindParam(':palette_store', $palette_store);
	$stmt->bindParam(':canvas_store', $canvas_store);
    $stmt->execute();
    $lastId = $db->lastInsertId();
    echo $lastId;
	exit();
} else {
    $sql = "SELECT * FROM projects WHERE id = :projectid AND user_id = :user_id";
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':projectid', $id);
    $stmt->bindParam(':user_id', $userid);
    $stmt->execute();

    if($stmt->rowCount() > 0) {
		$sql = "
			UPDATE projects 
			SET project_name=:project_name, last_edited = NOW(), category=:category, canvas_width=:canvas_width, canvas_height=:canvas_height, palette_store=:palette_store, canvas_store=:canvas_store
			WHERE id = :projectid AND user_id=:user_id
		";

        $stmt = $db->prepare($sql);
		$stmt->bindParam(':project_name', $projectname);
		$stmt->bindParam(':category', $category);
		$stmt->bindParam(':canvas_width', $canvas_width);
		$stmt->bindParam(':canvas_height', $canvas_height);
		$stmt->bindParam(':palette_store', $palette_store);
		$stmt->bindParam(':canvas_store', $canvas_store);
		$stmt->bindParam(':projectid', $id);
		$stmt->bindParam(':user_id', $userid);
        $stmt->execute();
        
        echo $id;
		exit();
        
    } else {
        echo "ERROR";
    }
}

?>
