<?php 

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

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

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

$errors = array();

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

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

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

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('message' => $errors);
   echo json_encode($message);

}else{

   // on success
   if(query("INSERT INTO categories (name, image, description, date_created) VALUES ('{$name}', 'default.png', '{$description}', '{$t}')")){

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

      if(!empty($_FILES['image']['name'])){
         move_uploaded_file($ptmpn, $dir.'images/categories/'.$filename);
         query("UPDATE categories SET image = '{$filename}' ORDER BY id DESC LIMIT 1");
         $_SESSION['messages'][] = "Image has been uploaded successfully";
      }

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

   }else{

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

   }

}

?>