<?php
// Konfigurasi koneksi database
$dsn = 'mysql:host=localhost;dbname=bilsprodevloy';
$username = 'bilsprodevloy';
$password = 'm6D5EFth3Xxfb2Lr';
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]);
    exit;
}
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');


// Header untuk JSON response
header('Content-Type: application/json');

// Tangani request API
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Ambil parameter `akun` dari URL
    $akun = $_GET['akun'] ?? '';

    if (empty($akun)) {
        echo json_encode(['error' => 'Parameter akun is required']);
        exit;
    }

    try {
        // Query untuk mencari data berdasarkan akun
        $stmt = $pdo->prepare("SELECT * FROM v_pelanggan WHERE akun LIKE :akun");
        $stmt->bindValue(':akun', "%$akun%", PDO::PARAM_STR);
        $stmt->execute();
        $data = $stmt->fetchAll();

        if ($data) {
            echo json_encode(['status' => 'success', 'data' => $data]);
        } else {
            echo json_encode(['status' => 'not_found', 'message' => 'No data found for the given akun']);
        }
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Query failed: ' . $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed. Use GET request.']);
}
