#!/usr/bin/perl

use strict;
use vars qw{%Form $Self $d};
require '/home/webmangr/cgi-box/polls/common.pm';

$Self = '/cgi-box/polls/vote';

&Decode('+');
&Connect();
&Main();

sub Main {

  my($r,$Skip);

  &Poll($Form{POLL});
  if($Form{POLL_ID} == 0) {
    &Error('Sorry, you have entered an invalid poll identifier.'); #!!
  };

  if($Form{POLL_ACTIVE} ne 'Y') {
    $Form{ERROR} = 'Sorry, this poll is now closed.';
    $Skip = 1;

  } elsif($Form{VOTE}) {
    if(scalar(split(',',$Form{OPTION})) != $Form{POLL_REQUIRED}) {
      if($Form{POLL_REQUIRED}==1) {
        $Form{ERROR} = "Please make a selection from the available options.";
      } else {
        $Form{ERROR} = "Please make $Form{POLL_REQUIRED} selections from the available options.";
      };
    } else {
#!! check for dupes, etc
#!! insert into results
      if($Form{POLL_REQUIRED}==1) {
        $Form{ERROR} = 'Your selection has been recorded.';
      } else {
        $Form{ERROR} = 'Your selections have been recorded.';
      };
      $Skip = 1;
    };

  };

  if(!$Skip) {

    my(%Option,$Checked,$Check);
    $d->select('SELECT * FROM PL_OPTIONS WHERE POLL=?',$Form{POLL_ID},\%Option);
    while($d->row()) {
      $Check = ",$Form{OPTION},";
      if($Check =~ /,$Option{ID},/) { $Checked = ' checked'; } else { $Checked = ''; };
      if($Form{POLL_REQUIRED}==1) {
        $r .= "<input type=radio name=OPTION value=$Option{ID} $Checked> $Option{DETAIL}<BR>\n";
      } else {
        $r .= "<input type=checkbox name=OPTION VALUE=$Option{ID} $Checked> $Option{DETAIL}<BR>\n";
      };
    };
    $r .= &Expand('<p><input type="hidden" name="POLL" value="{POLL}"><input type="submit" value="Vote" name="VOTE" style="width=100"></p>');

  };

  $Form{CHOICES} = $r;

  &Show('template_'.$Form{POLL_TEMPLATE});

};
