#!/usr/local/bin/perl

#┌────────────────────────
#│ cart.cgi - 2006/01/23
#│ Copyright (c) KentWeb
#└────────────────────────

# 外部ファイル取り込み
require './cart_init.cgi';

# 基本処理定義
&decode(0);
if ($mode eq "change") { &change; }
elsif ($mode eq "note") { &note; }
elsif ($mode eq "check") { &check; }
&pickup;

#-------------------------------------------------
#  カゴ入れ
#-------------------------------------------------
sub pickup {
	local($flag,$id,$code,$num,$size,$col,@new);

	$in{'num'} = &num_z2h($in{'num'});
	$in{'size'}  =~ s/:/：/g;
	$in{'size'}  =~ s/;/；/g;
	$in{'color'} =~ s/:/：/g;
	$in{'color'} =~ s/;/；/g;

	# BACK属性がなければ、HTTP_REFERERで取得
	if (!$in{'back'}) { $in{'back'} = $ENV{'HTTP_REFERER'}; }

	# 登録データ認識
	&get_data;

	# コード & 個数が共に無しの場合は「中身確認」
	if ($in{'code'} eq "" && $in{'num'} eq "") {

		# 在庫チェック
		if ($stock) {
			local($code,$zan);

			undef(%zan);
			open(IN,"$stkfile") || &error("Open Error: $stkfile");
			while (<IN>) {
				($code,$zan) = split(/<>/);

				$zan{$code} = $zan;
			}
			close(IN);
		}

		@cook = &get_cookie($cookieID);
		&basket(@cook);

	# 商品コードのみ無しはエラー
	} elsif ($in{'code'} eq "" && $in{'num'}) {
		&error("商品コードが不正です");

	# 商品個数のみ無しはエラー
	} elsif ($in{'code'} && $in{'num'} eq "") {
		&error("商品個数がありません");
	}

	# 商品コードの登録チェック
	if (!defined($cart{"$in{'code'}"})) {
		&error("商品コード「$in{'code'}」は登録されていないデータです。<br>管理者へお問い合わせください。");
	}

	# 在庫チェック
	if ($stock) {
		local($code,$zan);

		# ロック開始
		&lock if ($lockkey);

		$flag=0;
		undef(%zan);
		open(IN,"$stkfile") || &error("Open Error: $stkfile");
		while (<IN>) {
			($code,$zan) = split(/<>/);

			$zan{$code} = $zan;
			if ($code eq $in{'code'}) { $flag++; }
		}
		close(IN);

		# ロック解除
		&unlock if ($lockkey);

		if (!$flag) { &error("この商品は在庫数が未定義です"); }
		if ($zan{$in{'code'}} - $in{'num'} < 0) {
			&error("誠に申\し訳ありません。<br>現在この商品は在庫切れです(現在の在庫数:<b>$zan{$in{'code'}}</b>)");
		}
	}

	# クッキー取得
	@cook = &get_cookie($cookieID);

	# 重複チェック
	$flag=0; @new=();
	foreach (@cook) {
		($id,$code,$num,$size,$col) = split(/,/);

		# 要素が同じ場合は数量を足しこむ（重複する場合）
		if ($in{'code'} eq $code && $in{'size'} eq $size && $in{'color'} eq $col) {

			$flag++;
			$num += $in{'num'};

			# 在庫チェック
			if ($stock) {
				if ($zan{$in{'code'}} - $num < 0) {
					&error("誠に申\し訳ありません。<br>現在この商品は在庫切れです(現在の在庫数:<b>$zan{$in{'code'}}</b>)");
				}
			}

			$_ = "$id,$code,$num,$size,$col";
		}
		push(@new,$_);
	}
	@cook = @new;

	# 重複がなければ追加
	if (!$flag) {
		# 識別番号を発行
		($id) = split(/,/, $cook[0]);
		$id++;

		# クッキー追加
		@cook = ("$id,$in{'code'},$in{'num'},$in{'size'},$in{'color'}", @cook);
	}

	# クッキー格納
	&set_cookie(@cook);

	# カゴ確認画面
	&basket(@cook);
}

#-------------------------------------------------
#  カゴ画面表示
#-------------------------------------------------
sub basket {
	local(@cook) = @_;

	&header;
	print <<EOM;
[ <a href="$home" target="_top">ショッピングページのトップ（一般）へ戻る</a> ]
<br>
<div align="center">
<table><tr><td>
<ul>
<li><b>買物カゴの中身は以下のとおりです.</b>
<li>消費税や送料が別途かかる場合には最終確認画面で表\示されます.
<li>数量を変更する場合はプルダウンから変更ボタンを押してください.

</ul>
$AdComment
</td></tr></table>
<p>
EOM

	# 買物カゴの中身
	&cart_tbl('basket');

	# 中身がない場合
	if (@cook == 0) {
		print "<p><form>\n";

		if ($in{'back'}) {
			print "<input type=button value=\"買物を続ける\" onclick=window.open(\"$in{'back'}\",\"_self\")>\n";
		} else {
			print "<input type=button value=\"前画面に戻る\" onclick=\"history.back()\">\n";
		}

		print "</form></div>\n";
		print "</body></html>\n";
		exit;
	}

	print <<EOM;
<p>
<form action="$order" method="post">
<input type=hidden name=mode value="addr">
<input type=hidden name=back value="$in{'back'}">
EOM

	foreach (@cook) {
		s/;/；/g;
		($id,$code,$num,$size,$col) = split(/,/);

		print "<input type=hidden name=cart value=\"$id;$code;$num;$size;$col\">\n";
	}

	print <<EOM;
<table cellpadding="5" border="0">
<tr>
  <td valign="top">
	<input type="button" value="&lt; 買物を続ける" style="width:120px" onclick=window.open(\"$in{'back'}\",\"_self\")>
  </td>
  <td valign="top">
	<input type="submit" style="width:120px" value="注文画面へ &gt;">
  </td>
</tr>
</table>
</form>
</div>
</body>
</html>
EOM
	exit;
}

#-------------------------------------------------
#  カート内容変更
#-------------------------------------------------
sub change {
	local($chg_num,$del_num);
	foreach ( keys(%in) ) {
		if (/^chg:(\d+)/) {
			$chg_num = $1;
			last;
		} elsif (/^del:(\d+)/) {
			$del_num = $1;
			last;
		}
	}

	# 在庫チェック
	if ($stock) {
		local($code,$zan);

		undef(%zan);
		open(IN,"$stkfile") || &error("Open Error: $stkfile");
		while (<IN>) {
			($code,$zan) = split(/<>/);

			$zan{$code} = $zan;
		}
		close(IN);
	}

	# クッキー取得
	local(@get) = &get_cookie($cookieID);

	@cook=();
	foreach (@get) {
		($id,$code,$num,$size,$col) = split(/,/);

		# 変更
		if ($chg_num eq $id) {
			$_ = "$id,$code,$in{\"num:$id\"},$size,$col";
		# 削除
		} elsif ($del_num eq $id) {
			next;
		}
		push(@cook,$_);
	}

	# クッキー格納
	&set_cookie(@cook);

	# 買物カゴ
	&get_data;
	&basket(@cook);
}

#-------------------------------------------------
#  数字半角変換
#-------------------------------------------------
sub num_z2h {
	local($_) = @_;

	s/０/0/g;
	s/１/1/g;
	s/２/2/g;
	s/３/3/g;
	s/４/4/g;
	s/５/5/g;
	s/６/6/g;
	s/７/7/g;
	s/８/8/g;
	s/９/9/g;
	$_;
}

#-------------------------------------------------
#  チェックモード
#-------------------------------------------------
sub check {
	&header;
	print <<EOM;
<h3>Check Mode</h3>
<ul>
EOM

	# ログ
	local(%log) = ('登録データ', $datfile, '在庫データ', $stkfile);
	while ( ($k,$v) = each(%log) ) {
		if (-e $v) {
			print "<li>$kパス: OK\n";

			if (-r $v && -w $v) {
				print "<li>$kパーミッション: OK\n";
			} else {
				print "<li>$kパーミッション: NG → $v\n";
			}
		} else {
			print "<li>$kパス: NG → $v\n";
		}
	}

	# sendmailパス
	if (-e $sendmail) {
		print "<li>sendmailパス: OK\n";
	} else {
		print "<li>sendmailパス: NG → $sendmail\n";
	}

	print <<EOM;
<li>バージョン: $ver
</ul>
</body>
</html>
EOM
	exit;
}


__END__

