<?php
session_start(); // Mulai sesi di awal skrip

/**
 * Fungsi untuk menghasilkan CAPTCHA baru.
 * Ini akan dipanggil hanya jika $_SESSION['captcha_text'] belum diset
 * atau saat halaman pertama kali dimuat.
 */
function generateCaptcha() {
    $num1 = rand(1, 9);
    $num2 = rand(1, 9);
    $_SESSION['captcha_answer'] = $num1 + $num2;
    return "$num1 + $num2 = ?";
}

// Generate CAPTCHA pertama kali atau jika belum ada di sesi
if (!isset($_SESSION['captcha_text']) || !isset($_SESSION['captcha_answer'])) {
    $_SESSION['captcha_text'] = generateCaptcha();
}

// Tampilkan pesan error atau success dari redirect
$errorMessage = '';
if (isset($_GET['error'])) {
    $errorMessage = '<div class="error-message">' . htmlspecialchars($_GET['error']) . '</div>';
}

$successMessage = '';
if (isset($_GET['logout']) && $_GET['logout'] == 'success') {
    $successMessage = '<div class="success-message">Anda telah berhasil logout.</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Kader Posyandu</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    
    <style>
        /* Gaya CSS Anda */
        body {
            font-family: 'Poppins', sans-serif;
            background: white; /* Gradien hijau sebagai background */
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
            box-sizing: border-box;
        }

        .auth-container {
            background-color: #FFFFFF;
            border-radius: 15px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
            padding: 40px;
            max-width: 400px;
            width: 100%;
            text-align: center;
        }

        .auth-container h2 {
            color: #333;
            margin-bottom: 30px;
            font-weight: 700;
            font-size: 28px;
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
            font-size: 14px;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            color: #333;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
            box-sizing: border-box;
        }
        .form-control:focus {
            border-color: #4dab25;
            outline: none;
            box-shadow: 0 0 0 0.25rem rgba(77, 171, 37, 0.25);
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #4dab25, #024d52);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s ease, transform 0.2s ease, box-shadow 0.3s ease;
            margin-top: 10px;
        }
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.2);
        }

        .link-text {
            margin-top: 20px;
            font-size: 14px;
            color: #777;
        }
        .link-text a {
            color: #024d52;
            text-decoration: none;
            font-weight: 600;
            transition: color 0.2s ease;
        }
        .link-text a:hover {
            color: #4dab25;
            text-decoration: underline;
        }

        /* CAPTCHA Styles */
        .captcha-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
            background-color: #f9f9f9;
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 12px 15px;
        }
        .captcha-text {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            flex-grow: 1;
            text-align: right; /* Text CAPTCHA di kanan */
            padding-right: 10px;
        }
        .captcha-input {
            width: 80px; /* Lebar input captcha */
            padding: 8px 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            text-align: center;
            box-sizing: border-box; /* Pastikan padding tidak menambah lebar */
        }
        .captcha-reload {
            background: none;
            border: none;
            color: #024d52;
            font-size: 20px;
            cursor: pointer;
            transition: color 0.2s ease;
        }
        .captcha-reload:hover {
            color: #4dab25;
        }
        .error-message, .success-message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
        }
        .error-message {
            background-color: #ffe6e6;
            color: #cc0000;
            border: 1px solid #ffb3b3;
        }
        .success-message {
            background-color: #e6ffe6;
            color: #008000;
            border: 1px solid #b3ffb3;
        }

        /* Responsive adjustments */
        @media (max-width: 500px) {
            .auth-container {
                padding: 30px 25px;
                margin: 0 15px;
            }
            .auth-container h2 {
                font-size: 24px;
                margin-bottom: 25px;
            }
            .form-control, .captcha-input {
                padding: 10px 12px;
                font-size: 15px;
            }
            .submit-btn {
                padding: 12px;
                font-size: 16px;
            }
            .link-text, .error-message, .success-message {
                font-size: 13px;
                margin-top: 15px;
            }
            .captcha-group {
                padding: 10px 12px;
            }
            .captcha-text {
                font-size: 16px;
            }
            .captcha-reload {
                font-size: 18px;
            }
        }
    </style>
</head>
<body>
    <div class="auth-container">
        <h2>Login Kader Posyandu</h2>
        <?php
        echo $errorMessage;
        echo $successMessage;
        ?>

        <form action="../api/process_kader_login.php" method="POST">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" class="form-control" id="username" name="username" required autocomplete="username">
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" id="password" name="password" required autocomplete="current-password">
            </div>
            
            <div class="form-group">
                <label for="captcha">Verifikasi Keamanan</label>
                <div class="captcha-group">
                    <span id="captcha-text" class="captcha-text"><?php echo $_SESSION['captcha_text']; ?></span>
                    <input type="text" class="captcha-input" id="captcha" name="captcha" placeholder="Jawaban" required>
                    <button type="button" class="captcha-reload" id="reload-captcha" title="Reload CAPTCHA"><i class="fas fa-sync-alt"></i></button>
                </div>
            </div>

            <button type="submit" class="submit-btn">Login</button>
        </form>
        </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const captchaTextElement = document.getElementById('captcha-text');
            const reloadCaptchaBtn = document.getElementById('reload-captcha');
            const captchaInput = document.getElementById('captcha'); // Ambil referensi input CAPTCHA

            // Fungsi untuk me-load CAPTCHA baru dari server
            async function loadNewCaptcha() {
                try {
                    // Path ke generate_captcha.php relatif terhadap kader_login.php
                    const response = await fetch('generate_captcha.php'); 
                    const data = await response.json();
                    if (data.status === 'success') {
                        captchaTextElement.textContent = data.captcha_text;
                        captchaInput.value = ''; // Kosongkan input CAPTCHA setelah reload
                    } else {
                        console.error('Failed to load new CAPTCHA:', data.message);
                    }
                } catch (error) {
                    console.error('Error fetching new CAPTCHA:', error);
                }
            }

            // Event listener untuk tombol reload
            reloadCaptchaBtn.addEventListener('click', loadNewCaptcha);
        });
    </script>
</body>
</html>