<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Enable detailed error reporting (for debugging)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include_once __DIR__ . '/../config.php'; // Adjust path if needed

// Check DB connection
if (!$conn) {
    echo json_encode([
        "success" => false,
        "message" => "Database connection not established."
    ]);
    exit;
}

// Fetch all account types
$sql = "SELECT * FROM account_types ORDER BY ac_index DESC";
$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    $account_types = [];
    while ($row = $result->fetch_assoc()) {
        $account_types[] = $row;
    }

    echo json_encode([
        "success" => true,
        "message" => "Account types fetched successfully",
        "data" => $account_types
    ]);
} else {
    echo json_encode([
        "success" => false,
        "message" => "No account types found"
    ]);
}

$conn->close();
?>
