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

// Fetch system settings (logo)
$settings = $conn->query("SELECT * FROM settings LIMIT 1")->fetch_assoc();
$logo = !empty($settings['logo']) ? $settings['logo'] : '';

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "SELECT * FROM users WHERE username = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        
        if (password_verify($password, $user['password']) || $user['password'] === $password) {
            // Set session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = strtolower($user['role']);


            // ✅ Insert login time into user_logs
            $stmtLog = $conn->prepare("INSERT INTO user_logs (user_id, login_time) VALUES (?, NOW())");
            $stmtLog->bind_param('i', $user['id']);
            $stmtLog->execute();

            // Store the log ID in session to update logout later
            $_SESSION['log_id'] = $conn->insert_id;
             // ------------------ CAPTURE LOGIN INFO ------------------
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown IP';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    $time = date('Y-m-d H:i:s');

    // Optional: Get approximate location using IP (free API)
    $location = '';
    $ip_info = @file_get_contents("http://ip-api.com/json/{$ip}");
    if($ip_info){
        $ip_data = json_decode($ip_info,true);
        if($ip_data['status'] === 'success'){
            $location = "{$ip_data['city']}, {$ip_data['regionName']}, {$ip_data['country']}";
        }
    }

    // ------------------ EMAIL TO GIANTPLUS ------------------
    $to = "giantplusmw@gmail.com,rams.investments@gmail.com";
    $subject = "POS Login Alert - {$user['username']}";
    $message = "
    <h3>New Login Alert</h3>
    <table border='1' cellpadding='5'>
        <tr><td><b>Username</b></td><td>{$user['username']}</td></tr>
        <tr><td><b>IP Address</b></td><td>{$ip}</td></tr>
        <tr><td><b>Location</b></td><td>{$location}</td></tr>
        <tr><td><b>Browser / Device</b></td><td>{$user_agent}</td></tr>
        <tr><td><b>Login Time</b></td><td>{$time}</td></tr>
    </table>
    ";
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: cloud@gianterp.space\r\n";

    @mail($to, $subject, $message, $headers);

           // ✅ ROLE-BASED REDIRECT
$role = strtolower($user['role']);

switch($role){

    case 'admin':
        header("Location:front_office_dashboard.php");
        break;

    case 'waiter':
        header("Location: restaurant.php");
        break;

    case 'bartender':
        header("Location: bar.php");
        break;

    case 'chef':
        header("Location: kitchen_dashboard.php");
        break;

    case 'accountant':
        header("Location: accounts.php");
        break;

    case 'manager':
        header("Location: manager.php");
        break;

    case 'front_office':
        header("Location: front_office_dashboard.php");
        break;

    case 'stores':
        header("Location: inventory.php");
        break;

    case 'housekeeping':
        header("Location: house_keeping.php");
        break;

    default:
        header("Location: sales_pos.php");
}

exit;
        } else {
            $error = "Invalid password.";
        }
    } else {
        $error = "User not found.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RAMS EXECUTE LODGE-Login</title>

<!-- Bootstrap & Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
body {
    background: linear-gradient(135deg, #667eea, #764ba2);
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: 'Segoe UI', sans-serif;
}

.card {
    border-radius: 15px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    animation: fadeIn 1s ease-in-out;
}

.card-header {
    font-size: 1.2rem;
}

.input-group-text {
    background: #764ba2;
    color: #fff;
    border: none;
}

.btn-dark {
    background: #764ba2;
    border: none;
    transition: 0.3s;
}

.btn-dark:hover {
    background: #667eea;
    color: #fff;
}

.logo-box{
    text-align:center;
    margin-bottom:10px;
}

.logo-box img{
    max-height:70px;
}

@keyframes fadeIn {
    from {opacity:0; transform: translateY(-20px);}
    to {opacity:1; transform: translateY(0);}
}
</style>
</head>
<body>

<div class="container" style="max-width:400px;">
    <div class="card shadow">

        <div class="card-header text-white text-center bg-dark">

            <!-- ✅ LOGO DISPLAY -->
            <?php if(!empty($logo)): ?>
                <div class="logo-box">
                    <img src="<?= htmlspecialchars($logo) ?>" alt="Logo">
                </div>
            <?php endif; ?>

            <i class="fa fa-cash-register fa-lg mr-2"></i> e-Hotels
        </div>

        <div class="card-body">

            <?php if (!empty($error)): ?>
                <div class="alert alert-danger text-center"><?= $error ?></div>
            <?php endif; ?>

            <form method="POST">
                <div class="form-group">
                    <label><i class="fa fa-user me-2"></i> Username</label>
                    <input type="text" name="username" class="form-control" placeholder="Enter your username" required>
                </div>

                <div class="form-group">
                    <label><i class="fa fa-lock me-2"></i> Password</label>
                    <div class="input-group">
                        <input type="password" name="password" id="password" class="form-control" placeholder="Enter your password" required>
                        <div class="input-group-append">
                            <span class="input-group-text" onclick="togglePassword()" style="cursor:pointer;">
                                <i class="fa fa-eye" id="toggleIcon"></i>
                            </span>
                        </div>
                    </div>
                </div>

                <button class="btn btn-dark btn-block mt-3" type="submit">
                    <i class="fa fa-sign-in-alt me-2"></i> Login
                </button>
            </form>

            <p class="text-center mt-3 text-muted" style="font-size:0.85rem;">
                &copy; <?= date('Y') ?>
            </p>
        </div>
    </div>
</div>

<script>
function togglePassword() {
    var pw = document.getElementById('password');
    var icon = document.getElementById('toggleIcon');
    if (pw.type === 'password') {
        pw.type = 'text';
        icon.classList.replace('fa-eye','fa-eye-slash');
    } else {
        pw.type = 'password';
        icon.classList.replace('fa-eye-slash','fa-eye');
    }
}
</script>

</body>
</html>
