<?php 

$max_name = 30;
$max_description = 255;
$img_width = 250;
$img_height = 250;

$dir = '../../';

require_once $dir.'includes/main.php';

$errors = array();

$id = (int)$_POST['id'];

$name = clean($_POST['name']);
$description = clean($_POST['description']);

// check category
$sql = "SELECT * FROM categories WHERE id = '{$id}' LIMIT 1";
if(fetch_rows($sql) < 1){
    $errors[] = "Category could not be found";
}else{
    $x = fetch_records($sql);
}

// check name
if(empty($name)){
    $errors[] = "Name is required";
}

if(strlen($name) > $max_name){
    $errors[] = "Name cannot be more than $max_name characters";
}

if($name != $x['name']){
    if(fetch_rows("SELECT id FROM categories WHERE name = '{$name}' LIMIT 1") > 0){
        $errors[] = "Name already exists";
    }
}

// check description
if(empty($description)){
    $errors[] = "Description is required";
}

if(strlen($description) > $max_description){
    $errors[] = "Description cannot be more than $max_description characters";
}

// check image
if(!empty($_FILES['image']['name'])){

    $pname = $_FILES['image']['name'];
    $psize = $_FILES['image']['size'];
    $ptype = $_FILES['image']['type'];
    $ptmpn = $_FILES['image']['tmp_name'];

    if($ptype == 'image/png'){
        $image = imagecreatefrompng($ptmpn);
    }else{
        $_SESSION['messages'][] = 'File format must be PNG';
        header("location: ../create/category");
        exit;
    }

    $width = imagesx($image);
    $height = imagesy($image);

    if($width != $img_width){
        $errors[] = "Image width must be {$img_width}px. You uploaded: {$width}px";
    }

    if($height != $img_height){
        $errors[] = "Image width must be {$img_height}px. You uploaded: {$height}px";
    }

}

//check errors
if(!empty($errors)){

    // send errors
    $errors = implode('. ', $errors);
    $message = array('type' => 'ERROR', 'message' => $errors);
    echo json_encode($message);

}else{

    // on success

    if(query("UPDATE categories SET name = '{$name}', description = '{$description}' WHERE id = '{$id}' LIMIT 1")){

        $filename = to_url($name).'.png';

        if(!empty($_FILES['image']['name'])){
            $x['image'] != 'default.png' ? unlink($dir.'images/categories/'.$x['image']) : null;
            move_uploaded_file($ptmpn, $dir.'images/categories/'.$filename);
            query("UPDATE categories SET image = '{$filename}' WHERE id = '{$id}' LIMIT 1");
        }

        // send success
        $message = array('type' => 'SUCCESS', 'message' => "Category has been updated successfully. Thank you");
        echo json_encode($message);

    }else{

        // send error
        $message = array('type' => 'ERROR', 'message' => ERROR_DATABASE);
        echo json_encode($message);

    }

}

?>