#!/usr/bin/env ruby25
# coding: utf-8
Encoding.default_external = "UTF-8"
require 'kconv'
require 'cgi'
require 'csv'
require 'nkf'

$entry = Hash.new		# All input values

def cat(file)
  print IO.readlines(file).join
end

def cat_message(file)
  IO.readlines(file).join.gsub(/__[A-Z_]+__/){|w| $entry.fetch(w, "")}
end

def sendmail(command, text)
  open(command, "w") do |mail|
    mail.print text.tojis
  end
end

print "Content-type: text/html; charset=utf-8\n\n"
cat("../header2.html")

if Time.now.strftime("%F") > "2019-07-13"
  puts "<p>2019年度申し込みは締め切りました。どうもありがとうございました。</p>"
  cat("../footer.html")
  exit 0
end

begin
  c = CGI.new(:accept_charset => "UTF-8")

  for n in %w(name ruby sei email telephone address school grade class number appeal message check ref_num remail remail) do
    key = "__" + n.upcase + "__"	# "name" -> "__NAME__"
    $entry[key] = c[n].strip
  end
  submit_c = c["send"].strip
  check_c = c["check"].strip
  remail_c = c["remail"].strip

  # Collect elementary school names.  Read as numbers and convert to Hash
  # 1,琢成小学校 -> {1 => "琢成小学校"}
  $school= CSV.read("school.csv", {converters: :numeric}).to_h
  # -> <option value="01">琢成小学校</option>
  $entry["__SCHOOL_OPTION__"] =
    '<option value="">-- 以下一覧から選択 --</option>' + "\n" +
    $school.collect {|n, s|
    sprintf('<option value="%02d">%s</option>', n, s)
  }.join("\n")

  if submit_c == ""
    print cat_message("../form-initial2.html")

  else
    sni = $entry["__SCHOOL__"].to_i
    school_num = sprintf("%02d", sni)
    $entry["__SCHOOL_NAME__"] = $school[sni] || "備考記載"

    if submit_c == "1"
      if remail_c > ""
        $entry["__EMAIL__"] = remail_c
      end
      email = $entry["__EMAIL__"]
      sj = NKF.nkf('-jM', "Rubyてらこった テストメール")
      sendmail_test = "| Mail -s '#{sj}' " + email
      m = cat_message("../send_test2.txt")
      ENV["QMAILUSER"]="terakotta"
      ENV["QMAILHOST"]="e.koeki-u.ac.jp"
      t=Thread.new do
        sendmail(sendmail_test, m)
      end
      puts"<h2>確認画面</h2>"
      print cat_message("../form-confirm2.html")
      t.join

    elsif submit_c == "2"
      if check_c == ""
        puts"<h2>確認画面</h2>"
        puts"<p><em>テストメールを確認したらチェックボックスにチェックをつけてください。</em></p>"
        print cat_message("../form-confirm2.html")
      else

        if $entry["__SEI__"] == "男"
          sei_num = "1"
        else
          sei_num = "2"
        end

        case $entry["__GRADE__"]
        when /5/
          grade_num = "5"
        else
          grade_num = "6"
        end

        case $entry["__CLASS__"]
        when /\S*(\d{1})\S*/
          class_num = $1
        else
          class_num = "1"
        end

        case $entry["__NUMBER__"]
        when /\S*(\d+)\S*/
          number_num = sprintf("%02d", $1.to_i % 10)
        else
          number_num = "99"
        end

        # case $schedule_c
        # when /^A/
        #   sch = "A"
        # else
        #   sch = "B"
        # end

        $entry["__REF_NUM__"] =
          if school_num == "99"
            require 'digest/md5'
            "0"+sei_num+Digest::MD5.hexdigest($entry["__EMAIL__"])[0,6]
          else
            sei_num + school_num + grade_num + class_num + number_num
          end
        # host = "terakotta@e.koeki-u.ac.jp"
        host = "terakotta-app@e.koeki-u.ac.jp"
        sj = NKF.nkf('-jM', 'Rubyてらこった お申し込み完了メール')
        sendmail_app = "| Mail -s '#{sj}' " + $entry["__EMAIL__"]
        sj = NKF.nkf('-jM', 'Rubyてらこった申込(%s)' % $entry["__NAME__"])
        sendmail_host = "| Mail -s '#{sj}' " + host
        m1 = cat_message("../send_app2.txt")
        m2 = cat_message("../send_host2.txt")
        ENV["QMAILUSER"]="terakotta"
        ENV["QMAILHOST"]="e.koeki-u.ac.jp"
        t=Thread.new do
          sendmail(sendmail_app, m1)
          sendmail(sendmail_host, m2)
        end

        print cat_message("../form-submit2.html")
        t.join
      end
    else
      cat "../error2.html"
    end
  end

rescue
  cat "../error2.html"
end
