<?php
class DailymailShell extends Shell {
	var $uses = array('User', 'Administrator', 'Timeline', 'Friend');

	function send(){
		//サマリーメールの受信希望ユーザーの取得（今はユーザーIDが1のユーザーに限定）
		//$users = $this->User->find('all', array('conditions' => array('User.????' => '1')));
		$users = $this->User->find('all', array('conditions' => array('User.USR_ID' => '1')));
		foreach($users as $user){
			$timeline_limit = 10;			//$user['User']['TL_LIMIT']		など
			$timeline_comment_limit = 5;	//$user['User']['TLM_LIMIT']	など

			//タイムラインの取得
			$conditions = array('conditions'=>
									array('AND' =>
	 									array('Timeline.USR_ID IN ( SELECT F_USR_ID FROM T_FRIEND WHERE USR_ID = '.$user['User']['USR_ID'].' )'),
	 											'Timeline.ACT_ID' => '1',
	 											'Timeline.LAST_DATE >' => date('Y-m-d')));
			$timeline_count = $this->Timeline->find('count', $conditions);
	 		$timeline = $this->Timeline->find('all', array_merge($conditions,	array('limit' => $timeline_limit)));
	 		//デバッグ用
			//print_r($timeline);
			//print_r($timeline_count);

			//メッセージ作成とメール送信
			App::import('Component', 'Qdmail');
			$mail = new QdmailComponent();
			//$mail->inlineMode(true);
			//$mail->attach('./img/i_logo.jpg');
			$mail->from('wakabayashi-r@icz.co.jp');

			//メールタイトル
			$subject = '本日'.date('Y年m月d日').'のサマリーメールテスト';
			//↓ここからメール本文
			$body = '<html><body>こんにちは、'.$user['User']['NAME'].'さん<br>
					本日('.date('Y年m月d日').')は、フォローしている人の発言が'.$timeline_count.'件ありました。<br><br>
					フォローしている人の本日の発言↓（新しい順）<br><br>';

			foreach ($timeline as $timeline_value) {
				$body = $body.'<b>'.$timeline_value['User']['NAME'].'</b>さんの'.date("H時i分",strtotime($timeline_value['Timeline']['LAST_DATE'])).'の発言<br>
						<blockquote>'.$timeline_value['Timeline']['MESSAGE'];
						//タイムラインのコメントの取得
						$conditions = array('conditions' =>
												array('AND'=>
													array('Timeline.ACT_ID' => '2',
															'Timeline.VAL_ID' => $timeline_value['Timeline']['TML_ID'])));
						$timeline_comments_count = $this->Timeline->find('count', $conditions);
						$timeline_comments = $this->Timeline->find('all', array_merge($conditions, array('order' => 'Timeline.INSERT_DATE ASC', 'limit' => $timeline_comment_limit)));


						$body = $body.'<blockquote>';
						foreach ($timeline_comments as $timeline_comment) {
							$body = $body.'<small><b>'.$timeline_comment['User']['NAME'].'</b>:'.$timeline_comment['Timeline']['MESSAGE'].'</small><br>';
						}

				$body = $body.'</blockquote></blockquote><hr>';
			}
			//$body = $body.'<img src="cid:i_logo.jpg">画像表示<br>';

			if($timeline_count > $timeline_limit){
				$body = $body.'<a href="https://invoice.icz.co.jp/~wakabayashi-r/sns/homes">すべての発言を見る</a>';
			}else{
				$body = $body.'以上です。';
			}
			$body = $body.'</body></html>';
			//↑ここまで

			$mail->subject($subject);
			$mail->html($body);
			$mail->to($user['User']['MAIL']);
			$mail->errorDisplay(true);

			$errormsg = $mail->send();

			print_r($errormsg);
		}
	}
}
?>