<?php
session_start();
if ((empty($_SESSION['check_word'])) || (empty($_POST['captcha']))) {
    die("請填寫驗證碼");    
}else{
    if ($_SESSION['check_word'] != $_POST['captcha']) {
        die("驗證碼錯誤，請重新輸入");
    }
}
include("sql_detail.php");


try {
    $pdo = new PDO('sqlsrv:Server='.$hostname.';Database='.$db_name,$username,$password);
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e;
    echo json_encode('Error connecting to the server.');
    die ();
}
$sth = $pdo->prepare("SELECT [UserID],[UserName],[DepartmentID],[Email],[Account],[Password] FROM [User] WHERE [Account] = ?;");
$sth->execute(array($_POST['username']));

if (!isset($_POST['username'], $_POST['password'])) {
    exit('Please fill both the username and password fields!');
}
$i = 0;

$query = $sth->fetchAll();
foreach ($query as $row){
    $i++;
    if (md5($_POST['password']) == $row["Password"]) {
        session_regenerate_id();
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['name'] = $row["UserName"];
        $_SESSION['UserID'] = $row["UserID"];
        $_SESSION['Account'] = $row["Account"];
        $_SESSION['Email'] = $row["Email"];
        $_SESSION['DepartmentID'] = $row["DepartmentID"];
        $_SESSION['check_word'] = '';
        echo 'success';
    } else {
        echo '密碼錯誤，請重新輸入';
    }
}
if ($i == 0) {
    echo '帳號不存在，請再次檢查';
}

$sth = null;
$pdo = null;
