<?php
session_start();
session_regenerate_id(true);  //create a new session id to prevent hijacking

define('BASEPATH', true); //access connection script if you omit this line file will be blank
require_once './config.php';
$dbHandler = DbHandler();


if (isset($_POST['submit'])) {

    //ensure fields are not empty
    $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
    $passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null;

    //Retrieve the user account information for the given username.
    $sql = "SELECT id, username, password FROM tbl_administrator WHERE username = :username";
    $stmt = $dbHandler->prepare($sql);

    //Bind value.
    $stmt->bindValue(':username', $username);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    //If $row is FALSE.
    if ($user === false) {
        echo '<script>alert("invalid username or password")</script>';
    } else {
        //Compare and decrypt passwords.
        $validPassword = password_verify($passwordAttempt, $user['password']);

        //If $validPassword is TRUE, the login has been successful.
        if ($validPassword) {
            //Provide the user with a login session.
            // $_SESSION = [
            //     'id' => $row['id'],
            //     'username' => $row['username']
            // ];
            $_SESSION['admin'] = $username;
            $_SESSION['time_start_login'] = time();
            echo '<script>window.location.replace("./Blog/blog-manager");</script>';
            exit;
        } else {
            //$validPassword was FALSE. Passwords do not match.
            echo '<script>alert("invalid username or password")</script>';
        }
    }
}
