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

/*$DATABASE_HOST = '10.1.1.202:8080';
$DATABASE_USER = 'maabim';
$DATABASE_PASS = 'maabim001';
$DATABASE_NAME = 'phplogin';*/

include("sql.php");


try {
    $pdo = new PDO('sqlsrv:Server='.$hostname.';Database='.$dbname,$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 * FROM [21000X].[dbo].[User_Account] WHERE [user_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["user_password"]) {
        session_regenerate_id();
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['name'] = $row["user_account"];
        $_SESSION['id'] = $row["user_ID"];
        $_SESSION['check_word'] = '';
        echo 'success';
    } else {
        echo '密碼錯誤，請重新輸入';
    }
}
if ($i == 0) {
    echo '帳號不存在，請再次檢查';
}

$sth = null;
$pdo = null;
