<?php
session_start();
include('../includes/config.php');

$error_message = ''; // Initialize error message

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['username_email'], $_POST['password'])) {
    $username_email = trim($_POST['username_email']);
    $password = $_POST['password'];

    $sql = "SELECT id, first_name, last_name, username, email, phone_number, password, role_id, store_id, 
                   profile_picture, password_reset, password_changed 
            FROM users 
            WHERE username = ? OR email = ? 
            LIMIT 1";

    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("ss", $username_email, $username_email);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $stmt->bind_result(
                $id, $first_name, $last_name, $username, $email, $phone_number, $hashed_password, 
                $role_id, $store_id, $profile_picture, $password_reset, $password_changed
            );
            $stmt->fetch();

            if (password_verify($password, $hashed_password)) {
                // Store user session data
                $_SESSION['user_id'] = $id;
                $_SESSION['username'] = $username;
                $_SESSION['first_name'] = $first_name;
                $_SESSION['last_name'] = $last_name;
                $_SESSION['email'] = $email;
                $_SESSION['phone_number'] = $phone_number;
                $_SESSION['role_id'] = $role_id;
                $_SESSION['store_id'] = $store_id;
                $_SESSION['profile_picture'] = $profile_picture;
                $_SESSION['login_time'] = date("Y-m-d H:i:s");

                // Update activity timestamps
                $update_sql = "UPDATE users SET last_logged_in = NOW(), last_activity = NOW(), last_seen = NOW() WHERE id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("i", $id);
                $update_stmt->execute();
                $update_stmt->close();

                // Check if user must change password
                if ($password_reset == 1 && $password_changed == 0) {
                    header("Location: ../pages/shared/change_password.php?force=1");
                    exit();
                }

                // Redirect by role
                switch ($role_id) {
                    case 1:
                        header("Location: ../pages/admin/admin_dashboard.php");
                        break;
                    case 2:
                        header("Location: ../pages/manager/manager_dashboard.php");
                        break;
                    case 3:
                        header("Location: ../pages/cashier/cashier_dashboard.php");
                        break;
                    case 4:
                        header("Location: ../pages/accountant/accountant_dashboard.php");
                        break;
                    default:
                        $error_message = "Unauthorized role.";
                        break;
                }
                exit();
            } else {
                $error_message = "Invalid password.";
            }
        } else {
            $error_message = "No user found with that username or email.";
        }
        $stmt->close();
    } else {
        $error_message = "Login query failed.";
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login - Digital POS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            margin: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../images/bg.jpg') no-repeat center center fixed;
            background-size: cover;
        }

        .login-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: rgba(0, 0, 0, 0.6);
        }

        .login-form {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 40px;
            border-radius: 10px;
            width: 90%;
            max-width: 400px;
            color: #fff;
            text-align: center;
        }

        .login-form h1 {
            margin-bottom: 20px;
        }

        .login-form input {
            width: 100%;
            padding: 12px;
            margin: 10px 0;
            border-radius: 8px;
            border: none;
            font-size: 16px;
        }

        .login-form button {
            width: 100%;
            padding: 12px;
            background: orange;
            color: black;
            border: none;
            border-radius: 8px;
            font-weight: bold;
            font-size: 16px;
            cursor: pointer;
            margin-top: 10px;
        }

        .login-form button:hover {
            background-color: #ff9900;
        }

        .error-message {
            margin-top: 15px;
            color: #ff4d4d;
        }

        .image-container {
            margin-top: 25px;
        }

        .image-container img {
            width: 70px;
            border-radius: 50%;
        }

        .image-container p {
            font-size: 14px;
            color: #ffc107;
        }

        @media (max-width: 600px) {
            .login-form {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>

<div class="login-container">
    <div class="login-form">
        <h1>Digital POS Login</h1>
        <form method="POST">
            <input type="text" name="username_email" placeholder="Username or Email" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit">Login</button>
        </form>

        <?php if (!empty($error_message)): ?>
            <div class="error-message">
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <div class="image-container">
            <img src="../images/curious.jpeg" alt="Forgot Password">
            <p>Please enter correct password!</p>
        </div>
    </div>
</div>

</body>
</html>
