<?php
session_start();
require_once __DIR__ . '/../config.php';

$message = '';
$success = false;

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

    if (empty($username) || empty($password)) {
        $message = 'Username dan password harus diisi!';
    } else {
        echo "<h3>Testing Login...</h3>";
        echo "Username: " . htmlspecialchars($username) . "<br>";
        echo "Password: " . htmlspecialchars($password) . "<br><br>";

        $result = api_login($username, $password);

        echo "<h4>API Response:</h4>";
        echo "<pre>" . json_encode($result, JSON_PRETTY_PRINT) . "</pre>";

        if ($result['success']) {
            $message = 'Login berhasil!';
            $success = true;
            if (isset($result['data']['token'])) {
                echo "<p>Token: " . substr($result['data']['token'], 0, 20) . "...</p>";
            }
        } else {
            $message = 'Login gagal: ' . ($result['data']['pesan'] ?? 'Unknown error');
        }
    }
}
?>

<!DOCTYPE html>
<html>

<head>
    <title>Simple Login Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
        }

        .form-group {
            margin: 10px 0;
        }

        input[type="text"],
        input[type="password"] {
            padding: 8px;
            width: 200px;
        }

        button {
            padding: 10px 20px;
            background: #007cba;
            color: white;
            border: none;
            cursor: pointer;
        }

        .success {
            color: green;
        }

        .error {
            color: red;
        }
    </style>
</head>

<body>
    <h2>Simple Login Test</h2>

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

    <form method="POST">
        <div class="form-group">
            <label>Username:</label><br>
            <input type="text" name="username" value="<?php echo htmlspecialchars($_POST['username'] ?? 'Widia'); ?>" required>
        </div>

        <div class="form-group">
            <label>Password:</label><br>
            <input type="password" name="password" value="<?php echo htmlspecialchars($_POST['password'] ?? 'qwerty5*'); ?>" required>
        </div>

        <button type="submit">Test Login</button>
    </form>

    <hr>
    <h3>Quick Test Links:</h3>
    <a href="test_credentials.php">Test Multiple Credentials</a><br>
    <a href="debug_info.php">Debug Information</a><br>
    <a href="test_api.php">Test API Connection</a><br>
    <a href="debug_login.php">Debug Login</a><br>
</body>

</html>