<?php
session_start();
require_once 'db_connect.php'; // Path relatif dari folder 'api' ke 'db_connect.php'

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $user_captcha_answer = trim($_POST['captcha'] ?? ''); // Perhatikan name="captcha" di form

    // Ambil jawaban CAPTCHA yang tersimpan di sesi
    $correct_captcha_answer = $_SESSION['captcha_answer'] ?? null;
    $captcha_text_for_display = $_SESSION['captcha_text'] ?? '0 + 0 = ?'; // Untuk ditampilkan jika perlu refresh

    // Hapus CAPTCHA dari sesi setelah diambil, untuk keamanan sekali pakai
    unset($_SESSION['captcha_answer']);
    unset($_SESSION['captcha_text']);

    // Validasi CAPTCHA
    if (empty($user_captcha_answer) || !is_numeric($user_captcha_answer)) {
        header('Location: ../auth/jejaring_login.php?error=' . urlencode('Jawaban verifikasi keamanan harus berupa angka.') . '&username=' . urlencode($username));
        exit();
    } elseif ((int)$user_captcha_answer !== $correct_captcha_answer) {
        // regenerate captcha in session for next attempt
        // Ini akan ditangani oleh jejaring_login.php saat dimuat ulang
        header('Location: ../auth/jejaring_login.php?error=' . urlencode('Verifikasi keamanan salah. Silakan coba lagi.') . '&username=' . urlencode($username));
        exit();
    }

    // Validasi input lainnya
    if (empty($username) || empty($password)) {
        header('Location: ../auth/jejaring_login.php?error=' . urlencode('Username dan password harus diisi.') . '&username=' . urlencode($username));
        exit();
    }

    // Proses Login (Jika CAPTCHA benar)
    try {
        $stmt = $pdo->prepare("SELECT id, username, password_hash, user_type, nama_instansi, is_active FROM jejaring_users WHERE username = :username");
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            if ($user['is_active']) { // Cek apakah akun aktif
                if (password_verify($password, $user['password_hash'])) {
                    // Login Berhasil
                    $_SESSION['jejaring_id'] = $user['id'];
                    $_SESSION['jejaring_username'] = $user['username'];
                    $_SESSION['jejaring_user_type'] = $user['user_type'];
                    $_SESSION['jejaring_nama_instansi'] = $user['nama_instansi'];
                    $_SESSION['jejaring_logged_in'] = true;

                    // Redirect ke halaman dashboard jejaring
                    header('Location: ../jejaring/'); // Sesuaikan path ini!
                    exit();
                } else {
                    header('Location: ../auth/jejaring_login.php?error=' . urlencode('Password salah.') . '&username=' . urlencode($username));
                    exit();
                }
            } else {
                header('Location: ../auth/jejaring_login.php?error=' . urlencode('Akun Anda tidak aktif. Silakan hubungi administrator.') . '&username=' . urlencode($username));
                exit();
            }
        } else {
            header('Location: ../auth/jejaring_login.php?error=' . urlencode('Username tidak ditemukan.') . '&username=' . urlencode($username));
            exit();
        }
    } catch (PDOException $e) {
        error_log("Jejaring Login Error (DB): " . $e->getMessage()); // Log error untuk debugging
        header('Location: ../auth/jejaring_login.php?error=' . urlencode('Terjadi kesalahan sistem. Silakan coba lagi nanti.') . '&username=' . urlencode($username));
        exit();
    }

} else {
    // Jika ada akses langsung ke process_jejaring_login.php tanpa POST
    header('Location: ../auth/jejaring_login.php');
    exit();
}
?>