<?php
header('Content-Type: application/json');

// Database connection (replace with your own connection details)
$servername = "localhost";
$username = "healthas_regportal";
$password = "Victor@007";
$dbname = "healthas_regportal";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Get the state and planType parameters from the URL
$state = isset($_GET['state']) ? $_GET['state'] : '';
$planType = isset($_GET['planType']) ? $_GET['planType'] : '';

$hospitals = array();

if (!empty($state) && !empty($planType)) {
    // Prepare the SQL statement based on the selected plan type
    $sql = "SELECT provider_name, location FROM web_app_provider_list WHERE provider_group = 'default'";

    if ($planType === 'Social Plan') {
        $sql .= " AND state = ? AND provider_category = 'BANDD'";
    } elseif ($planType === 'Club Plan') {
        $sql .= " AND state = ? AND provider_category = 'BANDD'";
    }elseif ($planType === 'Business Plan') {
        $sql .= " AND state = ? AND provider_category = 'BANDD'";
    }elseif ($planType === 'Upper Plan') {
        $sql .= " AND state = ? AND (provider_category = 'BANDD' OR provider_category = 'BANDC')";
    } elseif ($planType === 'Executive Plan') {
        $sql .= " AND state = ? AND (provider_category = 'BANDD' OR provider_category = 'BANDC' OR provider_category = 'BANDB')";
    }elseif ($planType === 'Flex Plan') {
        $sql .= " AND state = ? AND (provider_category = 'BANDD' OR provider_category = 'BANDC' OR provider_category = 'BANDB' OR provider_category = 'BANDA')";
    } elseif ($planType === 'TSHIPCUA') {
        $sql .= " AND list_category = 3";
    } elseif ($planType === 'TSHIP_CUA') {
        $sql .=  " AND state = ? AND provider_category = 'BANDD'";
    }
    $stmt = $conn->prepare($sql);

    if ($stmt) {
        // Bind parameters and execute the statement
        $stmt->bind_param("s", $state);
        $stmt->execute();
        $result = $stmt->get_result();

        // Fetch the results
        while ($row = $result->fetch_assoc()) {
            $hospitals[] = $row['provider_name'] . ' - ' . $row['location'];
        }

        // Close the statement
        $stmt->close();
    } else {
        // Handle SQL statement preparation error
        echo json_encode(["error" => "Failed to prepare the SQL statement"]);
        exit();
    }
} else {
    echo json_encode(["error" => "No state or planType parameter provided"]);
    exit();
}

// Close the connection
$conn->close();

// Output the JSON response
echo json_encode(['hospitals' => $hospitals]);
?>
