#!/usr/bin/perl
use strict;
use warnings;

package API::Header;

our $Config;
BEGIN{
	use API::Config;
	$Config = $API::Config::Config;
}
use lib ($Config->{Website_libs});

use ECS::SQL;

my $DBH = ECS::SQL::connect();

sub update{
	
	my $ref = shift;
	my $input = shift;
	
	my $result = {
		'success'	=> 1,
		'error'		=> undef,
		'update_DB'	=> $Config->{update_DB}
	};
	# IF we want to write to DB (Determined by API::Config)
	# --------------------------------------------------
	if ($Config->{update_DB}){	
		if(!ECS::SQL::update({
	         DBH => $DBH,
	         table => 'html_block',
	         key => 'blockID',
	         columns => [qw(content shortDesc)],
	         hash => {content => $input->{entities_contentHtml}, blockID => $input->{blockID}, shortDesc => $input->{shortDesc}}		
	     })){
	     		$result->{success} = 0;
				$result->{error} = "Unable to update header.";
	     };
	}
    return $result;
}

sub add{

	my $ref = shift;
	my $input = shift;
	
	my $result = {
		'success'	=> 1,
		'error'		=> undef,
		'update_DB'	=> $Config->{update_DB},
		'row'	=> 0,
	};
	# IF we want to write to DB (Determined by API::Config)
	# --------------------------------------------------
	if ($Config->{update_DB}){
		use POSIX qw(strftime);
		$input->{'dateCreated'} = strftime("%Y-%m-%d %H:%M:%S",localtime(time));
	    my $row = ECS::SQL::insert({
	              		DBH => $DBH,
	                    table => 'html_block',
	                    key => 'blockID',
	                    columns => [qw(content dateCreated shortDesc)],
	                    hash => {content => $input->{entities_contentHtml}, dateCreated => $input->{dateCreated}, shortDesc => $input->{shortDesc}}
	                });
	    if(!$row){
	    	$result->{success} = 0;
	    	$result->{error} = "Unable to add header to DB.";
	    }
	    
		$result->{row} = $row;
	}
	return $result;
}

sub delete{
	my $ref = shift;
	my $input = shift;
	
	my $result = {
		'success'	=> 1,
		'error'		=> undef,
		'update_DB'	=> $Config->{update_DB}
	};
	
	my $tmp;
	($tmp = $input->{removeHeader}) =~ s/^a_//;
	ECS::SQL::delete({
		DBH => $DBH, 
		table => 'html_block',
		columns => [qw(blockID)],
		hash => {blockID=>$tmp}
	});
	
	return $result;
}

1;
