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

// Check if the credentials are provided
if (isset($_POST['signin'])) {
    $uname = $_POST['username'];
    $password = $_POST['password'];

    // Validate user input
    if (!empty($uname) && !empty($password)) {
        // Query to check credentials in the database
        $sql = "SELECT email, password FROM tbl_admin WHERE email = :uname AND password = :password";
        $query = $dbh->prepare($sql);
        $query->bindParam(':uname', $uname, PDO::PARAM_STR);
        $query->bindParam(':password', $password, PDO::PARAM_STR);
        $query->execute();
        $results = $query->fetchAll(PDO::FETCH_OBJ);

        if ($query->rowCount() > 0) {
            // Set session for the logged-in user
            $_SESSION['clogin'] = $uname;
            echo "<script type='text/javascript'>document.location ='index.php';</script>";

            // Fetch user's country and IP address
            $json = @file_get_contents("http://ip-api.com/json/");
            if ($json === FALSE) {
                $country = 'Unknown';
                $ip = $_SERVER['REMOTE_ADDR']; // Fallback to server-side IP
            } else {
                $data = json_decode($json);
                $country = isset($data->country) ? $data->country : 'Unknown';
                $ip = isset($data->query) ? $data->query : $_SERVER['REMOTE_ADDR'];
            }

            // Date and time of login
            $created_date_js = $_POST['reg_date_js'] ?? date('Y-m-d H:i:s');

            // Insert login history into the database
            $sql = "INSERT INTO login_history(email, ip, country, action, created_date_js, status)
                    VALUES(:email, :ip, :country, 'login', :created_date_js, 1)";
            $query = $dbh->prepare($sql);
            $query->bindParam(':email', $uname, PDO::PARAM_STR);
            $query->bindParam(':ip', $ip, PDO::PARAM_STR);
            $query->bindParam(':country', $country, PDO::PARAM_STR);
            $query->bindParam(':created_date_js', $created_date_js, PDO::PARAM_STR);
            $query->execute();
        } else {
            $msg = "Invalid login details or email not verified.";
            echo "<script>alert('$msg');</script>";
        }
    } else {
        echo "<script>alert('Please fill in all fields.');</script>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login</title>
    <style>
        body {
            background-color: #36454F; /* Charcoal black */
            color: #FFFFFF;
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            flex-direction: column;
        }

        .login-container {
            background-color: #2F4F4F; /* Slightly lighter charcoal */
            border: 2px solid #FFFFFF;
            border-radius: 8px;
            padding: 20px;
            width: 300px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .login-container h1 {
            text-align: center;
            color: #32CD32;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
        }

        .form-group input {
            width: 100%;
            padding: 10px;
            border: 2px solid #FFFFFF;
            border-radius: 4px;
            background-color: #36454F;
            color: #FFFFFF;
        }

        .form-group input:focus {
            border-color: #32CD32;
            outline: none;
        }

        .login-btn {
            width: 100%;
            padding: 10px;
            background-color: #32CD32;
            color: #FFFFFF;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .login-btn:hover {
            background-color: #28a428;
        }

        .login-btn:focus {
            outline: 2px solid #FFFFFF;
        }

        .footer {
            text-align: center;
            margin-top: 15px;
            font-size: 12px;
            color: #B0C4DE;
        }

        .footer a {
            color: #32CD32;
            text-decoration: none;
        }

        .footer a:hover {
            text-decoration: underline;
        }

        .status-message {
            display: none;
            text-align: center;
            color: red;
            font-size: 18px;
            background: #ffdddd;
            padding: 15px;
            border: 2px solid red;
            border-radius: 5px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>

    <div id="status-message" class="status-message">
        <p><b>EXE is not running!</b> Please start the application.</p>
    </div>

    <div id="login-container" class="login-container">
        <h1>Admin Login</h1>
        <form method="POST">
            <div class="form-group">
                <label for="username">Email</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" required>
            </div>
            <input type="submit" class="login-btn" name="signin" value="Login">
        </form>
        <div class="footer">
            <p>&copy; 2024 Admin Panel | <a href="#">Copy Trading</a></p>
        </div>
    </div>

    <script>
    function checkStatus() {
        fetch("check_status.php")
        .then(response => response.text())
        .then(status => {
            status = status.trim();
            const loginContainer = document.getElementById("login-container");
            const statusMessage = document.getElementById("status-message");

            if (status === "Not Running") {
                loginContainer.style.display = "none";
                statusMessage.style.display = "block";
            } else {
                loginContainer.style.display = "block";
                statusMessage.style.display = "none";
            }
        })
        .catch(error => console.error('Error fetching status:', error));
    }

    // Check status every second
    setInterval(checkStatus);
    </script>

</body>
</html>
