<!DOCTYPE HTML>
<?PHP
session_start();

// 1. Include the connection file
require_once 'db_connect.php'; 

// 2. Map the $conn from db_connect.php to $db_link
$db_link = $conn; 

// 3. Include functions
require_once 'functions.php'; 

// Check if functions exist
$fingerprint = function_exists('fingerprint') ? fingerprint() : 'unknown';

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

    // Include password pepper
    if (file_exists('config/pepper.php')) {
        require 'config/pepper.php';
    } else {
        $pepper = ""; 
    }

    // Sanitize user input
    $log_user = sanitize($db_link, $_POST['log_user']);
    $log_pw = sanitize($db_link, $_POST['log_pw']);

    // Select user details
    $sql_log = "SELECT * FROM user, ugroup WHERE user.ugroup_id = ugroup.ugroup_id AND user_name = '$log_user'";
    $query_log = mysqli_query($db_link, $sql_log);
    
    checkSQL($db_link, $query_log);
    
    $result_log = mysqli_fetch_assoc($query_log);

    // Verify Password
    if($result_log && password_verify($log_pw.$pepper, $result_log['user_pw'])){

        // Define Session Variables
        $_SESSION['log_user'] = $log_user;
        $_SESSION['log_time'] = time();
        $_SESSION['log_id'] = $result_log['user_id'];
        $_SESSION['log_ugroup'] = $result_log['ugroup_name'];
        $_SESSION['log_admin'] = $result_log['ugroup_admin'];
        $_SESSION['log_delete'] = $result_log['ugroup_delete'];
        $_SESSION['log_report'] = $result_log['ugroup_report'];
        $_SESSION['log_fingerprint'] = $fingerprint;

        // Check previous logout status
        $sql_logout = "SELECT logrec_id, logrec_logout FROM logrec WHERE logrec_id IN (SELECT MAX(logrec_id) FROM logrec WHERE user_id = '$_SESSION[log_id]')";
        $query_logout = mysqli_query($db_link, $sql_logout);
        checkSQL($db_link, $query_logout);
        
        $logout = mysqli_fetch_array($query_logout);
        $_SESSION['logrec_logout'] = $logout ? $logout[1] : 1; 

        // Close open sessions
        $sql_close_logrec = "UPDATE logrec SET logrec_end = '$_SESSION[log_time]' WHERE user_id = '$_SESSION[log_id]' AND logrec_end IS NULL";
        $query_close_logrec = mysqli_query($db_link, $sql_close_logrec);
        checkSQL($db_link, $query_close_logrec);

        // Record Login
        $sql_logrec = "INSERT INTO logrec (user_id, logrec_start, logrec_logout) VALUES ('$_SESSION[log_id]', '$_SESSION[log_time]', '0')";
        $query_logrec = mysqli_query($db_link, $sql_logrec);
        checkSQL($db_link, $query_logrec);

        // Get LOGREC ID
        $sql_logrecid = "SELECT MAX(logrec_id) FROM logrec WHERE user_id = '$_SESSION[log_id]'";
        $query_logrecid = mysqli_query($db_link, $sql_logrecid);
        checkSQL($db_link, $query_logrecid);
        
        $logrecid = mysqli_fetch_array($query_logrecid);
        $_SESSION['logrec_id'] = $logrecid['MAX(logrec_id)'];

        // Redirect to Dashboard
        header('Location: start.php');
        exit();
    }
    else {
        showMessage('Authentication failed!\nWrong Username and/or Password!');
    }
}
?>
<html>
    <?PHP 
    if(function_exists('includeHead')) {
        includeHead('Karomu Quick services');
    } else {
        echo "<head><title>Karomu Quick Services</title><link rel='stylesheet' href='style.css'></head>";
    }
    ?>

    <body>
        <div class="content_center" style="width:100%; margin-top:15em; display:flex; justify-content:center;">

            <div class="content_left" style="width:50%; padding-right:5em; text-align:right;">
                <img src="ico/mangoo.png" style="width:35%;">
            </div>

            <div class="content_right" style="width:50%; padding-left:5em; text-align:left;">

                <p class="heading" style="margin:0; text-align:left; font-size: 1.5em; font-weight:bold;">Please login...</p>

                <form action="" method="post">
                    <table id="tb_fields" style="margin:0; border-spacing:0em 1.25em;">
                        <tr>
                            <td>
                                <input type="text" style="width:50%; padding: 5px;" name="log_user" placeholder="Username" required />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="password" style="width:50%; padding: 5px;" name="log_pw" placeholder="Password" required />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="submit" name="login" value="Login" style="padding: 5px 15px; cursor:pointer;">
                            </td>
                        </tr>
                    </table>
                </form>

            </div>
        </div> 
    </body>
</html>