<?php 
require dirname(dirname(__FILE__)).'/inc/config.php';
require dirname(dirname(__FILE__)).'/inc/keyvaliation.php';
header('Content-type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

$pick_state_name = trim($data['pick_state_name'] ?? '');
$drop_state_name = trim($data['drop_state_name'] ?? '');

if ($pick_state_name == '' || $drop_state_name == '') {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Something Went Wrong!"
    ]);
    exit;
}

// Fetch all states from DB once
$states = [];
$result = $service->query("SELECT id, title FROM tbl_state");
while ($row = $result->fetch_assoc()) {
    $states[] = $row;
}

// Function to find best fuzzy match
function find_best_match($input, $states) {
    $input_lower = strtolower($input);
    $best_id = "0";
    $best_score = 0;

    foreach ($states as $state) {
        $title_lower = strtolower($state['title']);

        // Similarity score (0–100)
        similar_text($input_lower, $title_lower, $score);

        // Partial match boost
        if (strpos($title_lower, $input_lower) !== false || strpos($input_lower, $title_lower) !== false) {
            $score += 20;
        }

        if ($score > $best_score) {
            $best_score = $score;
            $best_id = $state['id'];
        }
    }

    // Accept if similarity > 50%
    return ($best_score > 50) ? $best_id : "0";
}

$pstate_id = find_best_match($pick_state_name, $states);
$dstate_id = find_best_match($drop_state_name, $states);

if ($pstate_id == '0' && $dstate_id == '0') {
    $returnArr = [
        "pick_state_id" => $pstate_id,
        "drop_state_id" => $dstate_id,
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Change Pick Up and Drop Location. We do not provide service at these locations!"
    ];
} else if ($pstate_id != '0' && $dstate_id == '0') {
    $returnArr = [
        "pick_state_id" => $pstate_id,
        "drop_state_id" => $dstate_id,
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Change Drop Location. We do not provide service at this location!"
    ];
} else if ($pstate_id == '0' && $dstate_id != '0') {
    $returnArr = [
        "pick_state_id" => $pstate_id,
        "drop_state_id" => $dstate_id,
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Change Pick Up Location. We do not provide service at this location!"
    ];
} else {
    $returnArr = [
        "pick_state_id" => $pstate_id,
        "drop_state_id" => $dstate_id,
        "ResponseCode" => "200",
        "Result" => "true",
        "ResponseMsg" => "Get State Id!!"
    ];
}

echo json_encode($returnArr);
?>
