<?php
// File: API_KONEKSI/auth/login.php
header('Content-Type: application/json');
include '../config/koneksi.php';

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

    if (empty($email) || empty($password)) {
        echo json_encode(["status" => "gagal", "pesan" => "Email dan Kata Sandi tidak boleh kosong!", "data" => []]);
        exit;
    }

    // Query dengan semua field yang dibutuhkan
    $stmt = $conn->prepare("SELECT user_id, lengkap_nm, email_tx, whatsapp_no, password_tx, role_nm, active_st FROM mst_user WHERE email_tx = ? AND deleted_st = 0 LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();

        if ($user['active_st'] == 0) {
            echo json_encode(["status" => "gagal", "pesan" => "Akun Anda tidak aktif.", "data" => []]);
            exit;
        }

        // Verifikasi Password
        if (password_verify($password, $user['password_tx']) || $password === $user['password_tx']) {
            
            // Generate KTP Digital (JWT Token)
            require_once __DIR__ . '/jwt_helper.php';
            $payload = [
                'user_id' => $user['user_id'],
                'role_nm' => $user['role_nm']
            ];
            $token = encodeJWT($payload);

            // Perbaikan: Mapping data dengan token
            $userData = [
                "user_id" => (string)$user['user_id'],
                "lengkap_nm" => $user['lengkap_nm'],
                "email_tx" => $user['email_tx'],
                "whatsapp_no" => $user['whatsapp_no'],
                "role_nm" => $user['role_nm'],
                "token" => $token
            ];

            echo json_encode(["status" => "sukses", "pesan" => "Login berhasil!", "data" => [$userData]]);
        } else {
            echo json_encode(["status" => "gagal", "pesan" => "Kata sandi salah!", "data" => []]);
        }
    } else {
        echo json_encode(["status" => "gagal", "pesan" => "Email tidak terdaftar!", "data" => []]);
    }
    $stmt->close();
}
$conn->close();
?>