<?php
$servername = "localhost";
$username = "uzx1egl6mvonn";
$password = "wfcdg8d9esqn";
$dbname = "dbpwyq3swetihg";

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

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

$action = $_POST['action'] ?? '';

$response = [];

if ($action === 'fetch_states') {
    $query = "SELECT DISTINCT state FROM clinicslistwithstateandcity ORDER BY state ASC";
    $result = $conn->query($query);

    $states = "";
    while ($row = $result->fetch_assoc()) {
        $states .= "<option value='" . htmlspecialchars($row['state']) . "'>" . htmlspecialchars($row['state']) . "</option>";
    }
    $states .= "<option value='other'>Other</option>";
    
    $response['states'] = $states;
}

elseif ($action === 'fetch_cities' && !empty($_POST['state'])) {
    $state = $_POST['state'];
    $stmt = $conn->prepare("SELECT DISTINCT city FROM clinicslistwithstateandcity WHERE state = ? ORDER BY city ASC");
    $stmt->bind_param("s", $state);
    $stmt->execute();
    $result = $stmt->get_result();

    $cities = "<option value='Select City'>Select City</option>";
    while ($row = $result->fetch_assoc()) {
        $cities .= "<option value='" . htmlspecialchars($row['city']) . "'>" . htmlspecialchars($row['city']) . "</option>";
    }
    $cities .= "<option value='other'>Other</option>";
    
    $response['cities'] = $cities;
    $stmt->close();
}

elseif ($action === 'fetch_clinics' && !empty($_POST['city'])) {
    $city = $_POST['city'];
    $stmt = $conn->prepare("SELECT id, clinic_names FROM clinicslistwithstateandcity WHERE city = ? ORDER BY clinic_names ASC");
    $stmt->bind_param("s", $city);
    $stmt->execute();
    $result = $stmt->get_result();

    $clinics = "<option value='Select Clinic'>Select Clinic</option>";
    while ($row = $result->fetch_assoc()) {
        $clinics .= "<option value='" . htmlspecialchars($row['id']) . "'>" . htmlspecialchars($row['clinic_names']) . "</option>";
    }
    $clinics .= "<option value='other'>Other</option>";
    
    $response['clinics'] = $clinics;
    $stmt->close();
}

echo json_encode($response);
$conn->close();
?>
