#!/usr/bin/perl

use strict;
use lib '/home/slowtwitch/forum.slowtwitch.com/cgi-bin/admin';
use GForum qw/$DB $CFG $IN/;
use vars qw/$PRINT_HEADER $FONT $MAX $poll_vars/;

local $SIG{__DIE__} = \&GForum::fatal;

GForum::init('/home/slowtwitch/forum.slowtwitch.com/cgi-bin/admin');

$poll_vars = do "poll.cfg";

$MAX = 20;
$FONT = qq~font face="tacoma, arial, san-serif" size="2"~;
main();

sub main {
    header();
    nav();
    my $do = $IN->param('do');
    if ($do eq 'add_form') { add_form(); }
    elsif ($do eq 'add') { add(); }
    elsif ($do eq 'modify_form') { modify_form(); }
    elsif ($do eq 'modify') { modify(); }
    elsif ($do eq 'disable') { disable(); }
    elsif ($do eq 'enable') { enable(); }
    elsif ($do eq 'home_show') { home_show(); }
    elsif ($do eq 'home_notshow') { home_notshow(); }
    else {
	&list();
    }
    footer();
}

sub header {
    if (!$PRINT_HEADER) {
	print $IN->header();
    }
    print "<html><head><title>Poll Admin</title></head><body><$FONT>";
}

sub nav {
    print qq!
<b>Poll</b>: <a href="admin.cgi?do=add_form">Add Poll</a> | <a href="admin.cgi">List Poll</a>
!;
#<br><b>Quiz</b>: <a href="admin.cgi?do=add_form&poll_type=1">Add Quiz</a> | <a href="admin.cgi?poll_type=1">List Quiz</a><br>
}

sub footer {
    print "</body></html>";
}

sub include_form {
# -------------------------------------------------------------------
#
    my $val = shift || {};
    my $option = shift || $MAX;
    my $output = qq~<form action="admin.cgi" method="post">
	<input type="hidden" name="do" value="$val->{do}">
	<input type="hidden" name="poll_id" value="$val->{poll_id}">\n~;

    $output .= qq~<p><$FONT color="red">$val->{error}</font></p>~ if $val->{error};

    $output .= qq~
	<B>Question:</B> <br><textarea rows="4" cols="50" name="poll_question">$val->{poll_question}</textarea><br>\n
	<B>Description:</B> <br><textarea rows="4" cols="50" name="poll_text">$val->{poll_text}</textarea><br>\n
	<b>Answers Options:</b> <br>
	~;
    my $i = 1;
    my $select = qq~<select name="poll_answer">~;
    if ($val->{poll_answers_loop}) {
	foreach my $ans (@{$val->{poll_answers_loop}}) {
	    $output .= qq~Option $i: <input type="text" name="poll_answer_answer_$i" size="30" value="$ans->{poll_answer_answer}"> &nbsp;~;
	    if (!$val->{poll_type}) {
		$output .= qq~Votes: <input type="text" name="poll_answer_votes_$i" size="10" value="$ans->{poll_answer_votes}"><br>\n~;
	    }
	    $output .= qq~<input type="hidden" name="current_poll_answer_id_$i" value="$ans->{poll_answer_id}">\n~;
	    $output .= "<br>";
	    $select .= qq~<option value="$ans->{poll_answer_id}"~;
	    if ($val->{poll_answer} == $ans->{poll_answer_id}) {
		$select .= " selected";
	    }
	    $select .= qq~>$i</option>\n~;
	    $i++;
	}
	if ($IN->param('num_answers') > $i) {
	    foreach  ($i .. $IN->param('num_answers')) {
		$output .= qq~Option $_: <input type="text" name="poll_answer_answer_$_" size="30" value=""> &nbsp;~;
		if (!$val->{poll_type}) {
		    $output .= qq~Votes: <input type="text" name="poll_answer_votes_$_" size="10" value="0"><br>\n~;
		}
		$output .= "<br>";
		$select .= qq~<option value="$_">$_</option>\n~;
	    }
	}
	$i += 2;
    }
    else {
	foreach  (1 .. $option) {
	    my $ans = $val->{'poll_answer_answer_' . $_};
	    $output .= qq~Option $_: <input type="text" name="poll_answer_answer_$_" size="30" value="$ans"> &nbsp;~;
	    if (!$val->{poll_type}) {
		$output .= qq~Votes: <input type="text" name="poll_answer_votes_$_" size="10" value="0">\n~;
	    }
	    $output .= "<br>";
	    $select .= qq~<option value="$_">$_</option>\n~;
	}
    }
    $select .= "</select>";
    if ($val->{poll_type} == 1) {
	$output .= qq~<b>Right Answer:</b> $select<br><input type="hidden" name="poll_type" value="1">\n~;
    }
    $output .= qq~<B>Total Votes:</B> <input type="text" size="10" name="poll_votes" value="$val->{poll_votes}"><br><br>\n~;
    $output .= $val->{poll_id} ? 
	qq~<input type="submit" value="Modify">&nbsp;<a href="admin.cgi?do=modify_form&poll_id=$val->{poll_id}&num_answers=$i">Want to add more options?</a></form>~ :
	qq~<input type="submit" value="Add"></form>~;

    return $output . "\n";
}

sub list {
# -------------------------------------------------------------------
#
    my $msg = shift; 
    my $start_at = $IN->param("start_at") || 1;
    my $poll_count = $IN->param("poll_count") || 100;
    my $cgi = $IN->get_hash();
    $cgi->{nh} ||= $start_at;
    $cgi->{mh} ||= $poll_count;
    $cgi->{sb} ||= "poll_date";
    $cgi->{so} ||= "DESC";
    $cgi->{poll_type} ||= 0;

#use Data::Dumper; print "<pre>" . Dumper($cgi) . "</pre>";
    my $db = $DB->table('Poll');
    my $ans_db = $DB->table('PollAnswer');
    my $sth = $db->query_sth($cgi);
    my $output;

    if ($msg) {
	$output .= "<p>$msg</p>";
    }
    my $i=1;
    my $correct = "";
    while (my $row = $sth->fetchrow_hashref()) {
	my $date = $row->{poll_date};
	$output .= qq~<p><table width="100%"><tr><td colspan="2"><$FONT>$i.) $row->{poll_question} (posted on $date)</td></tr>
	    <tr><td colspan="2"><$FONT>Description: $row->{poll_text}</td></tr>~;
	my $answers = $ans_db->select( { poll_id_fk => $row->{poll_id} })->fetchall_hashref();
	my $max = 0;
	my $votes = $row->{poll_votes};
	foreach my $poll_answer (@$answers) {
	    if ($votes) {
		$poll_answer->{poll_answer_percentage} = sprintf("%" . $poll_vars->{percentage_pre} . "." . $poll_vars->{percentage_post} . "f",$poll_answer->{poll_answer_votes} / $votes * 100); 
	    }
	    if ($poll_answer->{poll_answer_votes} > $max) {
		$max = $poll_answer->{poll_answer_votes};
		$poll_answer->{poll_answer_is_leading} = 1;
	    }
	    else {
		$poll_answer->{poll_answer_is_leading} = 0;
	    }
	    if ($poll_answer->{poll_answer_id} == $row->{poll_answer}) {
		$correct = $poll_answer->{poll_answer_answer};
	    }
	    $output .= qq~
		<tr>
		<td align="right" width="20%">
		<$FONT>
		$poll_answer->{poll_answer_answer}
	    </td>
		<td align="left" width="80%">
		<$FONT> ~;
	    if ($poll_answer->{poll_answer_percentage}) {
		my $width = $poll_answer->{poll_answer_percentage} * 4;
		$output .= qq~<img src="/images/leftbar.gif" height="10" width="2" alt="" /><img src="/images/mainbar.gif" height="10" width="$width" alt="" /><img src="/images/rightbar.gif" height="10" width="2" alt="" />~;
	    }
	    else {
		$output .= qq~<img src="/images/leftbar.gif" height="10" width="2" alt="" /><img src="/images/rightbar.gif" height="10" width="2" alt="" />~;
	    }
	    $output .= qq~$poll_answer->{poll_answer_votes} / $poll_answer->{poll_answer_percentage} %
		</td> 
		</tr>
		~;
	}
	if ($row->{poll_type}) {
	    $output .= qq~<tr><td colspan="2"><$FONT>The Correct Answer is: $correct</td></tr>~;
	    $output .= qq~<tr><td colspan="2"><$FONT>Total Answered: $row->{poll_votes}</td></tr>~;
	}
	else {
	    $output .= qq~<tr><td colspan="2"><$FONT>Total Votes: $row->{poll_votes}</td></tr>~;
	}
	$output .= qq~<tr><td colspan="2"><$FONT>	<a href="admin.cgi?do=modify_form&poll_id=$row->{poll_id}">Edit</a> | ~;
	$output .= $row->{poll_enabled} ?
	    qq~<a href="admin.cgi?do=disable&poll_id=$row->{poll_id}"> Disable </a>~ :
	    qq~<a href="admin.cgi?do=enable&poll_id=$row->{poll_id}"> Enable</a>~ ;
	$output .= $row->{poll_home} ?
	    qq~| <a href="admin.cgi?do=home_notshow&poll_id=$row->{poll_id}"> Don't Show this on Home Page</a>~ :
	    qq~| <a href="admin.cgi?do=home_show&poll_id=$row->{poll_id}"> Show this on Home Page</a>~ ;
	$output .= qq~</td></tr></table>~;
	$i++;
    }
    print $output;
}

sub add_form {
# -------------------------------------------------------------------
#
    my $cgi = $IN->get_hash();
    my $error = shift;
    if ($error) {
	$cgi->{error} = $error;
    }
    $cgi->{do} = 'add';
    my $form = include_form( { %$cgi }, 4 );
    print $form;
}

sub add {
# -------------------------------------------------------------------
# 
# This subroutine will get called whenever the hook 'do_post_post'
# is run.
    my $total_options = 0;
    my %seen;
    my $dup = 0;
    for (1 .. $MAX) {
	my $ans = $IN->param("poll_answer_answer_$_");
	if ($ans) {
	    if ($seen{$ans}) {
		$dup = 1;
		last;
	    }
	    $seen{$ans} = 1;
	    $total_options++;
	}
    }
    if ($dup) {
	return add_form("Answers are the same.");
    }

    if (!$IN->param('poll_question')) {
	add_form("No question entered!");
	return;
    }
    if ($total_options < 2) {
	add_form("POLL_NOT_ENOUGH_OPTIONS");
	return;
    }

# Insert question into Poll table
    my $a = $DB->table('Poll');
    my $cgi = $IN->get_hash;
    $cgi->{'poll_enabled'} = '1';
    $cgi->{'poll_type'} ||= 0;
    $cgi->{'poll_votes'} = 0;
    if (!$cgi->{'poll_type'}){
	$cgi->{'poll_answer'} = 0;
    }
    require GT::Date;
    $cgi->{'poll_date'} = GT::Date::date_get();
    my $rec = $a->insert($cgi) or die "$GT::SQL::error";
    my $poll_id = $rec->insert_id;

    if (!$poll_id) {
	print "error: can't add poll, reason: $GT::SQL::error";
	return;
    }
# Insert answers into PollAnswer table
    my $votes_sum;
    my $b = $DB->table('PollAnswer');
    for (my $i = 1; $i <= $MAX; $i++) {
	my %answer;
	if ($IN->param("poll_answer_answer_$i")) {
	    $answer{'poll_answer_answer'} = $IN->param("poll_answer_answer_$i");
	    $answer{'poll_answer_votes'} = 0;
	    $answer{'poll_id_fk'} = $poll_id;
	    my $res = $b->insert(\%answer);
	    my $ans_id = $res->insert_id;
	    if ($i == $cgi->{poll_answer}) {
		$a->update( { poll_answer => $ans_id }, { poll_id => $poll_id });
	    }
	};
    };
    my $msg = "Poll added successfully!";
    &list($msg);
}

sub modify_form {
# -------------------------------------------------------------------
#
    my $id = $IN->param('poll_id') || shift;
    if (!$id) {
	print "no poll id passed";
	return;
    }
    my $poll = $DB->table('Poll')->get($id);
    my $ans_db = $DB->table('PollAnswer');
    my $poll_answer = $ans_db->select( { poll_id_fk => $id } )->fetchall_hashref();
    my $hits = $ans_db->hits;
    my $form = include_form( { do => 'modify', %$poll, poll_answers_loop => $poll_answer}, 4 );
    print $form;
}

sub modify {
# -------------------------------------------------------------------
#
    my $poll_id = $IN->param('poll_id');
    my $cgi = $IN->get_hash();

# Update existing record or insert new record (PollAnswer table)
    my $votes_sum = 0;
    my $a = $DB->table('PollAnswer');
    for (my $i = 1; $i <= $MAX; $i++) {
	my %answer;
	if ($IN->param("poll_answer_answer_$i")) {
	    $answer{'poll_answer_answer'} = $IN->param("poll_answer_answer_$i");
	    if ($IN->param("poll_answer_votes_$i")) {
		$answer{'poll_answer_votes'} = $IN->param("poll_answer_votes_$i");
	    }
	    $answer{'poll_id_fk'} = $poll_id;
	    $votes_sum += $IN->param("poll_answer_votes_$i");
	    if ($IN->param("current_poll_answer_id_$i")) {
		$a->update(\%answer, { poll_answer_id => $IN->param("current_poll_answer_id_$i") }) or die $GT::SQL::error;
	    }
	    else {
		$a->insert(\%answer);
	    }
	}
	elsif ($IN->param("current_poll_answer_id_$i") and not $IN->param("poll_answer_answer_$i")) {
	    $a->delete( { poll_answer_id => $IN->param("current_poll_answer_id_$i") });
	};
    };

# Update vote count
    my $p = $DB->table('Poll');
    my $poll_type = $IN->param('poll_type') || '0';
    my $cols = $p->cols;
    my $mod = {};
    foreach (keys %$cols) {
	next if ($_ eq 'poll_id');
	next if ($_ eq 'poll_date');
	next if ($_ eq 'poll_home');
	next if ($_ eq 'poll_enabled');
	$mod->{$_} = $cgi->{$_}; 
    }
    if (!$poll_type) {
	$mod->{poll_answer} = 0; 
	$mod->{poll_type} = 0; 
    }
    $p->update( $mod , { poll_id => $poll_id }) or die "$GT::SQL::error";
    &list("The poll has been updated successfully!");
}

sub disable {
    my $poll_id = $IN->param('poll_id');
    my $p = $DB->table('Poll');

    my $poll = $p->get($poll_id);
    if (!$poll) {
	return &list("No such quiz or poll: $poll_id");
    }
    $p->update({ poll_enabled => 0 }, { poll_id => $poll_id });
    $IN->param('poll_id',"");
    $IN->param('poll_type',$poll->{poll_type});
    &list("The poll/quiz $poll->{poll_question} has been disabled.");
}

sub enable {
    my $poll_id = $IN->param('poll_id');
    my $p = $DB->table('Poll');

    my $poll = $p->get($poll_id);
    if (!$poll) {
	return &list("No such quiz or poll: $poll_id");
    }
    $p->update({ poll_enabled => 1  }, { poll_id => $poll_id });
    $IN->param('poll_id',"");
    $IN->param('poll_type',$poll->{poll_type});
    &list("The poll/quiz $poll->{poll_question} has been enabled.");
}

sub home_show {
    my $poll_id = $IN->param('poll_id');
    my $p = $DB->table('Poll');

    my $poll = $p->get($poll_id);
    if (!$poll) {
	return &list("No such quiz or poll: $poll_id");
    }
    $p->update({ poll_home => 0 });
    $p->update({ poll_home => 1 }, { poll_id => $poll_id });
    $IN->param('poll_id',"");
    $IN->param('poll_type',$poll->{poll_type});
    &list("The poll/quiz $poll->{poll_question} has been set to show on home page.");
}

sub home_notshow {
    my $poll_id = $IN->param('poll_id');
    my $p = $DB->table('Poll');

    my $poll = $p->get($poll_id);
    if (!$poll) {
	return &list("No such quiz or poll: $poll_id");
    }
    $p->update({ poll_home => 1  }, { poll_id => $poll_id });
    $IN->param('poll_id',"");
    $IN->param('poll_type',$poll->{poll_type});
    &list("The poll/quiz $poll->{poll_question} has been removed from showing on the home page.");
}
