<?php
// ✅ Add CORS headers BEFORE any output
header("Access-Control-Allow-Origin: https://accounts.finlms.com"); // or "*"
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// ✅ Handle OPTIONS preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Database connection
include 'connection.php';

// Get userId from request
$userId = isset($_GET['userId']) ? intval($_GET['userId']) : 0;

if ($userId === 0) {
    echo json_encode(['error' => 'Invalid userId']);
    exit;
}

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to fetch filtered companies
$sql = "SELECT com_name, com_id FROM company WHERE reg_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();

// Fetch data and encode in JSON
$companies = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $companies[] = array(
            'companyId' => $row['com_id'],
            'com_name' => $row['com_name']
        );
    }
}

// Output JSON
echo json_encode($companies);

// Close connection
$stmt->close();
$conn->close();
?>
