<?php
    header('Access-Control-Allow-Origin: '.$config->get('site_url'));
    header('Content-Type: application/json');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

    $response           = [];
    if($_SERVER["REQUEST_METHOD"] == "POST") {
        if(isset($_POST['csrf_token']) && $csrf_generator->validate($_POST['csrf_token']) && isset($_POST["city"])) {
            $city = strip_tags($_POST["city"]);
            $towns = array();
            $stmt = $db->query( "SELECT t.id, t.name FROM {$db->prefix}towns t LEFT JOIN {$db->prefix}cities c ON c.id=t.city_id WHERE plate_no = :city ORDER BY name ASC", array(':city'=>(int)$city));
            if($stmt->num_rows > 0) {
                foreach($stmt->rows as $row){ 
                    $item = array(
                        'id'                     => $row['id'],
                        'name'                   => $row['name']
                    );
                    array_push($towns, $item);
                }
            }
    
            $response = array('status'=>true,'towns'=>$towns);
        }else{
            $response = array('status'=>false,'text'=>"Hatalı CSRF Token!");
        }
    }else{
        $response = array('status'=>false,'text'=>"Hatalı İstek!");
    }

    echo json_encode($response);