<?php
session_start();
require 'config.php';

$error = '';
$info  = '';

// Show reason if user was kicked out due to another login
if (!empty($_GET['reason']) && $_GET['reason'] === 'session_conflict') {
    $info = 'Your account was logged in from another device or browser. Please sign in again.';
}

// If already logged in, go to dashboard
if (isset($_SESSION['email'])) {
    header('Location: dashboard.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($email === '' || $password === '') {
        $error = 'Please enter email and password.';
    } else {
        $sql = "SELECT id, username, email, password, role FROM users WHERE email = ? LIMIT 1";
        $user = null;

        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $stmt->bind_result($id, $username, $dbEmail, $hash, $role);

            if ($stmt->fetch()) {
                // Copy row into array, then CLOSE the statement
                $user = [
                    'id'       => $id,
                    'username' => $username,
                    'email'    => $dbEmail,
                    'hash'     => $hash,
                    'role'     => $role ?: 'user',
                ];
            }

            $stmt->close();
        } else {
            $error = 'Database error. Please try again later.';
        }

        if ($user) {
            if (password_verify($password, $user['hash'])) {

                // ---- SESSION ----
                session_regenerate_id(true);
                $sessionId = session_id();

                $_SESSION['user_id']  = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email']    = $user['email'];
                $_SESSION['role']     = $user['role'];

                // ---- LOGIN META: time, session id, user agent, ip ----
                $now       = date('Y-m-d H:i:s');
                $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
                $ip        = $_SERVER['REMOTE_ADDR'] ?? '';

                $updSql = "UPDATE users 
                           SET last_login = ?, 
                               last_activity = ?, 
                               last_logout = NULL, 
                               current_session_id = ?,
                               last_login_user_agent = ?,
                               last_login_ip = ?
                           WHERE id = ?";

                if ($up = $conn->prepare($updSql)) {
                    $up->bind_param('sssssi', $now, $now, $sessionId, $userAgent, $ip, $user['id']);
                    if (!$up->execute()) {
                        // Optional: log error to file instead of breaking login
                        @file_put_contents(
                            __DIR__ . '/session_debug.log',
                            date('Y-m-d H:i:s') . " UPDATE error for user {$user['id']}: " . $conn->error . "\n",
                            FILE_APPEND
                        );
                    }
                    $up->close();
                } else {
                    // Optional: log prepare error
                    @file_put_contents(
                        __DIR__ . '/session_debug.log',
                        date('Y-m-d H:i:s') . " PREPARE error for user {$user['id']}: " . $conn->error . "\n",
                        FILE_APPEND
                    );
                }

                header('Location: dashboard.php');
                exit;

            } else {
                $error = 'Invalid email or password.';
            }
        } else {
            if ($error === '') {
                $error = 'Invalid email or password.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login - Michelle²</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <style>
        * {
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            background: #f4f4f4;
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }
        .login-card {
            background: #fff;
            padding: 30px 25px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.15);
            width: 100%;
            max-width: 380px;
        }
        .login-card h1 {
            margin-top: 0;
            margin-bottom: 10px;
            text-align: center;
            color: #2c3e50;
        }
        .login-card p.subtitle {
            margin: 0 0 20px;
            text-align: center;
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-size: 0.9rem;
            color: #555;
        }
        input[type="email"],
        input[type="password"] {
            width: 100%;
            padding: 8px 10px;
            margin-bottom: 15px;
            border-radius: 4px;
            border: 1px solid #ccc;
            font-size: 0.95rem;
        }
        .btn {
            width: 100%;
            padding: 10px 0;
            border-radius: 4px;
            border: none;
            background: #3498db;
            color: white;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s ease, transform 0.1s ease;
        }
        .btn:hover {
            background: #2980b9;
        }
        .error {
            background: #fce4e4;
            border: 1px solid #e74c3c;
            color: #c0392b;
            padding: 8px 10px;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 0.85rem;
        }
        .info {
            background: #e8f4fd;
            border: 1px solid #3498db;
            color: #21618c;
            padding: 8px 10px;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 0.85rem;
        }
        .footer-links {
            margin-top: 15px;
            text-align: center;
            font-size: 0.85rem;
        }
        .footer-links a {
            color: #3498db;
            text-decoration: none;
        }
        .footer-links a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <h1>Michelle²</h1>
        <p class="subtitle">Sign in to manage your operations</p>

        <?php if ($info): ?>
            <div class="info"><?php echo htmlspecialchars($info); ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="post" action="login.php">
            <label for="email">Email</label>
            <input type="email" name="email" id="email" autocomplete="username" required>

            <label for="password">Password</label>
            <input type="password" name="password" id="password" autocomplete="current-password" required>

            <button type="submit" class="btn">Sign In</button>
        </form>

        <div class="footer-links">
            <a href="forgot_password.php">Forgot your password?</a>
        </div>
    </div>
</body>
</html>
