<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once './config.php';
//echo $db_name;
//var_dump($_POST);
// Function to log successful login entry to the database
function logLoginEntry($username, $ipAddress, $userAgent, $userType) {
    global $db_host, $db_name, $db_user, $db_password;

    $connection = mysqli_connect($db_host, $db_user, $db_password, $db_name);

    if (!$connection) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $timezone = new DateTimeZone('Europe/Paris'); // Set the desired timezone, such as Europe/Paris for GMT+1 (Central European Time)
    $timestamp = (new DateTime('now', $timezone))->format('Y-m-d H:i:s');

    $query = "INSERT INTO userlogs (username, login_time, ip_address, user_agent, user_type) VALUES ('$username', '$timestamp', '$ipAddress', '$userAgent', '$userType')";

    if (!mysqli_query($connection, $query)) {
        echo "Error: " . $query . "<br>" . mysqli_error($connection);
    }

    mysqli_close($connection);
}

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the username and password entered by the user
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Perform authentication logic against the database
    $connection = mysqli_connect($db_host, $db_user, $db_password, $db_name);

    if (!$connection) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $query = "SELECT username, password, user_type, zone, country, cell, id, church_id, cell_id, church, name FROM users WHERE username = '$username'";
    $result = mysqli_query($connection, $query);


    if ($row = mysqli_fetch_assoc($result)) {
        // Verify the entered password against the stored hash
        $storedPassword = $row['password'];
        if (password_verify($password, $storedPassword)) {
            // Authentication successful
            // Start the session and store relevant information
            //echo $row['userType'];
            session_start();

            $_SESSION['username'] = $row['username'];
            $_SESSION['name'] = $row['name'];
            $_SESSION['userType'] = $row['user_type'];
            $_SESSION['country'] = $row['country'];
            $_SESSION['zone'] = $row['zone'];
            $_SESSION['church'] = $row['church'];
            $_SESSION['cell'] = $row['cell'];
            $_SESSION['id'] = $row['id'];
            //$_SESSION['zone'] = $row['zone'];
            $_SESSION['church_id'] = $row['church_id'];
            $_SESSION['cell_id'] = $row['cell_id'];

            // Log the login ent

            // Log the login entry
            logLoginEntry($username, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'], $_SESSION['userType']);

            // Redirect to the appropriate dashboard based on user type
            if ($_SESSION['userType'] === 'admin') {
                header('Location: adm/dashboard.php');
            } elseif ($_SESSION['userType'] === 'member') {
                header('Location: member/dashboard.php');
            }  elseif ($_SESSION['userType'] === 'cellleader') {
                header('Location: member/dashboard.php');
            } elseif ($_SESSION['userType'] === 'director') {
                header('Location: dir/dashboard.php');
            }  elseif ($_SESSION['userType'] === 'pastor') {
                header('Location: member/dashboard.php');
            } elseif ($_SESSION['userType'] === 'mmd_admin') {
                header('Location: mmd/admin_mmd.php');
            } elseif ($_SESSION['userType'] === 'finance_admin') {
                header('Location: finance/admin_finance.php');
            } elseif ($_SESSION['userType'] === 'cg_admin') {
                header('Location: cg/admin_cg_serviceReport.php');
            } elseif ($_SESSION['userType'] === 'online_admin') {
                header('Location: online/dashboard.php');
            } else {
                // Handle other user types or redirect to a default page
                header('Location: default/dashboard.php');
            }
            exit();
        } else {
            // Authentication failed
            $errorMessage = 'Invalid username or password. Please try again.';
        }
    } else {
        // User not found
        $errorMessage = 'Invalid username or password. Please try again.';
    }

    mysqli_close($connection);
}

// HTML form for user login
?>
<!--
<form method="post" action="">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br>

    <input type="submit" value="Log in">
</form>-->
