<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '.. / config/Database.php';
include_once '.. / class/Items.php';

$database = new Database();
$db = $database->getConnection();

$items = new Items($db);

$data = json_decode(file_get_contents("php://input"));

if(!empty($data->ruc) && !empty($data->nombre) &&
!empty($data->nombre_comercial) && !empty($data->direccion) &&
!empty($data->created_at)){

$items->ruc = $data->ruc;
$items->nombre = $data->nombre;
$items->nombre_comercial = $data->nombre_comercial;
$items->direccion = $data->direccion; 
$items->created_at = date('Y-m-d H:i:s'); 

if($items->create()){ 
http_response_code(201); 
echo json_encode(array("message" => "Item was created."));
} else{ 
http_response_code(503); 
echo json_encode(array("message" => "Unable to create item."));
}
}else{ 
http_response_code(400); 
echo json_encode(array("message" => "Unable to create item. Data is incomplete."));
}
?>

<?php
function create(){

$stmt = $this->conn->prepare("
INSERT INTO ".$this->itemsTable."(`ruc`, `nombre`, `nombre_comercial`, `direccion`, `created_at`)
VALUES(?,?,?,?,?)");

$this->ruc = htmlspecialchars(strip_tags($this->ruc));
$this->nombre = htmlspecialchars(strip_tags($this->nombre));
$this->nombre_comercial = htmlspecialchars(strip_tags($this->nombre_comercial));
$this->direccion = htmlspecialchars(strip_tags($this->direccion));
$this->created_at = htmlspecialchars(strip_tags($this->created_at));


$stmt->bind_param("ssiis", $this->name, $this->description, $this->price, $this->category_id, $this->created);

if($stmt->execute()){
return true;
}

return false; 
}
?>