<?php
require_once 'config.php';
$session = $facebook->getSession();
$me = null;
if ($session) {
  try {
    $me = $facebook->api('/me');  /*Check whether the current session is valid by retrieving user information.*/
  }
  catch (Exception $e) {
  }
}
/* If the current session is invalid or user has not authorized the application then redirect to a authorization URL.*/
if(!($me)) {
  echo '<script>
    top.location.href="' 
    . $facebook->getLoginUrl(
        array(
          'req_perms' => 'publish_stream,friends_birthday',
          'next' => 
            'http://apps.facebook.com/[your_app_url]/',
        )
      ) 
    . '";
    </script>';
  exit;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
</head>
<body>
<?php if(!isset($_REQUEST['selection'])) : ?>
<form name="myForm" onsubmit="http://apps.facebook.com/[your_app_url]/ ">
  <select size="1" name="selection">
    <option value="1"> Jan </option>
    <option value="2"> Feb</option>
    <option value="3"> Mar </option>
    <option value="4"> Apr </option>
    <option value="5"> May</option>
    <option value="6"> Jun </option>
    <option value="7"> Jul </option>
    <option value="8"> Aug</option>
    <option value="9"> Sep </option>
    <option value="10"> Oct</option>
    <option value="11"> Nov </option>
    <option value="12"> Dec </option>
  </select>

  <input type="submit" name="submit" value="Go !" />
</form>
<?php 
  exit;
  endif; 
?>
<?php

$month = $_REQUEST['selection'];

$friends = $facebook->api(array('method' => 'fql.query',  'query' => "SELECT birthday_date, name, uid, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1= me())"));

$ordered_friends = array();

foreach($friends as $friend){
  if(isset($friend['birthday_date'])){

    $dt = split("/",$friend['birthday_date']);

      if($dt[0] == $month){
        $ordered_friends[ltrim($dt[1],'0')][] = $friend;
      }
  } 
}

$last_day = date("d", strtotime("-1 day", strtotime(date("Y-" . ($month+1) . "-01"))));

$image = imagecreatetruecolor(450, 700);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$orange = imagecolorallocate($image, 0xF5, 0xA9, 0x53);

$bg = imagecreatefromjpeg('./app2_bg.jpg');

imagesettile($image, $bg);

imagefilledrectangle($image, 0, 0, 450, 700, IMG_COLOR_TILED);
imagedestroy($bg);

$font_file = './TURNBB__.TTF';
imagefttext($image, 16, 0, 15, 50, $orange, $font_file, 'Friends Birthday Calender');
imagefttext($image, 16, 0, 150, 80, $orange, $font_file, date("F", strtotime(date("Y-" . ($month) . "-01"))));
$day = 1;

for($i=0;$i<ceil($last_day/5);$i++) {
  for($j=0;$j<5&&$day<=$last_day;$j++,$day++) {
    imagefilledrectangle($image, 30+($j*80), 100+($i*80), 30+($j*80+70), 100+($i*80+70), $white);
    imagefttext($image, 22, 45, 40+($j*80+15), 150+($i*80+15), $orange, $font_file, $day);   
    if(count($ordered_friends[$day])) {
      for($col=1;count($ordered_friends[$day])>($col*$col);$col++);
      $side = 50;
      $cell_side = floor($side/$col);
      for($count=0;$count<count($ordered_friends[$day]);$count++) {
        $image_p = imagecreatetruecolor($cell_side, $cell_side);
        $image_o = imagecreatefromstring(file_get_contents($ordered_friends[$day][$count]['pic_square']));
        imagecopyresized($image_p, $image_o, 0, 0, 0, 0, $cell_side, $cell_side, $side, $side);
        $des_x = 30+($j*80)+(5*(($count%$col)+1)+(($count%$col)*$cell_side));
        $des_y = 100+($i*80)+(5*(floor($count/$col)+1)+(floor($count/$col)*$cell_side));
        imagecopymerge($image,$image_p,$des_x,$des_y,0,0,$cell_side,$cell_side,100);
        imagedestroy($image_p);
        imagedestroy($image_o);
      }
    }
  }
}


imagepng($image, './img/' . $me['id'] . '.png');

$pic = realpath("/home/botskoco/public_html/cookbook/img/" . $me['id'] . '.png');
$facebook->setFileUploadSupport("http://" . $_SERVER['SERVER_NAME']);
$pic_id = $facebook->api('/me/photos', 'POST', array('message' => $message
);

imagedestroy($image);
?>


  <div id="fb-root">
    <!-- Your application content here -->     
    <img src="./img/<?php echo $me['id']; ?>.png" />

  </div>
<script type="text/javascript">
  window.fbAsyncInit = function() {
    FB.init({
      appId  : '<?php echo $facebook->getAppId(); ?>', 
      status : true, 
      cookie : true, 
      xfbml  : true
    });
    $(document).ready(function() {
      

    });
  };
  (function() {
    var e = document.createElement('script');
    e.type = 'text/javascript';
    e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

</body>
</html>
