#!/usr/bin/perl

use strict;
use DBI;
use CGI;
use Jcode;
use Template;
use jus::dvd;

use constant JUS_TEMPLATE_PATH => './../templates';

sub nendo {

    my @date = (localtime)[5,4];
    $date[0] += 1900;
    $date[1]++;

    $date[0]-- if ( $date[1] < 8);
    $date[0];
}

sub exp_date { sprintf "%04d-06-01",  nendo; }


print "Content-Type: text/html; charset=EUC-JP\n\n";

my $query = CGI->new();
my ($number, $type, $html_file);
my $sendmail = '/usr/sbin/sendmail';

my $member_info;
$html_file = 'passwd.txt';
my $handle = jus::dvd::openDB('jusdb');
if ($query->param('number') ne undef) {
    ($number, $type) = getID($query);
    if ($member_info = existID($handle, $number, $type)) {
	$html_file = 'passwd2.txt';
        send_pass($member_info, $sendmail);
    } else {
        $member_info->{message} = '<font color=red>指定された会員番号に誤りがあります。もう一度確認してください</font>';
    }
}

jus::dvd::closeDB($handle);
my %cgi;
$cgi{$_} = jus::dvd::escape_html($query->param($_)) foreach ($query->param());

my $template = Template->new({ INCLUDE_PATH => JUS_TEMPLATE_PATH });
$template->process(
     $html_file,
     {
	info => $member_info,
        cgi  => \%cgi,
        n    => nendo,
     }
);

exit;

sub existID {

    my $handle = shift;
    my $number = shift;
    my $type   = shift;

    my $sql = 'select * from members where number = ? and type = ? and exp_date > ?';
    $sql = $handle->prepare($sql);
    my $num = $sql->execute($number, $type, exp_date );
    return undef if ($num == 0);

    my $result = $sql->fetchrow_hashref();
    $sql->finish();

    $sql = 'select * from active where number = ? and year = ?';
    $sql = $handle->prepare($sql);
    $sql->execute($number, nendo);
    my $pass = $sql->fetchrow_hashref();
    $sql->finish();

    $result->{password} = $pass->{password};
    $result;
}

sub getID {
    my $query = shift;

    my $ID = $query->param('number');
    my ($number, $type);
    $ID =~ /^(\d{5})(\w)$/;
    ($number, $type) = ($1, $2);
}

sub send_pass {

    my $info = shift;
    my $sendmail = shift;
    my $mail_body;
    my $template = Template->new({INCLUDE_PATH => JUS_TEMPLATE_PATH});
    $template->process(
          'passwd_send.txt',
          { info => $info, n => nendo },
          \$mail_body
    );

    $mail_body = Jcode->new($mail_body)->jis();

    open MAIL, "| $sendmail -f office\@jus.or.jp -- $info->{email}";
    print MAIL $mail_body;
    close MAIL;

}

