#!/usr/bin/env ruby32
# -*- coding: utf-8 -*-
require 'cgi'
require 'csv'
require 'sqlite3'
require 'nkf'
require './duetime'

close_after = $due = DueTime.new.due
UNIQUE = ["email", "hiraname"]

myname	= File.basename($0)
admin = "jd-entry@e.koeki-u.ac.jp"
admin = sprintf("%s <%s>", NKF.nkf('-jM', "ジュニアドクター鳥海塾申請受付"), admin)
rcpt = if /koeki-prj\.org/ =~ ENV["SERVER_NAME"]
         "jd-submit@e.koeki-u.ac.jp"
       else
         "yuuji@es.gentei.org"
       end

=begin
params = {
  "pref" => "都道府県", "schoolid" => "学校番号", "schoolname" => "学校名",
  "hiraname" => "ふりがな", "fm" => "性別", "name" => "氏名",
  "birthday" => "生年月日",
  "pname" => "保護者名", "phiragana" => "ほごしゃめい",
  "grade" => "学年", "class" => "クラス", "seatnum" => "出席番号",
  "address" => "住所", "phone" => "電話番号", "email" => "email",
  "transport" => "交通手段", "clubs" => "課外活動",
  "motive" => "応募の動機", "interest" => "科学的興味",
  "contest" => "コンテスト等参加歴", "issues" => "地域課題意識",
  "selfintro" => "自己紹介"
}
# grep name= appform.html | sed -E 's/.*name="([^"]*)".*/\1/'|uniq 
for k, v in params
  printf("<h2>%s</h2>\n<p class=\"answer\">\n__%s__\n</p>\n",
         v, k.upcase)
end; exit
# ./appjd.rb > mailtmpl.txt
=end

header = <<_EOS_
<!DOCTYPE html>
<head><title>Junior Doctor Chokai Academy Application</title>
<link rel="stylesheet" type="text/css" href="../jdmain.css">
</head>
<body>
<main>
_EOS_
footer = "<p><a href=\"./#{myname}\">もどる</a></p>
</main></body>\n"

sent = <<_EOF_
<h1>送信完了</h1>
<p>以下の内容でジュニアドクター鳥海塾申請書を送信しました。</p>
_EOF_

c = CGI.new(:accept_charset => "UTF-8")
print "Content-type: text/html; charset=UTF-8\n\n"
print header

if Time.now > close_after
  print(<<~EOF)
	<h2>募集終了</h2>
	<p>応募者数が審査できる上限に達したため
        応募を締め切りました。</p>
        <p>ジュニアドクター鳥海塾は5ヶ年事業です。
        次年度になりましたら、また募集いたしますので
        ぜひご応募ください。</p>
	EOF
  print footer
  exit 0
end

email = c["email"].read.gsub("'", "").gsub('"', "").gsub(/\s/, "")
name  = c["pname"].read.strip
from = ""

sj = NKF.nkf('-jM', "申請書").strip
fr = NKF.nkf('-jM', name).strip
from = sprintf("%s <%s>", fr, email)

# For recievers
body = open("mailtmpl.txt"){|tp| tp.read}.force_encoding('utf-8')
body.gsub!(/__(\w+)__/){|k| CGI.escapeHTML(c[$1.downcase].read)}

# For applicant
table = open("mailtmpl.html"){|h| h.read}.force_encoding('utf-8')
table.gsub!(/__(\w+)__/) {|k|
  CGI.escapeHTML(NKF.nkf('-wZ', c[$1.downcase].read))
}



require "tmpdir"
Dir.mktmpdir {|tmp|
  grade = c["grade"].read.sub("小", "E").sub("中", "J")
  uid = [c["schoolid"], grade, c["class"], c["seatnum"]].join("-")
  file=""
  if c["recfile"].original_filename > "" then
    of = c["recfile"].original_filename
    ext = File.extname(of)
    bn =  uid + ext
    file = File.expand_path(bn, tmp)
    open(file, "w"){|o| o.binmode; o.write c["recfile"].read}
    table.gsub!(/::FILE::/,
                sprintf("%dバイトの%sファイル",
                        c["recfile"].size, ext.sub(".", "").upcase))
  else
    table.gsub!(/::FILE::/, "なし")
  end
  csv = File.expand_path(uid+".csv", tmp)
  CSV.open(csv, "w") do |data|
    keys = c.params.keys.reject {|x|
      ["nptn", "school", "recfile", "submit"].index(x)
    }
    data << keys
    addition = keys.collect{|k| NKF.nkf('-wZ', c.params[k][0])}
    data << addition
    if test(?w, "db") then
      dbf = "db/app.sq3"
      csv = "db/app.csv"
      siz = test(?s, dbf)
      db = SQLite3::Database.new(dbf)
      db.busy_timeout = 3000
      begin
        if siz==nil then            # Create initial table
          cols = keys.join(",")
          uniq = UNIQUE.join(",")
          db.execute(<<~EOF)
	CREATE TABLE IF NOT EXISTS
	applicants(#{cols}, UNIQUE(#{uniq}))
	EOF
        end
        phs = Array.new(keys.length, "?").join(",")	# -> "?,?,?,?,?"
        db.execute(<<~EOF, *addition)
	REPLACE INTO applicants VALUES(#{phs})
	EOF
        # Create csv
        db.close
      rescue
        STDERR.puts "#{Time.now} SQL error"
        STDERR.printf("phs=%s\n", phs.inspect)
      end
      email.gsub("'", "")
      if true then
        CSV.open(csv, "w", force_quotes: true) do |c|
          c << keys
          c << addition
        end
      else
        system(<<~EOF)
	sqlite3 -header -csv #{dbf} "SELECT * FROM applicants WHERE email='#{email}'" > #{csv}
	EOF
      end
    end
  end
  # Send to admin
  cmd = "| ./sendmultipart.sh -t #{rcpt} -s '#{sj}' -f '#{from}' '#{csv}'"
  cmd += " '#{file}'" if file > ""
  open(cmd, "w") do |m|
    m.print NKF.nkf('-wZ0', body)
  end
  # Send to submitter
  sj = NKF.nkf('-jM', "ジュニアドクター鳥海塾(#{$due.year})申請書の写し").strip
  cmd = "| ./sendmultipart.sh -t #{email} -s '#{sj}' -f '#{admin}'"
  open(cmd, "w") do |m|
    m.print "以下の内容で申請しました:\n\n"
    m.print NKF.nkf('-wZ0', body)
  end
}

print sent
print table
print footer
