<?php
/*******************************************
 Database query to get poll info
 *******************************************/
// get vote from form
$vote=$_POST['vote'];
// connect to MySQL server

/*
if (!$db_conn = mysql_connect("localhost", "root", "jghomi"))
{
    echo 'Could not connect to db<br />';
    exit;
}
@mysql_select_db('poll');
*/

$host = 'localhost'; // Change as necessary
$data = 'polling'; // Change as necessary
$user = 'root'; // Change as necessary
$pass = 'mysql'; // Change as necessary
$chrs = 'utf8mb4';
$attr = "mysql:host=$host;dbname=$data;charset=$chrs";
$opts =
[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

try
{
    $pdo = new PDO($attr, $user, $pass, $opts);
}
catch (PDOException $e)
{
    throw new PDOException($e->getMessage(), (int)$e->getCode());
}



if (!empty($vote))  // if they filled the form out, add their vote
{
    $vote = addslashes($vote);
    $query = "update poll_results
            set num_votes = num_votes + 1
            where candidate = '$vote'";
    $result = $pdo->query($query);
    
    if(!$result)
    {
        echo 'Could not connect to db<br />';
        exit;
    }
}


// get current results of poll, regardless of whether they voted
$query = 'select * from poll_results';
$result = $pdo->query($query);
if(!$result)
{
    echo 'Could not connect to db<br />';
    exit;
}

/*
$num_candidates = mysql_num_rows($result);
// calculate total number of votes so far
$total_votes=0;
while ($row = mysql_fetch_object ($result))
{
    $total_votes +=  $row->num_votes;
}
mysql_data_seek($result, 0);  // reset result pointer
*/
$total_votes = 0;
while ($row = $result->fetch()) {
    $total_votes +=  $row['num_votes'];
  //  echo "n = ".$row['num_votes']."<br>";
  //  reset($result);
  //  $sim_users .= ", '".($row['username'])."'";
}



$num_candidates = $result->rowCount();
echo "numcan = ".$num_candidates;
//echo "hhhhhhhhhhhhhhhhhhhhhhh=".$total_votes;
/*******************************************
 Initial calculations for graph
 *******************************************/
// set up constants

/*
echo "setup";
$width=500;        // width of image in pixels - this will fit in 640x480
$left_margin = 50; // space to leave on left of image
$right_margin= 50; // ditto right
$bar_height = 40;
$bar_spacing = $bar_height/2;
//$font = 'c:\windows\fonts\arial.ttf';
$title_size= 16; // point
$main_size= 12; // point
$small_size= 12; // point
$text_indent = 10; // position for text labels on left
// set up initial point to draw from
$x = $left_margin + 60;  // place to draw baseline of the graph
$y = 50;		  // ditto
$bar_unit = ($width-($x+$right_margin)) / 100;   // one "point" on the graph
// calculate height of graph - bars plus gaps plus some margin
$height = $num_candidates * ($bar_height + $bar_spacing) + 50;

echo "bar = ".$bar_spacing;
*/



/*******************************************
 Set up base image
 *******************************************/

//echo "h = ".$height ;
//echo "w = ".$width;
/*
// create a blank canvas
$im = imagecreatetruecolor($width,$height);
// Allocate colors
$white=imagecolorallocate($im,255,255,255);
$blue=imagecolorallocate($im,0,64,128);
$black=imagecolorallocate($im,0,0,0);
$pink = imagecolorallocate($im,255,78,243);
$text_color = $black;
$percent_color = $black;
$bg_color = $white;
$line_color = $white;
$bar_color = $blue;
$number_color = $pink;
// Create "canvas" to draw on
imagefill($im, 0, 0, $blue);
imagestring($im, 60, 200, 50, 'Olomrayaneh.net', $white);
//imagefilledrectangle($im,0,0,$width,$height,$bg_color);
// Draw outline around canvas
//imagerectangle($im,0,0,$width-1,$height-1,$line_color);
imagepolygon($im, $values, 3, $color);
// output image
Header ('Content-type: image/png');
imagepng ($im);
// clean up
imagedestroy($im);
*/

$width = 230;
$height = 500;

$im = imagecreatetruecolor($width, $height);
$white = ImageColorAllocate ($im, 255, 255, 255);
$blue = ImageColorAllocate ($im, 0, 0, 255);
// draw on image
imagefill($im, 0, 0, $blue);
imagestring($im, 60, 200, 50, 'Olomrayaneh.net', $white);
imageline($im, 10, 100, 490, 100, $white);
$color = ImageColorAllocate ($im, 255, 0, 0);
imageellipse($im, 250, 350, 300, 200, $color);
imageellipse($im, 250, 350, 200, 200, $color);
$values = array(
    250,  110, // Point 1 (x, y)
    50, 250,  // Point 2 (x, y)
    450,  250 // Point 3 (x, y)
);
imagepolygon($im, $values, 3, $color);
// output image
Header ('Content-type: image/png');
imagepng ($im);
// clean up
imagedestroy($im);









// Add title
/*
$title = 'Poll Results';
$title_dimensions = imagettfbbox($title_size, 0, $font, $title);
$title_length = $title_dimensions[2] - $title_dimensions[0];
$title_height = abs($title_dimensions[7] - $title_dimensions[1]);
$title_above_line = abs($title_dimensions[7]);
$title_x = ($width-$title_length)/2;  // center it in x
$title_y = ($y - $title_height)/2 + $title_above_line; // center in y gap
imagestring($im, $title_size, $title_x, $title_y,  $title, $text_color);
*/
// Draw a base line from a little above first bar location
// to a little below last
//imageline($im, $x, $y-5, $x, $height-15, $line_color);
/*******************************************
 Draw data into graph
 *******************************************/


/*




// Get each line of db data and draw corresponding bars
//while ($row = mysql_fetch_object ($result))
echo "out of while";

$query = 'select * from poll_results';
$result = $pdo->query($query);
/*
foreach ($result as $row ) {
    echo "n = ".$row['num_votes']."<br>";
}*/
//reset($result);
//$row = $result->fetch();
//echo $row['num_votes'];
/*
while ($row = $result->fetch()) 
{
    echo "iiiiiin while<br>";
    if ($total_votes > 0)
        $percent = intval(round(($row['num_votes']/$total_votes)*100));
    else
        $percent = 0;
    // display percent for this value
    imagestring($im, $main_size,  $width-30, $y+($bar_height/2),  $percent.'%',  $percent_color);
    if ($total_votes > 0)
         $right_value = intval(round(($row['num_votes'] / $total_votes)*100));
    else
         $right_value = 0;
    $bar_length = $x + ($right_value * $bar_unit);
    // draw bar for this value
    imagefilledrectangle($im, $x, $y-2, $bar_length, $y+$bar_height, $bar_color);
    // draw title for this value
    $ca = $row['candidate'];
    //ImageString($im, $main_size,  $text_indent, $y+($bar_height/2),    "$row->candidate", $text_color);
    imagestring($im, $main_size,  $text_indent, $y+($bar_height/2),    $ca, $text_color);
    // draw outline showing 100%
    imagerectangle($im, $bar_length+1, $y-2,  ($x+(100*$bar_unit)), $y+$bar_height, $line_color);
    // display numbers
    $num = $row['num_votes'];
    //  ImageString($im, $small_size, $x+(100*$bar_unit)-50, $y+($bar_height/2),    $row->num_votes.'/'.$total_votes, $number_color);
    imagestring($im, $small_size, $x+(100*$bar_unit)-50, $y+($bar_height/2), $num.'/'.$total_votes, $number_color);
   // move down to next bar
   $y = $y + ($bar_height+$bar_spacing);
}
/*
/*******************************************
 Display image
 *******************************************/
//header('Content-type:  image/png');//
//imagepng($im);
/*******************************************
 Clean up
 *******************************************/
imagedestroy($im);
?>


