#!/usr/bin/perl

require 5.004;

use strict;
use CGI::Carp qw(fatalsToBrowser);
use CGI;
use EdcomLib::EdcomLib;
use EdcomLib::SQL;
use EdcomLib::Tables;
use EdcomLib::Auth;
use EdcomLib::Time;

$CGI::POST_MAX=1024 * 10;
$CGI::DISABLE_UPLOADS = 1;

my $q = new CGI;
my $p = new EdcomLib::EdcomLib;
my $t = new EdcomLib::Tables;
my $time = new EdcomLib::Time;
my $auth = new EdcomLib::Auth;
my $s = new EdcomLib::SQL;
$s->connect(
	{ 'pass' => 'qudc79' }
);

my $heb;

if(! $auth->auth()) {
	print $q->header();
}

if($q->param('del') eq '1' and
	$auth->checkaccess() >= $auth->fetchreq('Administrator'))
{
	can_delete();
}

if($q->param('aid') ne '') {
	display_comments();
}
else {
	print $q->start_html();
	print $t->getblock('bad_access');
	print $q->end_html();
}

sub display_comments {
	my $aref = $s->sql(
		"SELECT aid,uid,did,title,intro,body,ts FROM stories WHERE aid = ?",
		$q->param('aid')
	);
	my $h = $aref->[0];

	$h->{'parent'} = ($q->param('parent') or '0');
	$h->{'cid'} = ($q->param('cid') or '');
	$h->{'tid'} = ($q->param('tid') or '');

	if($q->param('view') eq ''
		or $q->param('sort') eq ''
		or $q->param('view') =~ m/no comments/i)
	{
		$heb = $t->fetchdeptvalue('story_t',$aref->[0]->{'did'});
	}
	else {
		$heb = $t->fetchdeptvalue('nostory_t',$aref->[0]->{'did'});
	}
	print $p->parse(
		$t->getheb($heb),
		$h
	);
}

sub can_delete {
	return if $q->param('cid') eq '';
	delete_comments($q->param('cid'));
		my $aref = $s->sql(
			"SELECT uid,cid FROM msgcomments WHERE cid = ?",
			$q->param('cid')
		) if $q->param('cid') ne '';
		if($aref->[0]->{'uid'} ne '0') {
			$s->sql(
				"DELETE FROM recent_posts WHERE uid = ? AND cid = ?",
				$aref->[0]->{'uid'},$q->param('cid')
			);
		}
	$s->sql("DELETE FROM comments WHERE cid = ?",$q->param('cid'));

	# Update our story touch column to indicate a recent change
	$s->sql(
		"UPDATE stories SET touch = ? WHERE aid = ?",
			$time->now_to_dbdate(),
			$q->param( 'aid' )
	);

}

sub delete_comments {
	my $cid = shift;
	my $aref = $s->sql(
		"SELECT cid,parent FROM comments WHERE parent = ?",
		$cid
	);
	for(my $x = 0; $x < @$aref; $x++) {
		delete_comments($aref->[$x]->{'cid'});
		$s->sql("DELETE FROM comments WHERE cid = ?",$aref->[$x]->{'cid'});
	}
}
