<?php 
ob_start();
session_start();
include "../inc/config.php";
$today_date = date('Y-m-d');

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
}

if(isset($_POST['type']) && $_POST['type']=='zone_generation'){
     try{
        $pdo->beginTransaction(); 
            $client_id = $_POST['client_id'];
            $zone_id = $_POST['zone_id'];
            $from_city = $_POST['from_city'];
            $destination_state = $_POST['destination_state'];
            $destination_cities = $_POST['destination_city'];
            $destination_cities = implode(',', $destination_cities);
            
            $statementsss = $pdo->prepare("SELECT * FROM `tbl_generate_zone` WHERE client_id=? and from_city=? and zone_id=? and destination_state=?");
            $resultsss = $statementsss->execute(array($client_id,$from_city,$zone_id,$destination_state));
            $totalsss = $statementsss->rowCount();
            if($totalsss){
               //update code 
                $statement = $pdo->prepare("UPDATE `tbl_generate_zone` SET  client_id=?,from_city=?,zone_id=?,destination_state=?,destination_cities=? WHERE client_id=? and from_city=? and zone_id=? and destination_state=?");
       	        $result = $statement->execute(array($client_id,$from_city,$zone_id,$destination_state,$destination_cities,$client_id,$from_city,$zone_id,$destination_state));
       	        $msg="Updated";
            }else{
                //insert code 
                $statement = $pdo->prepare("INSERT INTO `tbl_generate_zone`(`client_id`,from_city,zone_id,destination_state,destination_cities) VALUES (?,?,?,?,?)");
    	        $result = $statement->execute(array($client_id,$from_city,$zone_id,$destination_state,$destination_cities));
    	        $msg="Added";
            }
        if($result){
            $last_inserted_id = $pdo->lastInsertId();
            $pdo->commit();
            $return_arr['message']='Zone Generation '.$msg.' Successfully...';
            $return_arr['status']=200;
        }
        else
        {
            $return_arr['message']='Something Went Wrong..';
            $return_arr['status']=400;
        }
     }catch(PDOException $e){
        $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}
?>