<?php
	require("__include-common.php");
	require("../account/__logincheck.php");
	require("_my_calendar.php");
	require("input-include.php");
	if ($_POST) {
		post_done_proc();
	} else {
		if (INPUT_POPUP_CALENDAR == 'YUI') {
			$add_input_header = '_add_input_header_YUI.php';
		} else if (INPUT_POPUP_CALENDAR == 'kanaya') {
			$add_input_header = '_add_input_header-kanaya.php';
		} else {
			$add_input_header = '_add_input_header.php';
		}
		html_header(HTML_TITLE.' 伝言', $add_input_header, '#f8f8f8');
		page_header();
		contents_header('off');
		main_proc();
		page_footer();
		html_footer();
	}
	exit();
?>
<?php
function post_done_proc() {
	$msg_id[] = array();
	$con = my_mysqli_connect(_DB_SCHEMA);
	if (isset($_POST['to_id'])) {
		foreach ($_POST['to_id'] as $to_id) {
			$sql = "insert into m_message (from_id_account,to_id_account,c_message,c_registtime)";
			$sql .= " values ('".$_SESSION['login_id']."','".$to_id."','".str_for_mysql(form_str_adjust($_POST["message"]))."','".date("Y/m/d H:i:s")."')";
			my_mysqli_query($sql, "伝言登録でエラー。");
			$msg_id[$to_id] = my_mysqli_insert_id();
		}
	}
	if ($_POST['add_schedule'] == 'Y') {
		if ($_POST['inputY']) {
			$year = get_post_str("inputY");
		}
		if ($_POST['inputM']) {
			$month = get_post_str("inputM");
		}
		if ($_POST['inputD']) {
			$day = get_post_str("inputD");
		}
		if (!checkdate($month, $day, $year)) {
			error_exit("日付が不正", True);
		}
		$schedule_to_date = '';
		if ($_POST['inputToD'].'' <> '') {
			$to_year = get_post_str("inputToY");
			$to_month = get_post_str("inputToM");
			$to_day = get_post_str("inputToD");
			if (!checkdate($to_month, $to_day, $to_year)) {
				error_exit("日付範囲が不正", True);
			}
			$schedule_to_date = date("Y-m-d", mktime(0, 0, 0, $to_month, $to_day, $to_year));
			$s_date = mktime(0, 0, 0, $month, $day, $year);
			$e_date = mktime(0, 0, 0, $to_month, $to_day, $to_year);
			$scopeDay = ($e_date - $s_date) / (3600 * 24);
			if ($scopeDay < 0) {
				error_exit("日付範囲の前後が逆転", True);
			} elseif ($scopeDay == 0) {
				$schedule_to_date = "";
			} else {
				if ($_POST['repeat_type'] == 'week') {
					if ($scopeDay > 92) error_exit("日付範囲が3ヶ月以上", True);
				} else {
					if ($scopeDay > 31) error_exit("日付範囲が1ヶ月以上", True);
				}
			}
		}
		$schedule_date = date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
		if ($_POST['hh1'] <> "") {
			$time1 = "'2008-1-1 ".$_POST['hh1'].":".$_POST['mm1'].":00'";
		} else {
			$time1 = "NULL";
		}
		if ($_POST['hh2'] <> "") {
			$time2 = "'2008-1-1 ".$_POST['hh2'].":".$_POST['mm2'].":00'";
		} else {
			$time2 = "NULL";
		}
		if ($schedule_to_date == "") {
			$sql1 = "insert into m_schedule ";
			$sql1 .= "(id_account";
			$sql1 .= ", c_date";
			$sql1 .= ", c_subject";
			$sql1 .= ", c_memo";
			$sql1 .= ", c_memo_strip_tags";
			$sql1 .= ", c_map";
			$sql1 .= ", c_time1";
			$sql1 .= ", c_time2";
			$sql1 .= ", c_registtime";
			$sql1 .= ", c_updatetime";
			$sql1 .= ", add_id_account";
			$sql1 .= ") values ('";
			$sql2 = "', '".$schedule_date."'";
			$sql2 .= ", '".post_to_mysql('c_subject')."'";
			$sql2 .= ", '".post_to_mysql('c_memo')."'";
			$sql2 .= ", '".post_to_mysql_strip_tags("c_memo")."'";
			$sql2 .= ", '" . $_POST['c_map'] . "'";
			$sql2 .= ", ".$time1;
			$sql2 .= ", ".$time2;
			$sql2 .= ", '". date("Y/m/d H:i:s") . "'";
			$sql2 .= ", '". date("Y/m/d H:i:s") . "'";
			$sql2 .= ", '". $_SESSION['login_id'] . "'";
			$sql2 .= ")";
			if (isset($_POST['to_id'])) {
				foreach ($_POST['to_id'] as $to_id) {
					$sql = $sql1.$to_id.$sql2;
					my_mysqli_query($sql, "スケジュール登録でエラー。");
				}
			}
		} else {
			if (isset($_POST['to_id'])) {
				$scd_id[] = array();
				foreach ($_POST['to_id'] as $to_id) {
					$scd_id[$to_id] = 0;
				}
				if ($_POST['repeat_type'] == 'week') {
					$rep_add_day = 7;
				} else {
					$rep_add_day = 1;
				}
				for ($dd=0; $dd<=$scopeDay; $dd+=$rep_add_day) {
					$insert_date = date("Y-m-d", mktime(0, 0, 0, $month, $day+$dd, $year));
					$sql1 = "insert into m_schedule ";
					$sql1 .= "(id_account";
					$sql1 .= ", c_date";
					$sql1 .= ", id_group";
					$sql1 .= ", c_subject";
					$sql1 .= ", c_memo";
					$sql1 .= ", c_memo_strip_tags";
					$sql1 .= ", c_map";
					$sql1 .= ", c_time1";
					$sql1 .= ", c_time2";
					$sql1 .= ", c_registtime";
					$sql1 .= ", c_updatetime";
					$sql1 .= ", add_id_account";
					$sql1 .= ") values ('";
					$sql2 = "', '".$insert_date."', '";
					$sql3 = "', '".post_to_mysql('c_subject')."'";
					$sql3 .= ", '".post_to_mysql('c_memo')."'";
					$sql3 .= ", '".post_to_mysql_strip_tags('c_memo')."'";
					$sql3 .= ", '" . $_POST['c_map'] . "'";
					$sql3 .= ", ".$time1;
					$sql3 .= ", ".$time2;
					$sql3 .= ", '". date("Y/m/d H:i:s") . "'";
					$sql3 .= ", '". date("Y/m/d H:i:s") . "'";
					$sql3 .= ", '". $_SESSION['login_id'] . "'";
					$sql3 .= ")";
					foreach ($_POST['to_id'] as $to_id) {
						$sql = $sql1.$to_id.$sql2.$scd_id[$to_id].$sql3;
						my_mysqli_query($sql, "スケジュール登録でエラー。");
						// ****** 添付ファイル用＆グルーピング用 ******
						if ($scd_id[$to_id] == 0) {
							//直近のINSERTクエリによりAUTO_INCREMENTカラム用に生成されたIDを取得
							$scd_id[$to_id] = my_mysqli_insert_id();
							$sql = "update m_schedule set";
							$sql .= " id_group = '".$scd_id[$to_id]."'";
							$sql .= " where id_schedule = ".$scd_id[$to_id];
							my_mysqli_query($sql, "スケジュールgroup設定でエラー。");
						}
					}
				}
			}
		}
	}
	mysqli_close($con);
	if ($_POST['sendmail'] == 'Y') {
		$subject = '≪伝言≫ '.left_short($_POST["message"],40);
		$body = $_SESSION['login_handle']."さんから伝言がありました。\n\n";
		$body .= "≪伝言≫\n";
		$body .= $_POST["message"]."\n\n";
		$body .= "==================================\n";
		$body .= "このメールには返信しないで下さい。\n";
		$body .= "==================================\n";
		$header_from = _SENDMAIL_EMAIL_NAME.' <'._SENDMAIL_EMAIL_ADDR.'>';
		if (isset($_POST['to_id'])) {
			foreach ($_POST['to_id'] as $to_id) {
				$con_ac = my_mysqli_connect(_DB_ACCOUNT_SCHEMA);
				$sql_ac = "select c_handle,c_email_calendar from m_account where id_account = ".$to_id;
				$rs_ac = my_mysqli_query($sql_ac);
				$rec_ac = mysqli_fetch_array($rs_ac);
				if ($rec_ac['c_email_calendar'] <> '') {
					$send_body = $rec_ac['c_handle']."さんへ\n\n".$body;
					$ret = my_send_mail(_SENDMAIL_EMAIL_ADDR, $header_from, $rec_ac['c_email_calendar'], $subject, $send_body, _SENDMAIL_HOST, _SENDMAIL_PORT, _SENDMAIL_AUTH_USE, _SENDMAIL_EMAIL_USER, _SENDMAIL_EMAIL_PASS);
					if (!$ret) {
						error_msg("メール送信でエラーが発生しました。", True);
						echo '-----------------------------------<br>';
						echo ins_br($send_body);
						echo '-----------------------------------<br>';
						exit();
					}
					$send_f = 'S';
				} else {
					$send_f = 'N';
				}
				mysqli_close($con_ac);
				$con = my_mysqli_connect(_DB_SCHEMA);
				$sql = "update m_message set c_sendmail = '".$send_f."' where id_message = ".$msg_id[$to_id];
				my_mysqli_query($sql);
				mysqli_close($con);
			}
		}
	}
	redirect($_SERVER['SCRIPT_NAME']);
}
function main_proc() {
	$con = my_mysqli_connect(_DB_SCHEMA);
?>
<style>
div#main_body {
	margin: 10px 0 0 20px;
}
div#from_message h4 {
	width: 660px;
	color: #ffffff;
	background-color: #ff6347;
}
div#to_message h4 {
	width: 660px;
	color: #ffffff;
	background-color: #0087d1;
}
td.handle {
	color: #245CCC;
}
td.message {
	padding-left: 6px;
	width: 400px;
	color: #101010;
	word-break: break-all;
}
td.time {
	padding-left: 6px;
	color: #404040;
}
td.delete_btn {
	padding-left: 4px;
}
td.receive {
	padding-left: 4px;
}
span.received {
	color: blue;
	background: #ffffff;
}
span.unreceived {
	color: red;
	background: #ffffff;
}
span.sendmail {
	color: #ff8c00;
}
span.nosendmail {
	coloR: #DA70D6;
}
#form0 {
	margin: 8px 0 0 0;
}
.empty_msg {
	margin: 5px 10px;
	color: #808080;
}
table.input_form_table {
	border-collapse: collapse;	/* separate collapse */
}
table.input_form_table td {
	background-color: #ffffff;
	border: silver 1px solid;
}
div.images_button td {
	background-color: #ffffff;
	border-style: none;
}
</style>
<script>
function formCheck(form) {
	var to_checked = false;
	$("[name='to_id[]']:checked").each(function(){
		to_checked = true;
	});
	if (!to_checked) {
		window.alert('伝言の宛先を選択してください。');
		return false;
	}
	if (form.message.value == '') {
		window.alert('伝言が未記入です。');
		return false;
	}
	if (form.c_subject.value != '' || form.c_memo.value != '') {
		if (!form.add_schedule.checked) {
			window.alert('スケジュールの記入がありますが、「カレンダーに追加する」がチェックされていません。');
			return false;
		}
	}
	if (form.add_schedule.checked) {
		if (form.c_subject.value == '' && form.c_memo.value == '') {
			window.alert('「カレンダーに追加する」がチェックされていますが、スケジュールが見記入です。');
			return false;
		}
	}
	return true;
}
function delete_message(id) {
//	if (window.confirm('削除しますか？')) {
		$.ajax({
			type: "GET",
			url: "message-delete.php?id="+id,
			async: false,
			success: function(res){
				$('.msg_'+id).html('');
			}
		});
//	}
}
</script>
<div id="main_body">
<div id="from_message">
<h4>受信伝言</h4>
<?php
	from_message();
?>
</div>
<div id="to_message">
<h4>送信済み伝言</h4>
<?php
	to_message();
?>
</div>
<form method="POST" id="form0" name="form0" onSubmit="return formCheck(this)">
<div>宛先：
<?php
	for ($ix=0; $ix<=$_SESSION['login_friends_number']; $ix++) {
		$friends_id = $_SESSION['login_friends_id_'.$ix];
		// if ($friends_id <> $_SESSION['login_id']) {
?>
	<label><input type="checkbox" name="to_id[]" value="<?= $friends_id ?>"><?= $_SESSION['login_friends_handle_'.$friends_id] ?></label>
<?php
		// }
	}
?>
</div>
<textarea name="message" id="message" style="width:500px;" rows=4 wrap="soft"></textarea><br>
<input type="submit" value="伝言を送る">
<p>
<?php	if (_SCHEDULE_SENDMAIL_USE) { ?>
<label><input type="checkbox" name="sendmail" value="Y"> ↑ 電子メールでも上記伝言を送信する (相手がメールアドレスを登録しているユーザーのみ)</label><br>
<?php	} ?>
<label><input type="checkbox" name="add_schedule" value="Y"> ※ 伝言と同時に以下のスケジュールを宛先メンバのカレンダーに追加する</label>
</p>
<?php
	$year = date('Y');
	$month = date('m');
	$day = date('d');
?>
<?php if (TEXTAREA_HTML_USE == "YES") { ?>
<script src="../scripts/encloseTextArea.js"></script>
<script>
function encloseLink(s, e) {
	if(url = window.prompt("リンク先を入れてください。URL：", "")) {
		encloseTextArea('<a href="' + url + '" target="_blank">', '</a>', 'c_memo');
		htmlPreview();
	}
}
function enclosePreview(s, e) {
	encloseTextArea(s, e, 'c_memo');
	htmlPreview();
}
function htmlPreview() {
	document.getElementById('memo_html').innerHTML = htmlDecode(document.getElementById('c_memo').value).replace(/<icon /ig,"<img src=<?= IMAGES_FOLDER ?>/").replace(/\n/ig,"<br>").replace(/<m>/ig,"<span style=\"color: #008000\">[").replace(/<\/m>/ig,"]</span>");
}
function htmlDecode(str) {
	return str.replace(/&gt;/ig,">").replace(/&lt;/ig,"<").replace(/&nbsp;/ig,"");
}
</script>
<?php } ?>
<table class="input_form_table">
<tr>
	<td>日付</td>
	<td nowrap>
		<p>
			<input type="hidden" name="c_date_current" value="">
		<?php
			$endYY = date("Y") + 10;
			select_view_with_id("inputY", "年", _CALENDAR_SELECT_FIRST_YEAR, $endYY, $year);
			select_view_with_id("inputM", "月", 1, 12, $month);
			select_view_with_id("inputD", "日", 1, 31, $day);
		?>
		<?php	if (INPUT_POPUP_CALENDAR == 'YUI') { ?>
			<img src="../images/calendar.png" onclick="YahhoCal.render('inputY', 'inputM', 'inputD');">
		<?php	} else if (INPUT_POPUP_CALENDAR == 'kanaya') { ?>
			<img src="../images/calendar.png" onClick="wrtCalendar(event,document.form0.ymd1,'inputY','inputM','inputD');">
			<input type="hidden" name="ymd1" id="ymd1" value="">
		<?php	} else { ?>
			<a href="javascript:viewCalen(theMonth,'calenArea1','inputY','inputM','inputD'); void(0);"><img src="../images/calendar.png"></a>
			<span id="calenArea1" class="calenBox"></span>
		<?php	} ?>
		<?php
			if ($id == 0) {
		?>
		～
		<?
				$endYY = date("Y") + 10;
				select_view_with_id("inputToY", "年", _CALENDAR_SELECT_FIRST_YEAR, $endYY, $year);
				select_view_with_id("inputToM", "月", 1, 12, $month);
				select_view_with_id_with_blank("inputToD", "日", 1, 31, "");
		?>
		<?php 	if (INPUT_POPUP_CALENDAR == 'YUI') { ?>
			<img src="../images/calendar.png" onclick="YahhoCal.render('inputToY', 'inputToM', 'inputToD');">
		<?php	} else if (INPUT_POPUP_CALENDAR == 'kanaya') { ?>
			<img src="../images/calendar.png" onClick="wrtCalendar(event,document.form0.ymd2,'inputToY','inputToM','inputToD');">
			<input type="hidden" name="ymd2" id="ymd2" value="">
		<?php	} else { ?>
			<a href="javascript:viewCalen(theMonth,'calenArea2','inputToY','inputToM','inputToD'); void(0);"><img src="../images/calendar.png"></a>
			<span id="calenArea2" class="calenBox"></span>
		<?php	} ?>
		</p>
		<p>
			<label><input type="radio" name="repeat_type" value="all" checked>連続(1ヶ月以内)</label>
			<label><input type="radio" name="repeat_type" value="week">同じ曜日のみ(3ヶ月以内)</label>
		</p>
		<?php
			}
		?>
		</div>
	</td>
	<?php
		if (TEXTAREA_HTML_USE == "YES") {
			view_images_button(4);
		}
	?>
</tr>
<tr>
	<td nowrap>時間<br></td>
	<td>
	<?php
			select_time("hh1", "mm1", $hh1, $mm1);
			echo "～";
			select_time("hh2", "mm2", $hh2, $mm2);
	?>
	</td>
</tr>
<tr>
	<td>件名</td>
	<td>
		<input class="text" type="text" name="c_subject" size=40 value="<?= my_htmlspecialchars($subject) ?>">
		<label><input type="checkbox" name="c_map" value="1" style="margin-left: 10px;">地図</label>
	</td>
</tr>
<tr>
	<td nowrap>スケジュール<br>本文</td>
	<td id="input_memo" style="width:450px;">
	<div>
	<?php
		if (TEXTAREA_HTML_USE == "YES") {
			require(INPUT_COLOR_TAG);
			foreach ($color_tbl as $color) {
	?>
		<style>
		#input_memo input[type=button].c_<?= $color ?> {
			background-image: -moz-linear-gradient(top, <?= $color ?>, <?= $color ?>);
			background-image: -ms-linear-gradient(top, <?= $color ?>, <?= $color ?>);
			background-image: -webkit-gradient(linear, 0 0, 0 100%, from(<?= $color ?>), to(<?= $color ?>));
			background-image: -webkit-linear-gradient(top, <?= $color ?>, <?= $color ?>);
			background-image: -o-linear-gradient(top, <?= $color ?>, <?= $color ?>);
			background-image: linear-gradient(top, <?= $color ?>, <?= $color ?>);
			filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='<?= $color ?>', endColorstr='<?= $color ?>', GradientType=0);
		}
		</style>
		<input type="button" class="c_<?= $color ?>" value=" " style="margin: 0; padding: 0; height: 18px; width: 18px; background-color: <?= $color ?>; color: <?= $color ?>;" onClick="enclosePreview('<font color=<?= $color ?>>','</font>');return false;">
	<?php
			}
			if (!strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {	//IE以外
				$button_style = 'margin: 0 0 1px 0; padding: 0; line-height: 0.9;';
			}
	?>
		<input type="button" value="Ｂ" style="<?= $button_style ?> height: 18px; width: 18px; font-weight: bold; background-color: #f0f0f0;" onClick="enclosePreview('<b>','</b>');return false;">
		<input type="button" value="Ｉ" style="<?= $button_style ?> height: 18px; width: 18px; font-weight: bold; background-color: #f0f0f0;" onClick="enclosePreview('<i>','</i>');return false;">
		<input type="button" value="Ｓ" style="<?= $button_style ?> height: 18px; width: 18px; font-weight: bold; background-color: #f0f0f0; text-decoration: line-through ;" onClick="enclosePreview('<s>','</s>');return false;">
		<input type="button" value="大" style="<?= $button_style ?> height: 18px; width: 18px; font-weight: bold; background-color: #f0f0f0;" onClick="enclosePreview('<span style=\'font-size:large;\'>','</span>');return false;">
		<input type="button" value="地" style="<?= $button_style ?> height: 18px; width: 22px; font-weight: bold; background-color: #f0f0f0;" onClick="enclosePreview('<m>','</m>');return false;">
		<input type="button" value="Ｌ" style="<?= $button_style ?> height: 18px; width: 18px; font-weight: bold; background-color: #f0f0f0;" onClick="encloseLink();return false;">
	<?php
		}
	?>
	</div>
		<div class="block_left;clear:left;">
		<?php
			$str = my_htmlspecialchars($memo);
			$rows = textarea_rows($str, 430) + 1;
			if ($rows < 5) {
				$rows = 5;
			} elseif (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE") and $rows > 30) {
				$rows = 30;
			}
		?>
	<?php	if (TEXTAREA_HTML_USE == "YES") { ?>
		<textarea id="c_memo" name="c_memo" style="width:430px;" rows="<?= $rows ?>" wrap="soft" onkeyup="htmlPreview()"><?= $str ?></textarea>
	<?php	} else { ?>
		<textarea id="c_memo" name="c_memo" style="width:430px;" rows="<?= $rows ?>" wrap="soft"><?= $str ?></textarea>
	<?php	} ?>
		</div>
	<div id="memo_html" class="block">
	<?php	if (TEXTAREA_HTML_USE == "YES") { ?>
		<?= ins_br(my_schedule_decorate_preview($memo)) ?>
	<?php	} ?>
	</div>
	</td>
</tr>
</table>
</form>
</div>
<?php
	mysqli_close($con);
}
function from_message() {
	$sql = 'select * from v_message where to_id_account = '.$_SESSION['login_id'].' order by id_message desc';
	$rs = my_mysqli_query($sql);
	if (mysqli_num_rows($rs) == 0) {
		echo '<p class="empty_msg">※ 受信伝言はありません。</p>';
		return;
	}
	$sqlup = "update m_message set c_receivedtime = '".date("Y/m/d H:i:s")."' where to_id_account = ".$_SESSION['login_id'];
	my_mysqli_query($sqlup);
?>
	<table id="to_message_tbl">
<?php
	while ($rec=mysqli_fetch_array($rs)) {
		if ($rec['c_sendmail'] == 'S') {
			$sendmail = '&nbsp;<span class="sendmail">(メール済)</span>';
		} elseif ($rec['c_sendmail'] == 'N') {
			$sendmail = '&nbsp;<span class="nosendmail">(メール未送信)</span>';
		} else {
			$sendmail = '';
		}
?>
	<tr class="msg_<?= $rec['id_message'] ?>">
	<td class="handle">By: <?= my_htmlspecialchars($rec['from_c_handle']) ?></td>
	<td class="delete_btn"><button onclick="delete_message('<?= $rec['id_message'] ?>');">削除</button></td>
	<td class="message"><?= ins_atag_br($rec['c_message']) ?><?= $sendmail ?></td>
	<td class="time"><?= $rec['c_registtime'] ?></td>
	</tr>
<?php
	}
?>
	</table>
<?php
}
function to_message() {
	$sql = 'select * from v_message where from_id_account = '.$_SESSION['login_id'].' order by id_message desc';
	$rs = my_mysqli_query($sql);
	if (mysqli_num_rows($rs) == 0) {
		echo '<p class="empty_msg">※ 送信済み伝言はありません。</p>';
		return;
	}
?>
	<table id="to_message_tbl">
<?php
	while ($rec=mysqli_fetch_array($rs)) {
		if ($rec['c_receivedtime'] > $rec['c_registtime']) {
			$read = '<span class="received">既読</span>';
		} else {
			$read = '<span class="unreceived">未読</span>';
		}
		if ($rec['c_sendmail'] == 'S') {
			$sendmail = '&nbsp;<span class="sendmail">(メール済)</span>';
		} elseif ($rec['c_sendmail'] == 'N') {
			$sendmail = '&nbsp;<span class="nosendmail">(メール未送信)</span>';
		} else {
			$sendmail = '';
		}
?>
	<tr class="msg_<?= $rec['id_message'] ?>">
	<td class="handle">To: <?= my_htmlspecialchars($rec['to_c_handle']) ?></td>
	<td class="delete_btn"><button onclick="delete_message('<?= $rec['id_message'] ?>');">削除</button></td>
	<td class="receive"><?= $read ?></td>
	<td class="message"><?= ins_atag_br($rec['c_message']) ?><?= $sendmail ?></td>
	<td class="time"><?= $rec['c_registtime'] ?></td>
	</tr>
<?php
	}
?>
	</table>
<?php
}
?>
