<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Start output buffering
ob_start();

// Start the session
session_start();

if (isset($_SESSION['error'])) {
    $errorMessage = $_SESSION['error'];
    unset($_SESSION['error']);
} else {
    $errorMessage = '';
}

// Include your database connection
include 'includes/dbconn.php';

function incrementFailedAttempts($email, $conn) {
    $stmt = $conn->prepare("UPDATE users SET failed_attempts = failed_attempts + 1, last_attempt_time = CURRENT_TIMESTAMP WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->close();
}

function resetFailedAttempts($email, $conn) {
    $stmt = $conn->prepare("UPDATE users SET failed_attempts = 0 WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->close();
}

function updateLastLoginTime($email, $conn) {
    $stmt = $conn->prepare("UPDATE users SET last_attempt_time = CURRENT_TIMESTAMP WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->close();
}

function isPasswordChangeRequired($email, $conn) {
    $passwordChangeDuration = 90 * 24 * 60 * 60; // 90 days in seconds
    $stmt = $conn->prepare("SELECT last_password_change FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $userData = $result->fetch_assoc();
    $stmt->close();
    
    $lastPasswordChange = strtotime($userData['last_password_change']);
    $currentTime = time();
    return (($currentTime - $lastPasswordChange) > $passwordChangeDuration);
}

function checkLoginAttempts($email, $conn) {
    $maxAttempts = 6;
    $lockDuration = 30 * 60; // 30 minutes in seconds
    $stmt = $conn->prepare("SELECT failed_attempts, last_attempt_time FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $userData = $result->fetch_assoc();
    $stmt->close();

    $failedAttempts = $userData['failed_attempts'];
    $lastAttemptTime = null;
    if ($userData['last_attempt_time'] !== null) {
        $lastAttemptTime = strtotime($userData['last_attempt_time']);
    }
    $currentTime = time();

    if ($failedAttempts >= $maxAttempts && ($currentTime - $lastAttemptTime) < $lockDuration) {
        // User is locked out
        return false;
    }
    return true;
}

if (isset($_POST['email']) && isset($_POST['password'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (!checkLoginAttempts($email, $conn)) {
        // User is locked out
        $_SESSION['error'] = "Account is locked. Please try again later.";
        header('Location: auth-login.php');
        exit();
    }

    if (isPasswordChangeRequired($email, $conn)) {
        // Password change required
        $_SESSION['error'] = "Password change required. Please update your password.";
        header('Location: change_password.php'); // Redirect to password change page
        exit();
    }

    $stmt = $conn->prepare("SELECT user_id, company_id, password_hash FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        if (password_verify($password, $row['password_hash'])) {
            // Reset failed attempts on successful login
            resetFailedAttempts($email, $conn);

            // Update last login time
            updateLastLoginTime($email, $conn);

            // Setting session variables
            $_SESSION['user_id'] = $row['user_id'];
            $_SESSION['company_id'] = $row['company_id'];

            if ($row['company_id'] == 0) {
                // Redirect admin to admin-specific index page
                header('Location: dashboard.php');
            } else {
                // Redirect regular user to client index page
                header('Location: client/index.php');
            }
            exit();
        } else {
            // Increment failed attempts on incorrect password
            incrementFailedAttempts($email, $conn);
            $_SESSION['error'] = "Incorrect username or password";
            header('Location: auth-login.php'); // Redirect to login page on failure
            exit();
        }
    } else {
        incrementFailedAttempts($email, $conn);
        $_SESSION['error'] = "Incorrect username or password";
        header('Location: auth-login.php'); // Redirect to login page on failure
        exit();
    }
    $stmt->close();
} else {
    $_SESSION['error'] = "Login form data not submitted.";
    header('Location: auth-login.php');
    exit();
}

ob_end_flush();
?>
