<?php
include('includes/config.php');

// Handle Cities by State
if (!empty($_POST["state_id"])) {
    $id = intval($_POST['state_id']);
    $query = mysqli_query($con, "SELECT * FROM cities WHERE state_id=$id ORDER BY city_name ASC");
    echo '<option value="">Select City</option>';
    while ($row = mysqli_fetch_array($query)) {
        echo '<option value="' . htmlentities($row['id']) . '">' . htmlentities($row['city_name']) . '</option>';
    }
}

// Handle Pickup Stations by City
if (!empty($_POST["city_id"])) {
    $id = intval($_POST['city_id']);
    $query = mysqli_query($con, "SELECT * FROM pickup_stations WHERE city_id=$id AND status=1 ORDER BY station_name ASC");
    if (mysqli_num_rows($query) > 0) {
        echo '<option value="">Select Pickup Station</option>';
        while ($row = mysqli_fetch_array($query)) {
            echo '<option value="' . htmlentities($row['id']) . '">' . htmlentities($row['station_name']) . ' (' . htmlentities($row['address']) . ')</option>';
        }
    } else {
        echo '<option value="">No pickup stations available in this city</option>';
    }
}

// Handle Saving Preferred Pickup Station
if (!empty($_POST["save_pickup_id"]) && !empty($_POST["user_id"])) {
    $pickup_id = intval($_POST['save_pickup_id']);
    $user_id = intval($_POST['user_id']);
    $query = mysqli_query($con, "UPDATE user_details SET preferred_pickup_id=$pickup_id WHERE user_id=$user_id");
    if ($query) {
        echo "success";
    } else {
        echo "error";
    }
}
?>