<?php

include('custom-function.php');
$getImgRootPath=$_SERVER['DOCUMENT_ROOT']."/wp-content/themes/adventure-republiq/operator/uploads/";
$uploadDir = $_SERVER['DOCUMENT_ROOT']."/wp-content/themes/adventure-republiq/operator/uploads/";
include('db.php');
if(($_REQUEST['Action']=='generalAction')){
    $oid = $conn->real_escape_string($_REQUEST['oid'] ?? '');
    $new_password = $_POST['new_password'] ?? '';
    $repeat_password = $_POST['repeat_password'] ?? '';

    // Validate passwords
    if (empty($new_password) || empty($repeat_password)) {
        echo  'Both password fields are required';
        exit;
    }

    if ($new_password !== $repeat_password) {
          echo  "Passwords do not match";

        exit;
    }

    // Hash the password using MD5
    $hashed_password = md5($new_password);

    // Update the password in the database
    $update_sql = "UPDATE wpwr_users SET user_pass = '$hashed_password' WHERE ID = '$oid'";
    
    if ($conn->query($update_sql) === TRUE) {
        echo  "Password updated successfully";
    } else {
       echo  "PaError updating password";
        //echo json_encode(['status' => 'error', 'message' => 'Error updating password: ' . $conn->error]);
    }
    exit;
}
if(($_REQUEST['Action']=='opfullaccess')){
  // error_reporting(E_ALL);
  // ini_set('display_errors', 1);
  // ini_set('display_startup_errors', 1);
  
      $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
      $roles=$conn -> real_escape_string($_REQUEST['roles']?? '');
      $first_name=$conn -> real_escape_string($_REQUEST['first_name']?? '');
      $phone=$conn -> real_escape_string($_REQUEST['phone']?? '');
      $pcc=$conn -> real_escape_string($_REQUEST['pcc']?? '');
      $whatsapp=$conn -> real_escape_string($_REQUEST['whatsapp']?? '');
      $companyname=$conn -> real_escape_string($_REQUEST['companyname']?? '');
      $headlocation=$conn -> real_escape_string($_REQUEST['headlocation']?? '');
      $latitude=$conn -> real_escape_string($_REQUEST['latitude']?? '');
      $longitude=$conn -> real_escape_string($_REQUEST['longitude']?? '');
      $address1=$conn -> real_escape_string($_REQUEST['address1']?? '');
      $address2=$conn -> real_escape_string($_REQUEST['address2']?? '');
      $facebook=$_REQUEST['facebook']?? '';
      $instagram =$_REQUEST['instagram']?? '';
      $youtube=$_REQUEST['youtube']?? '';
      $toursell=$conn -> real_escape_string($_REQUEST['toursell']?? '');
      $decribes=$conn -> real_escape_string($_REQUEST['decribes']?? '');
      $skype=$conn -> real_escape_string($_REQUEST['skype']?? '');
      $infoprovide=$conn -> real_escape_string($_REQUEST['infoprovide']?? '');
      $guides=$conn -> real_escape_string($_REQUEST['guides']?? '');
      if($guides=='Yes'):
         $nocontrguide='';
      else:
             $nocontrguide=$conn -> real_escape_string($_REQUEST['nocontrguide']?? '');
      endif;   
      if(!empty($nocontrguide)):
             $guides='No';
      endif;          
      $owntrasnport=$conn -> real_escape_string($_REQUEST['owntrasnport']?? '');
      $trcontract=$conn -> real_escape_string($_REQUEST['trcontract']?? '');
      $ownhotels=$conn -> real_escape_string($_REQUEST['ownhotels']?? '');
      $htcontract=$conn -> real_escape_string($_REQUEST['htcontract']?? '');
      $contactadventure=$conn -> real_escape_string($_REQUEST['contactadventure']?? '');
      $cntfullname=$conn -> real_escape_string($_REQUEST['cntfullname']?? '');
      $compemail=$conn -> real_escape_string($_REQUEST['compemail']?? '');
      $compphone=$conn -> real_escape_string($_REQUEST['compphone']?? '');
      $compskyup=$conn -> real_escape_string($_REQUEST['compskyup']?? '');
      $complocation=$conn -> real_escape_string($_REQUEST['complocation']?? ''); 
      $resfullname=$conn -> real_escape_string($_REQUEST['resfullname']?? '');
      $resemail=$conn -> real_escape_string($_REQUEST['resemail']?? '');
      $rpcc=$conn -> real_escape_string($_REQUEST['rpcc']?? '');
      $resphoneno=$conn -> real_escape_string($_REQUEST['resphoneno']?? '');
      $reswhatapp=$conn -> real_escape_string($_REQUEST['reswhatapp']?? '');
      $day1M=$conn -> real_escape_string($_REQUEST['monstart']?? '');
      $day1E=$conn -> real_escape_string($_REQUEST['monend']?? '');
      $day2M=$conn -> real_escape_string($_REQUEST['tuestart']?? '');
      $day2E=$conn -> real_escape_string($_REQUEST['tueend']?? '');
      $day3M=$conn -> real_escape_string($_REQUEST['wedstart']?? '');
      $day3E=$conn -> real_escape_string($_REQUEST['wedend']?? '');
      $day4M=$conn -> real_escape_string($_REQUEST['thurstart']?? '');
      $day4E=$conn -> real_escape_string($_REQUEST['thurend']?? '');
      $day5M=$conn -> real_escape_string($_REQUEST['fristart']?? '');
      $day5E=$conn -> real_escape_string($_REQUEST['friend']?? '');
      $day6M=$conn -> real_escape_string($_REQUEST['satstart']?? '');
      $day6E=$conn -> real_escape_string($_REQUEST['satend']?? '');
      $day7M=$conn -> real_escape_string($_REQUEST['sunstart']?? '');
      $day7E=$conn -> real_escape_string($_REQUEST['sunend']);
      $url=$conn -> real_escape_string($_REQUEST['url']);
      $pscode=$conn -> real_escape_string($_REQUEST['postalcode']);  
      $city=$conn -> real_escape_string($_REQUEST['city']);
      $checkquery=$conn->query("select * from operator_details where oids='$oid'");
       $countopr= $checkquery->num_rows;
       if($countopr==0)
       {
           
           $sql =  $conn->query("INSERT INTO operator_details (oids, roles, pcc, phoneno,whatsapp,companyname,
                               headlocation,address1,address2,zipcode,city,facebook,instagram,youtube,skype,guides,
                               nocontrguide,owntrasnport,trcontract,ownhotels,htcontract,latitude,longitude)
                    VALUES ('$oid', '$roles','$pcc','$phone', '$whatsapp', '$companyname','$headlocation', '$address1','$address2',
                           '$pscode','$city','$facebook','$instagram','$youtube','$skype','$guides','$nocontrguide'
                           ,'$owntrasnport','$trcontract','$ownhotels','$htcontract','$latitude','$longitude')");
                       
                       $conn->query($sql);
          
       }
       else
       {
       $sql = "UPDATE operator_details   
                  SET roles='$roles',
                  pcc='$pcc',
                  phoneno='$phone',
                  whatsapp='$whatsapp',
                  companyname='$companyname',
                  headlocation='$headlocation',
                  address1='$address1',
                  address2='$address2',
                  zipcode='$pscode',
                  city='$city',
                  facebook='$facebook',
                  instagram='$instagram',
                  youtube='$youtube',
                  skype='$skype',
                  guides='$guides',
                  nocontrguide='$nocontrguide',
                  owntrasnport='$owntrasnport',
                  trcontract='$trcontract',
                  ownhotels='$ownhotels',
                  htcontract='$htcontract',
                  latitude='$latitude',
                  longitude='$longitude'
                  WHERE oids='$oid'";
                    $conn->query($sql);
       }          
    
      $sqlname = "UPDATE wpwr_usermeta   SET meta_value='$first_name' WHERE user_id='$oid' and meta_key='first_name'";
      $conn->query($sqlname);
      $sqlurl = "UPDATE wpwr_users   SET user_url='$url' WHERE ID='$oid'";
      $conn->query($sqlurl);
      $resfullname=$conn -> real_escape_string($_REQUEST['resfullname']?? '');
      $resemail=$conn -> real_escape_string($_REQUEST['resemail']?? '');
      $rpcc=$conn -> real_escape_string($_REQUEST['rpcc']?? '');
      $resphoneno=$conn -> real_escape_string($_REQUEST['resphoneno']?? '');
      $reswhatapp=$conn -> real_escape_string($_REQUEST['reswhatapp']?? '');
      $reslocation=$conn -> real_escape_string($_REQUEST['reslocation']?? ''); 
      $day1M=$conn -> real_escape_string($_REQUEST['monstart']?? '');
      $day1E=$conn -> real_escape_string($_REQUEST['monend']?? '');
      $day2M=$conn -> real_escape_string($_REQUEST['tuestart']?? '');
      $day2E=$conn -> real_escape_string($_REQUEST['tueend']?? '');
      $day3M=$conn -> real_escape_string($_REQUEST['wedstart']?? '');
      $day3E=$conn -> real_escape_string($_REQUEST['wedend']?? '');
      $day4M=$conn -> real_escape_string($_REQUEST['thurstart']?? '');
      $day4E=$conn -> real_escape_string($_REQUEST['thurend']?? '');
      $day5M=$conn -> real_escape_string($_REQUEST['fristart']?? '');
      $day5E=$conn -> real_escape_string($_REQUEST['friend']?? '');
      $day6M=$conn -> real_escape_string($_REQUEST['satstart']?? '');
      $day6E=$conn -> real_escape_string($_REQUEST['satend']?? '');
      $day7M=$conn -> real_escape_string($_REQUEST['sunstart']?? '');
      $day7E=$conn -> real_escape_string($_REQUEST['sunend']?? '');
      $jsondata = '{"monM":"'.$day1M.'", 
                    "monE":"'.$day1E.'",
                    "tueM":"'.$day2M.'",
                    "tueE":"'.$day2E.'",
                    "wedM":"'.$day3M.'",
                    "wedE":"'.$day3E.'",
                    "thurM":"'.$day4M.'",
                    "thurE":"'.$day4E.'",
                    "friM":"'.$day5M.'",
                    "friE":"'.$day5E.'",
                    "satM":"'.$day6M.'",
                    "satE":"'.$day6E.'",
                    "sunM":"'.$day7M.'",
                    "sunE":"'.$day7E.'"}'; 

                    $checkResv=$conn->query("select * from operator_reservation where oid='$oid'");
                    $countResv= $checkResv->num_rows;
                    if($countResv==0) {

                      $sql =  $conn->query("INSERT INTO operator_reservation (oid, resfullname, resemail, rpcc, resphoneno,reswhatapp,reslocation,hours)
                    VALUES ('$oid', '$resfullname', '$resemail','$rpcc','$resphoneno', '$reswhatapp', '$reslocation','$jsondata')");
                       $conn->query($sql);
       
        
                    }
                    else {

                       $sqlresv = "UPDATE operator_reservation  
                      SET 
                      resfullname='$resfullname',
                      resemail='$resemail',
                      rpcc='$rpcc',
                      resphoneno='$resphoneno',
                      reswhatapp='$reswhatapp',
                      reslocation='$reslocation',
                      hours='$jsondata'
                      WHERE oid='$oid'";
                      $conn->query($sqlresv);
                    }



  }
if($_REQUEST['Action']=='day-cal-price'){
   
     $dayprice=$conn -> real_escape_string($_REQUEST['dayprice']);
     $seats=$conn -> real_escape_string($_REQUEST['seats']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $oid=$conn -> real_escape_string($_REQUEST['oid']); 
     $daypricedate=$_REQUEST['daypricedata'];
     $cust_currency=$conn -> real_escape_string($_REQUEST['cust_currency']); 
     $getData=$conn->query("select * from tour_day_price_calender where  daypricedate= '$daypricedate' and  oid= '$oid' and tid='$tid'");
     $checknum= $getData->num_rows;
     if($checknum>0){
                 $conn->query("UPDATE tour_day_price_calender  SET  price='$dayprice',  seats='$seats' WHERE daypricedate= '$daypricedate' and tid='$tid'");
     }
     else{
        
           $sql = "INSERT INTO tour_day_price_calender (tid,oid, daypricedate,price,seats,active) VALUES ('$tid', '$oid', '$daypricedate','$dayprice','$seats',0)";
           $conn->query($sql);
     }
      $data=$conn->query("select tours_price_data.tourdates,tours_price_data.seats,tours_price_data.tourprice from tours_price_data where tid='$tid'");
      $fetchdetails=$data -> fetch_assoc();
      $GetDates = explode(',', $fetchdetails['tourdates']);
      $date = str_replace('/', '-', $GetDates);
           function date_sort($a, $b) {
               return strtotime($a) - strtotime($b);
           }
        usort($date, "date_sort");
        $nowDate=date('d-m-Y');
        $unixCrDate=strtotime($nowDate);

    ?>
     <table class="table">
           <tbody>
                  <tr class="custom">
                       <th scope="col">Sr. no</th>
                       <th scope="col">Date</th>
                       <th scope="col">Seats</th>
                       <th scope="col">Price</th>
                       <th scope="col">Add/Edit Day Price</th> 
                   </tr>
               <?php
                   $i=1;
                    $UpdateValue=array();
                    foreach($date as $compareDate)
                                       {
                                         $unixCompareDate=strtotime($compareDate);
                                          if($unixCompareDate>=$unixCrDate)
                                           {
                                               $UpdateValue[]=date('d-m-Y', $unixCompareDate);
                                               $dayPriceDate=date('d/m/Y', $unixCompareDate);
                                          
                                           ?>
                                               <tr>
                                                  <td><?php echo $i;?></td>
                                                  <td><?php echo date('d-m-Y', $unixCompareDate);?></td>
                                                  <td><?php echo $fetchdetails['seats'];?></td>
                                                 
                                                  <td><?php echo day_price_calender($cust_currency,$tid,$dayPriceDate);?></td>
                                                  <td><a herf="javascript:void()" data-pricedata="<?php echo $dayPriceDate;?>" data-toggle="modal" data-target="#caldayPrice" class="dayprice">Add/Edit</a></td>
                                                </tr>
                                           <?php
                                           }
                                           $i++; 
                                         }
      
                                          ?>
                                </tbody>
                           </table>
    <?php
    
    

    
} 

function day_price_calender($cust_currency,$tid,$dayPriceDate){
         
         include(dirname( __FILE__ ) . '/db.php');
         $query=$conn->query("select * from tour_day_price_calender where tid='$tid'");
       
         while($fetchdata=$query -> fetch_assoc()){
             if($dayPriceDate==$fetchdata['daypricedate']){
                 echo $cust_currency.number_format($fetchdata['price'],2);
             }
           
           
        }
}


 if($_REQUEST['playvideo']){
        $tid=$conn -> real_escape_string($_REQUEST['tid']);
        $getData=$conn->query("select * from tours where  tid='$tid'");
        $fetchInclude=$getData -> fetch_assoc();
        $video_id = explode("?v=", $fetchInclude['tourvideo']);
                                $video_id = $video_id[1];
        ?>
        
       <iframe width="100%" height="350"
            src="https://www.youtube.com/embed/<?php echo $video_id;?>" 
                                   frameborder="0" allowfullscreen>
                           </iframe>
      <?php
}
 if($_REQUEST['delvideo']){
      
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $mid=$conn -> real_escape_string($_REQUEST['mid']);
     $conn->query("UPDATE tours  SET  tourvideo='' WHERE id= '$mid'");
     echo tour_dashboard_list($oid);
} 
if($_REQUEST['Action']=='AddVideo'){
     $videourl=$conn -> real_escape_string($_REQUEST['videourl']);
      $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $conn->query("UPDATE tours  SET  tourvideo='$videourl' WHERE tid= '$tid'");
     echo tour_dashboard_list($oid);
    
}

if($_REQUEST['Action']=='toursinclude'){

 error_reporting(E_ALL);

     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $thistrtype=$conn -> real_escape_string($_REQUEST['thistrtype']);
     $accdecp=$conn -> real_escape_string($_REQUEST['accdecp']);
     $accstatus=$conn -> real_escape_string($_REQUEST['accstatus']);
     $flightdecp=$conn -> real_escape_string($_REQUEST['flightdecp']);
     $guidedecp=$conn -> real_escape_string($_REQUEST['guidedecp']);
     $flightdecp=$conn -> real_escape_string($_REQUEST['flightdecp']);
     $insurance=$conn -> real_escape_string($_REQUEST['insurance']);
     $mealsdecp=$conn -> real_escape_string($_REQUEST['mealsdecp']);  
     $transtranportdecp=$conn -> real_escape_string($_REQUEST['transtranportdecp']);
     $optionaldecp=$conn -> real_escape_string($_REQUEST['optionaldecp']);
     $otherinc=$conn -> real_escape_string($_REQUEST['otherinc']);
     $othernotinc=$conn -> real_escape_string($_REQUEST['othernotinc']);
     $covid='';
     $flsstatus=$conn -> real_escape_string($_REQUEST['flsstatus']);
     $guidestatus=$conn -> real_escape_string($_REQUEST['guidestatus']);
     $mealstatus=$conn -> real_escape_string($_REQUEST['mealstatus']);
     $insrstatus=$conn -> real_escape_string($_REQUEST['insrstatus']);
     $transstatus=$conn -> real_escape_string($_REQUEST['transstatus']);
     $optstatus = isset($_REQUEST['optstatus']) ? $conn->real_escape_string($_REQUEST['optstatus']) : '';
     $othstatus = isset($_REQUEST['othstatus']) ? $conn->real_escape_string($_REQUEST['othstatus']) : '';
     $othnotstatus = $conn->real_escape_string($_REQUEST['othnotstatus'] ?? '');
     $artstatus=$conn -> real_escape_string($_REQUEST['artstatus'] ?? '');
     $artstatusdecp=$conn -> real_escape_string($_REQUEST['artstatusdecp'] ?? '');
     $getData=$conn->query("select * from tours_include where oid='$oid' and  tid='$tid'");
     $checknum= $getData->num_rows;
     $fetchInclude=$getData -> fetch_assoc();
     $oldaccType = $fetchInclude['acctype'] ?? '';
     $newaccType= array();
     $acclocation=  $_REQUEST['location'] ?? '';
     $accnights= $_REQUEST['nights'] ?? '';
     $acctype= $_REQUEST['acctype'] ?? '';
     $accname= $_REQUEST['name'] ?? '';
     $accrating= $_REQUEST['rating'] ?? '';
     $occtype= $_REQUEST['accmoocctype'] ?? '';
     $count = count($acclocation);
     for ( $i = 0; $i < $count; $i++ ) {
         if ( $acclocation[$i] != '' ) :
         $newaccType[$i]['location'] = $acclocation[$i];
         $newaccType[$i]['nights'] = $accnights[$i];
         $newaccType[$i]['acctype'] = $acctype[$i];
         $newaccType[$i]['name'] = $accname[$i];
         $newaccType[$i]['rating'] = $accrating[$i];
         $newaccType[$i]['occtype'] = $occtype[$i];
         
         endif;
   }

   if ( !empty( $newaccType ) && $newaccType != $oldaccType ){
             $jsonacctype= $conn -> real_escape_string(json_encode($newaccType));
           
   }
   elseif ( empty($newaccType) && $oldaccType ){
            $jsonacctype= $conn -> real_escape_string(json_encode($oldaccType));
          }

     $oldFood = $fetchInclude['foodtypes'] ?? '';
     $newFood= array();
     $foodType = $_REQUEST['foodtypes'] ?? '';
     $count = is_array($foodType) ? count($foodType) : 0;
     //$count = count($foodType);
     for ( $i = 0; $i < $count; $i++ ) {
         if ($foodType[$i]!= '' ) :
         $newFood[$i]['foodtype'] = stripslashes($foodType[$i]);
         endif;
   }
 
   if ( !empty( $newFood) && $newFood != $oldFood ){
             $jsonfoodtypes= json_encode($newFood);
           
   }
   elseif ( empty($newFood) && $oldFood ){
              $jsonfoodtypes= json_encode($oldFood);
       }
         $oldTransport== $fetchInclude['transtranporttype'] ?? '';
         $newTransport= array();
         $transportType = $_REQUEST['transtranporttype'] ?? [];

         // Make sure it's an array before counting
         if (!is_array($transportType)) {
             $transportType = [$transportType]; // Convert single value to array
         }
         
         $counttrans = count($transportType);
         for ( $i = 0; $i < $counttrans; $i++ ) {
             if ($transportType[$i]!= '' ) :
             $newTransport[$i]['transport'] = stripslashes($transportType[$i]);
             endif;
          }
     
       if ( !empty( $newTransport) && $newTransport != $oldTransport ){
                 $jsontransport= json_encode($newTransport);
               
       }
       elseif ( empty($newTransport) && $oldTransport ){
                  $jsontransport= json_encode($oldTransport);
           }
     $oldlistAcctype = $fetchInclude['accomodation'] ?? '';
     $newlistAcctype= array();
     $accomodation = $_REQUEST['accomodation'] ?? [];
     $countaccomodation = is_array($accomodation) ? count($accomodation) : 0;
     for ( $i = 0; $i < $countaccomodation; $i++ ) {
         if ($accomodation[$i]!= '' ) :
         $newlistAcctype[$i]['accomodation'] = stripslashes($accomodation[$i]);
         endif;
   }
 
   if ( !empty( $newlistAcctype) && $newlistAcctype != $oldlistAcctype ){
             $jsonlist= json_encode($newlistAcctype);
           
   }
    elseif ( empty($newlistAcctype) && $newlistAcctype ){
                  $jsonlist= json_encode($oldlistAcctype);
           }
           
           $oldTransport== $fetchInclude['transtranporttype'] ?? '';
         $newTransport= array();
         $transportType = $_REQUEST['transtranporttype'] ?? '';
         $counttrans = is_array($transportType) ? count($transportType) : 0;
         for ( $i = 0; $i < $counttrans; $i++ ) {
             if ($transportType[$i]!= '' ) :
             $newTransport[$i]['transport'] = stripslashes($transportType[$i]);
             endif;
          }
     
       if ( !empty( $newTransport) && $newTransport != $oldTransport ){
                 $jsontransport= json_encode($newTransport);
               
       }
       elseif ( empty($newTransport) && $oldTransport ){
                  $jsontransport= json_encode($oldTransport);
           }
     $oldpickuplocation = $fetchInclude['picklocation'] ?? '';
     $newpickuplocation= array();
     $pickuplocation= $_REQUEST['pickuplocation'] ?? '';
     $countpickuplocation = count($pickuplocation);
     for ( $i = 0; $i < $countpickuplocation; $i++ ) {
         if ($pickuplocation[$i]!= '' ) :
         $newpicklocation[$i]['pickuplocation'] = stripslashes($pickuplocation[$i]);
         endif;
   }
 
       if ( !empty( $newpicklocation) && $newpicklocation != $oldpickuplocation ){
                 $jsonpicklocation= json_encode($newpicklocation);
               
       }
        elseif ( empty($newpicklocation) && $newpicklocation ){
                      $jsonpicklocation= json_encode($oldpickuplocation);
               }
           

       if($checknum<1)
        {
       
       $sql = "INSERT INTO tours_include (tid,oid,accdecp,acctype,listacctype,accstatus,flightdecp,flsstatus,guidedecp, mealsdecp,foodtypes,insurance,transtranportdecp,
            transtranporttype,optionaldecp,otherinc,guidestatus,mealstatus,insrstatus,transstatus,optstatus,othernotinc,covid, artstatus,artstatusdecp,picklocation)
            
         VALUES ('$tid', '$oid', '$accdecp', '$jsonacctype', '$jsonlist','$accstatus','$flightdecp','$flsstatus','$guidedecp','$mealsdecp','$jsonfoodtypes','$insurance',
              '$transtranportdecp','$jsontransport','$optionaldecp','$otherinc','$guidestatus','$mealstatus','$insrstatus','$transstatus','$optstatus','$othernotinc','$covid','$artstatus','$artstatusdecp','$jsonpicklocation')";
                $conn->query($sql);
     


        }
        else {
      //  if($acctype) {
      //    $updateAcctype="acctype='$jsonacctype',";

      //  }
      //  else {
      //      $updateAcctype="acctype='NULL',";

      //  }
      // if($accdecp) {
      //    $updateAccdecp="accdecp='$accdecp',";
      //  }
      //  if($jsonlist) {
      //    $updateList="accdecp='$jsonlist',";
      //  }
      //  if($flightdecp) {
      //    $updateFlight="flightdecp='$flightdecp',";
      //  }
      //  if($guidedecp) {
      //    $updateGuide="guidedecp='$guidedecp',";
      //  }
      //  if($mealsdecp) {
      //    $updateMeal="mealsdecp='$mealsdecp',";
      //  }
      //  if($jsonfoodtypes) {
      //    $updateFoodtypes="foodtypes='$jsonfoodtypes',";
      //  }
      // if($insurance) {
      //    $updateInsr="insurance='$insurance',";
      //  }
      //  if($transtranportdecp) {
      //    $updateTranportDecp="transtranportdecp='$transtranportdecp',";
      //  }
      //  if($jsontransport) {
      //    $updateTransport="transtranporttype='$jsontransport',";
      //  }
      //  if($optionaldecp) {
      //    $updateOptionaldecp="optionaldecp='$optionaldecp',";
      //  }
      //  if($otherinc) {
      //    $updateOtherinc="otherinc='$otherinc',";
      //  }
      //  if($flightdecp) {
      //    $updateFlightdecp="flightdecp='$flightdecp',";
      //  }
      //   if($othernotinc) {
      //    $updateOtherNotinc="othernotinc='$othernotinc',";
      //  }
      //   if($othnotstatus) {
      //    $updateOtherNotStatus="othnotstatus='$othnotstatus',";
      //  }
      //   if($artstatusdecp) {
      //    $updateArtstatusDecp="artstatusdecp='$artstatusdecp',";
      //  }

      //  if($jsonpicklocation) {
      //    $updatePickLocation="picklocation='$jsonpicklocation',";
      //  }
      if($othnotstatus=='') {
          $othnotstatus=0;
      }
    $sqlopdt = "UPDATE tours_include  SET 
                 accdecp='$accdecp',
                 acctype='$jsonacctype',
                 listacctype='$jsonlist', 
                 accstatus='$accstatus', 
                 flightdecp='$flightdecp',
                 guidedecp='$guidedecp',
                 mealsdecp='$mealsdecp', 
                 foodtypes='$jsonfoodtypes',
                 insurance='$insurance',
                 transtranportdecp='$transtranportdecp', 
                 transtranporttype='$jsontransport',
                 optionaldecp='$optionaldecp',
                 otherinc='$otherinc',
                 flightdecp='$flightdecp',
                 flsstatus='$flsstatus',
                 guidestatus='$guidestatus',
                 mealstatus='$mealstatus',
                 insrstatus='$insrstatus',
                 transstatus='$transstatus',
                 optstatus='$optstatus',
                 othernotinc='$othernotinc',
                 othnotstatus='$othnotstatus',
                 covid='$covid',
                 artstatus='$artstatus',
                 artstatusdecp='$artstatusdecp',
                 picklocation='$jsonpicklocation' 
                 WHERE oid='$oid' and  tid='$tid'";
                 $conn->query($sqlopdt);
        }

}

if(($_REQUEST['Action']=='goodtoknow')){
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $thistrtype=$conn -> real_escape_string($_REQUEST['thistrtype']);  
     $goodtoknow=$conn -> real_escape_string($_REQUEST['goodtoknow']);
     $addonfaqs=$conn -> real_escape_string($_REQUEST['addonfaqs']);
     $sqlopdt = "UPDATE  touraddons  SET 
                 goodtoknow='$goodtoknow', faqs='$addonfaqs'
                 WHERE oid='$oid' and  tid='$tid'";
     $conn->query($sqlopdt);
  
        
}
if(($_REQUEST['Action']=='AddItinerary')){
 include('db.php');
 ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(1);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $trtype=$conn -> real_escape_string($_REQUEST['thistrtype']);
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $pickupdescription=$conn -> real_escape_string($_REQUEST['pickupdescription']);
     $pcfromtime=$conn -> real_escape_string($_REQUEST['pcfromtime']);
     $pcendtime=$conn -> real_escape_string($_REQUEST['pcendtime']);
     $dropdescription=$conn -> real_escape_string($_REQUEST['dropdescription']);
     $dropfromtime=$conn -> real_escape_string($_REQUEST['dropfromtime']);
     $dropendtime=$conn -> real_escape_string($_REQUEST['dropendtime']);

     $getData=$conn->query("select * from tour_itinerary  WHERE oid='$oid' AND tid='$tid'");
     $row_cnt = $getData->num_rows;
     $fetchmeta=$getData -> fetch_assoc();

     

      /* Add Json tour  destination */

      $oldDestination  = $fetchmeta['destination'];
      $newDestination = array();
      $tax_input = $_REQUEST['tax_input'];
      $singleArray = []; 
       foreach ($tax_input as $childArray) 
       { 
           foreach ($childArray as $value) 
           { 
               if($value>0){
                   $singleArray[] = $value;  
               }
          
           } 
       }
      
      $count = count($singleArray);
   
      for ($i = 0; $i < $count; $i++ ) {
         if ( $singleArray[$i] != '' ) :
         $newDestination[$i]['destination'] = stripslashes($singleArray[$i]);
         endif;
      }
       $converjson=json_encode($newDestination);  
      if($oldDestination!=$converjson){
          $jsondestination=$converjson;
      }
      else{
           $jsondestination=$oldDestination;
      }


  /* Add Json Days Itinerary */
  $gettitle = $_REQUEST['gettitle'] ?? [];
  $countData = is_array($gettitle) ? count($gettitle) : 0;
       $description=$_REQUEST['getdescription'];
       $oldItinerary  = $fetchmeta['itineraryData'];
       $newItinerary = array();
     
    
      for ($j = 0; $j < $countData; $j++ ) {
         if ( $gettitle[$j] != '' ) :
              $newItinerary[$j]['gettitle']  = $gettitle[$j];
              $newItinerary[$j]['description'] =$_REQUEST['getdescription'][$j];
         endif;
      }

     $converitjson=$conn -> real_escape_string(json_encode($newItinerary));  
      if($oldItinerary!=$converitjson){
     
          $jsondata=$converitjson;
      }
      else{
           $jsondata=$oldItinerary;
      }

     if($row_cnt==0) {
          $sql = "INSERT INTO tour_itinerary (tid,oid,destination,pickupdescription,pcfromtime,pcendtime,dropfromtime,dropendtime,itineraryData,dropdescription)
             VALUES ('$tid', '$oid', '$jsondestination', '$pickupdescription', '$pcfromtime', '$pcendtime','$dropfromtime','$dropendtime','$jsondata','$dropdescription')";
           $conn->query($sql);
        }

     else
     { 
       $sql =   "UPDATE tour_itinerary  SET 
                 destination='$jsondestination',
                 pickupdescription='$pickupdescription',
                 pcfromtime='$pcfromtime',
                 pcendtime='$pcendtime',
                 dropfromtime='$dropfromtime',
                 dropendtime='$dropendtime',
                 dropdescription='$dropdescription',
                 itineraryData='$jsondata'
                 WHERE oid='$oid' AND tid='$tid'";
       $conn->query($sql);
     

      
        }

      
    }
if($_REQUEST['deletephotos'])
 {
     $removeData=array();
     $delid=$_REQUEST['imgid'];
       $tourid=$_REQUEST['tid'];
       $thistrtype=$_REQUEST['thistrtype'];
       $formid=$_REQUEST['formid'];
   $selectSql = $conn->query("select * from tour_images where id = '$delid'");
      $getRow = $selectSql -> fetch_assoc();
     $updateArray=array();
     $delfile='/wp-content/themes/adventure-republiq/operator/uploads/'.$_REQUEST['imagname'];
           $removeData[]=$_REQUEST['imagname'];
               $getimgdata=explode(",",$getRow['tourimages']);
                foreach($getimgdata as $ShowData)
                {
                       if(!in_array( $ShowData, $removeData)){
                          $updateArray[]=$ShowData;
                       }
                 }
                 $List = implode(',',$updateArray); 
                 $conn->query("UPDATE tour_images  SET  tourimages='$List' WHERE id= '$delid'");
                 $get_photos=explode(",",$List);
                 unlink($delfile);
           ?>
          <ul> 
            <?php
                $i=0;
                    foreach($updateArray as $photos ){
                        if($photos) { ?>
                        <li><img src="/wp-content/themes/adventure-republiq/operator/uploads/<?php echo $photos;?>">
                           <a href="javascript:void(0);" data-count="<?php echo count($updateArray);?>" class="delgallery" data-tid="<?php echo $tourid ;?>"  data-thistrtype="<?php echo rtrim($thistrtype, '/');?>"
                           data-imgid="<?php echo $delid;?>" data-imagname="<?php echo $photos?>"  data-formid="<?php echo $formid;?>">
                              <i class="fa fa-trash" aria-hidden="true"></i>
                            </a>
                         </li>
                        <?php
                        $i++;
                        }
                    }
                
                 ?>
                </ul>
                <script type="text/javascript" src="https://dashboard.adventurerepubliq.com/wp-content/themes/adventure-republiq/operator/js/scripts.js"></script>
          <?php

   }
if($_REQUEST['Action']=='seatUpdatePrice'){
    
      $oid=$conn -> real_escape_string($_REQUEST['oid']);
      $tid=$conn -> real_escape_string($_REQUEST['tid']);

      $singleprice=$_REQUEST['singleprice'];
      $enablemulti=$_REQUEST['enablemulti'];
      $tourdates=$_REQUEST['tourdates'];
      $seats=$_REQUEST['seats'];
      $operating_type=$conn -> real_escape_string($_REQUEST['operating_type']?? '');
      
      if($operating_type==0) {
          $operating_type_label='grouponly';
      }
       if($operating_type==1) {
          $operating_type_label='private_tr_booking';
      }
       if($operating_type==2) {
          $operating_type_label='bothgrpr';
      }

      $query=$conn->query("select * from tours_price_data where oid='$oid' and  tid='$tid'");
      $fetchPriceData=$query -> fetch_assoc();
    
    /* Insert Multiple Tour Time */

     $oldtourtime = $fetchPriceData['tourtime'];
     $newtourtime= array();
     $starttime= $_REQUEST['starttime'];
     $timecount = count($starttime);
           for ( $i = 0; $i < $timecount; $i++ ) {
               if ( $starttime[$i] != '' ) :
                   $newtourtime[$i]['starttime'] = stripslashes($starttime[$i]);
                 endif;
         }    
           if ( !empty( $newtourtime ) && $newtourtime != $oldtourtime ){
                    $jsontimes= json_encode($newtourtime);
                
         }
           elseif ( empty($newtourtime) && $oldtourtime ){
                    $jsontimes= json_encode($oldtourtime);
                    
            }

       /* Insert Multiple Price Optioon */   
       
             $oldtPriceOpt = $fetchPriceData['priceoption'];
             $newPriceOpt=  array();  

             $mulperson= $_REQUEST['mulperson'];
             $price= $_REQUEST['price'];
             $percount = count($mulperson);
           for ( $i = 0; $i < $percount; $i++ ) {
               if ( $mulperson[$i] != '' &&  $price[$i]!='') :
               $newPriceOpt[$i]['perpeson'] = stripslashes($mulperson[$i]);
               $newPriceOpt[$i]['price'] = stripslashes($price[$i]);
                 endif;
         }    
           if ( !empty( $newPriceOpt ) && $newPriceOpt != $oldtPriceOpt ){
                    $jsonmultiprice= json_encode($newPriceOpt);
                
         }
           elseif ( empty($newPriceOpt) && $oldtPriceOpt ){
                    $jsonmultiprice= json_encode($oldtPriceOpt);
                    
            }

    
       /* Insert Multiple Other Price Option */   
       
             $oldPriceCat = $fetchPriceData['otherpricecat'];
             $newPriceCat=  array();  

             $othtitle= $_REQUEST['TitleItem'];
             $optage= $_REQUEST['OptionalAge'];
             $optprice= $_REQUEST['optprice'];
             $othcount = count($othtitle);
             
           for ( $i = 0; $i < $othcount; $i++ ) {
               if ( $othtitle[$i] != '' ) :
               $newPriceCat[$i]['title'] = stripslashes($othtitle[$i]);
               $newPriceCat[$i]['age'] = stripslashes($optage[$i]);
               $newPriceCat[$i]['price'] = stripslashes($optprice[$i]);
                 endif;
         }    
           if ( !empty( $newPriceCat ) && $newPriceCat != $oldPriceCat ){
                    $jsonPriceCat= json_encode($newPriceCat);
                
         }
           elseif ( empty($newPriceCat) && $oldPriceCat ){
                    $jsonPriceCat= json_encode($oldPriceCat);
                    
            }
   
          $sqlopdt = "UPDATE tours_price_data  SET 
                   tourdates='$tourdates',
                   tourtime='$jsontimes',
                   seats='$seats',
                   tourprice='$singleprice',
                   priceoption='$jsonmultiprice',
                   multiprice='$enablemulti',
                   otherpricecat='$jsonPriceCat',
                  `$operating_type_label` = '$operating_type'
                   WHERE oid='$oid' and  tid='$tid'";
        $conn->query($sqlopdt);
        ?>
        
<?php         
}		
if($_REQUEST['postimg'])
{
   
    $postid=$conn -> real_escape_string($_REQUEST['postid']);
    $imgid=$conn -> real_escape_string($_REQUEST['imgid']);
    $getquery=$conn->query("SELECT meta_value FROM wpwr_postmeta  where meta_key='wp_travel_itinerary_gallery_ids' and post_id='$postid'");
    $fetchimage=$getquery -> fetch_assoc();
    $decodeData=$fetchimage['meta_value'];
    
    $arr_index = array();
    $str_arr = preg_split ("/\,/", $decodeData);
 
    print_r($str_arr);
    
    
     foreach($fetchimage['meta_value'] as $showPostImges ){
  
         
         $j++;
     }
         $sqlopdt = "UPDATE wpwr_postmeta  SET  meta_value='$decodeData' WHERE  
                         post_id='$postid' and meta_key='wp_travel_itinerary_gallery_ids'";
     // $conn->query($sqlopdt);
}

if($_REQUEST['tabRefersh']){
   $tid=$conn -> real_escape_string($_REQUEST['tid']);
   $oid=$conn -> real_escape_string($_REQUEST['oid']);
   showroutes($tid, $oid);
}



if($_REQUEST['deladdon']){
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $imgid=$conn -> real_escape_string($_REQUEST['imgid']);
     $imgname=$conn -> real_escape_string($_REQUEST['imgname']);
     $getquery=$conn->query("select * from tour_images where tid='$tid' and imgid='$imgid'");
     $row_cnt = $getquery->num_rows;
     $fetchimage=$getquery -> fetch_assoc();
     $removeData=array();
     $removeData[]=$imgname;
     $updateArray=array();
     $selected_images=explode(",",$fetchimage['tourimages']);
        foreach($selected_images as $ShowData)
        {
               if(!in_array( $ShowData, $removeData)){
                  $updateArray[]=$ShowData;
               }
         }
        
         $List = implode(',', $updateArray); 
         $conn->query("UPDATE tour_images  SET  tourimages='$List'  where tid='$tid' and imgid='$imgid'");
         $arrayData=array_map('intval', explode(',', $List));
     if($row_cnt>0){
       ?>
        <ul class="edilistimg">
             <?php foreach($updateArray as $showimage){
                 if($showimage):?>
                 
                  <li><img src="/wp-content/themes/adventure-republiq/operator/uploads/<?php echo $showimage;?>">
                    <a  class="deladdonImg" href="javascript:void(0);" data-imgid="<?php echo $imgid;?>"  data-imgname="<?php echo $showimage;?>"  data-tid="<?php echo $tid;?>">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                        </a>
                  </li>
                  <?php endif;  } ?>
            </ul>
       <?php
        }
        ?>
        <script>
    jQuery('.deladdonImg').click(function() {
         var tid= jQuery(this).data("tid");
         var imgid= jQuery(this).data("imgid"); 
         var thistrtype= jQuery(this).data("thistrtype");
         var oid= jQuery(this).data("oid");
         var imgname= jQuery(this).data("imgname");
         var deladdon= "Yes";
            $('.edilistimg').html('loading');
               $.ajax({
               type: 'POST',
               url: '/wp-content/themes/adventure-republiq/operator/process.php',
               data:{tid: tid,imgid:imgid,oid:oid,thistrtype:thistrtype,deladdon:deladdon,imgname:imgname},
               success: function(data) {
                 $('.edilistimg').html(data);
               }
          
           }); 
 }); 
        </script>
        <?php
}


if($_REQUEST['Action']=='guideprofile'){
  //   error_reporting(E_ALL);
  // ini_set('display_errors', 1);
  // ini_set('display_startup_errors', 1);
     $uploadedFile = ''; 
      $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
     $id = $conn->real_escape_string($id);
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $gname=$conn -> real_escape_string($_REQUEST['gname']);
     $glanguage=$conn -> real_escape_string($_REQUEST['glanguage']);
     $gaboutme=$conn -> real_escape_string($_REQUEST['gaboutme']);
     $gbesttravel=$conn -> real_escape_string($_REQUEST['gbesttravel']);
     $gfavplaces=$conn -> real_escape_string($_REQUEST['gfavplaces']);
     $gunforgetable=$conn -> real_escape_string($_REQUEST['gunforgetable']); 
     $fileName = basename($_FILES["file"]["name"]); 
     $targetFilePath = $uploadDir . $fileName; 
     $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
     $allowTypes = array( 'jpg', 'png', 'jpeg');
         if($_FILES["file"]["name"]) {  
             
             if(in_array($fileType, $allowTypes)){ 
                 move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath); 
                        $uploadedFile = $fileName; 
                  }
              else
                  {
                      echo 'Sorry, only JPG, JPEG, & PNG files are allowed to upload.'; 
                  }
         }
                  
   if(empty($id)){
          $sql = "INSERT INTO operator_guide_profile (oids, gname, gprofile,glanguage,gaboutme,gbesttravel,gfavplaces,gunforgetable)
                   VALUES ('$oid', '$gname','$fileName', '$glanguage', '$gaboutme','$gbesttravel','$gfavplaces','$gunforgetable')";
                    if ($conn->query($sql) === TRUE) {
                     // echo "New record created successfully";
                      } else {
                        echo "Error: " . $sql . "<br>" . $conn->error;
                      }
    
     }
     else
          {
              if($_FILES["file"]["name"]) {
                  $sqlguide = "UPDATE operator_guide_profile  SET 
                 gname='$gname',
                 gprofile='$fileName',
                 gaboutme='$gaboutme',
                 glanguage='$glanguage',
                 gbesttravel='$gbesttravel',
                 gfavplaces='$gfavplaces',
                 gunforgetable='$gunforgetable'
                 WHERE id='$id'";
                 $conn->query($sqlguide);
              }
               else
               {
              $sqlguide = "UPDATE operator_guide_profile  SET 
               
                 gname='$gname',
                 gaboutme='$gaboutme',
                 glanguage='$glanguage',
                 gbesttravel='$gbesttravel',
                 gfavplaces='$gfavplaces',
                 gunforgetable='$gunforgetable'
                 WHERE id='$id'";
                 $conn->query($sqlguide);
               }
            }
          echo  guide_reload($oid) ;
  
       }



 
if($_REQUEST['DeltrasnImgs'])
   {
        $imgid=$conn -> real_escape_string($_REQUEST['imgid']);
        $tid=$conn -> real_escape_string($_REQUEST['tid']);
        $id=$conn -> real_escape_string($_REQUEST['id']);
        $imgpath=$_REQUEST['imgpath'];
        unlink($getImgRootPath.$imgpath); 
        $conn->query("DELETE FROM tour_images WHERE id='$id'"); 
        $getData=$conn->query("select * from operator_transport where id='$tid'");
        $fetchTransport =$getData -> fetch_assoc();
        $imgid=$fetchTransport['imgid'];   
        
      ?>
        <ul class="trasnlist">
         <?php
            $getImage=$conn->query("select * from tour_images where imgid='$imgid'");
            while($transImg=$getImage -> fetch_assoc()){?>
               <li> <img src="<?php echo $getImgRootPath.$transImg['tourimages'];?>"  class="timges">
                    <a href="javascript:void(0)" class="deltrasport" data-imgpath="<?php echo $transImg['tourimages'];?>" data-id="<?php echo $transImg['id'];?>"  data-tid="<?php echo $fetchTransport['id'];?>" data-imgid="<?php echo $imgid;?>" data-imgid="<?php echo $fetchTransport['id'];?>">
                       <i class="fa fa-trash" aria-hidden="true"></i>
                </a>
           </li>
             <?php }?>
            </ul>
        <?php
        ?>
        <script>
           jQuery(".deltrasport").click(function() {
                  jQuery('.trasnlist').html("<b>Loading response...</b>");
                      var imgid = jQuery(this).data("imgid");
                      var imgpath = jQuery(this).data("imgpath");
                      var id = jQuery(this).data("id");
                      var tid = jQuery(this).data("tid");
                      var DeltrasnImgs ="Yes";
                    $.ajax({
                          type: 'POST',
                          url:  '/wp-content/themes/adventure-republiq/operator/process.php',
                          data : {imgid: imgid,DeltrasnImgs:DeltrasnImgs,tid:tid,imgpath:imgpath,id:id},
                           success: function(data){
                             jQuery('.trasnlist').html(data);
                           }
                   
                   }); 
          
  }); 
        </script>
        <?php
   }

if($_REQUEST['singleprice']){

 include('db.php');
     $singleprice=$conn -> real_escape_string($_REQUEST['singleprice']?? '');
     $tid=$conn -> real_escape_string($_REQUEST['tid']?? '');
      $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
     $gedata=$conn->query("select * from group_price_data where tid='$tid'");
     $fetchData =$gedata -> fetch_assoc();
     $array=json_decode($fetchData['price_meta']);
     $i=1;
           foreach($array as $updatejson){
              $data[]= array ('perperson' =>$i,'price'=> $singleprice,'key'=> $i);
             $i++; 
          
           }
     $encodJson=json_encode($data);

     $sqlopdt = "UPDATE group_price_data  SET 
                 price_meta='$encodJson'
                 WHERE tid='$tid'";
                $conn->query($sqlopdt);
                
    $sqlopdt = "UPDATE tours_price_data  SET 
                 tourprice='$singleprice'
                 WHERE tid='$tid'";
                $conn->query($sqlopdt);
  echo showPriceTable($tid,$oid);                 
}


 /* Add  Operator Details  Before Full Access*/

 if(($_REQUEST['role'])){
 $oid=$conn -> real_escape_string($_REQUEST['oid']);
 $role=$conn -> real_escape_string($_REQUEST['role']);
 $first_name=$conn -> real_escape_string($_REQUEST['first_name']);
 $checkNum=$conn->query("select * from operator_details where oids='$oid'");
 $row_cnt = $checkNum->num_rows;
 if($row_cnt==0){
 $sql = "INSERT INTO operator_details (oids, roles)
 VALUES ('$oid', '$role')";
        if ($conn->query($sql) === TRUE) {
       
        } else {
          echo "Error: " . $sql . "<br>" . $conn->error;
        }
        $sqlname = "UPDATE wpwr_usermeta   SET meta_value='$first_name' WHERE user_id='$oid' and meta_key='first_name'";
          $conn->query($sqlname);
 }
 else{
        $sql = "UPDATE operator_details   SET oids='$oid',roles='$role' WHERE oids='$oid'";
        $conn->query($sql); 
        $sqlname = "UPDATE wpwr_usermeta   SET meta_value='$first_name' WHERE user_id='$oid' and meta_key='first_name'";
        $conn->query($sqlname);
 }

 }
 if(($_REQUEST['phone'])){
 
  $oid=$conn -> real_escape_string($_REQUEST['oid'] ?? '');
  $phone=$conn -> real_escape_string($_REQUEST['phone']?? '');
  $pcc=$conn -> real_escape_string($_REQUEST['pcc'] ?? '');
  $whatsapp=$conn -> real_escape_string($_REQUEST['whatsapp'] ?? '');
  $companyname=$conn -> real_escape_string($_REQUEST['companyname'] ?? '');
  $headlocation=$conn -> real_escape_string($_REQUEST['headlocation'] ?? '');
  $latitude=$conn -> real_escape_string($_REQUEST['latitude'] ?? '');
  $longitude=$conn -> real_escape_string($_REQUEST['longitude'] ?? '');
  $address1=$conn -> real_escape_string($_REQUEST['address1'] ?? '');
  $address2=$conn -> real_escape_string($_REQUEST['address2'] ?? '');
  $facebook=$_REQUEST['facebook'];
  $instagram =$_REQUEST['instagram'];
  $youtube=$_REQUEST['youtube'];
  $toursell=$conn -> real_escape_string($_REQUEST['toursell'] ?? '');
  $decribes=$conn -> real_escape_string($_REQUEST['decribes'] ?? '');
  $skype=$conn -> real_escape_string($_REQUEST['skype'] ?? '');
  $twodays=$conn -> real_escape_string($_REQUEST['twodays'] ?? '');
  $longerdays=$conn -> real_escape_string($_REQUEST['longerdays'] ?? '');
  $infoprovide=$conn -> real_escape_string($_REQUEST['infoprovide'] ?? '');
  $guides=$conn -> real_escape_string($_REQUEST['guides'] ?? '');
  $url=$conn -> real_escape_string($_REQUEST['url'] ?? '');
 if($guides=='Yes'):
        $nocontrguide='';
 else:
        $nocontrguide=$conn -> real_escape_string($_REQUEST['nocontrguide'] ?? '');
 endif;   
 if(!empty($nocontrguide)):
        $guides='No';
 endif;          
 
 $owntrasnport=$conn -> real_escape_string($_REQUEST['owntrasnport'] ?? '');
 $trcontract=$conn -> real_escape_string($_REQUEST['trcontract'] ?? '');
 $ownhotels=$conn -> real_escape_string($_REQUEST['ownhotels'] ?? '');
 $htcontract=$conn -> real_escape_string($_REQUEST['htcontract'] ?? '');
 $contactadventure=$conn -> real_escape_string($_REQUEST['contactadventure'] ?? '');
 $cntfullname=$conn -> real_escape_string($_REQUEST['cntfullname'] ?? '');
 $compemail=$conn -> real_escape_string($_REQUEST['compemail'] ?? '');
 $compphone=$conn -> real_escape_string($_REQUEST['compphone'] ?? '');
 $compskyup=$conn -> real_escape_string($_REQUEST['compskyup'] ?? '');
 $complocation=$conn -> real_escape_string($_REQUEST['complocation'] ?? '');
 $sql = "UPDATE operator_details  
         SET 
         pcc='$pcc',
         phoneno='$phone',
         whatsapp='$whatsapp',
         companyname='$companyname',
         headlocation='$headlocation',
         address1='$address1',
         address2='$address2',
         facebook='$facebook',
         instagram='$instagram',
         youtube='$youtube',
         skype='$skype',
         twolonger='',
         guides='$guides',
         nocontrguide='$nocontrguide',
         owntrasnport='$owntrasnport',
         trcontract='$trcontract',
         ownhotels='$ownhotels',
         htcontract='$htcontract',
         latitude='$latitude',
         longitude='$longitude'
         WHERE oids='$oid'";
        $conn->query("update wpwr_usermeta set meta_value='$pcc' where meta_value='pccode' and  user_id=$oid");        
        $conn->query($sql);
       
        $conn->query("update wpwr_users set user_url='$url' where ID=$oid");  
       
 }
 if(($_REQUEST['resfullname'])){

     $oid=$conn -> real_escape_string($_REQUEST['oid'] ?? '');
     $resfullname=$conn -> real_escape_string($_REQUEST['resfullname'] ?? '');
     $resemail=$conn -> real_escape_string($_REQUEST['resemail'] ?? '');
     $rpcc=$conn -> real_escape_string($_REQUEST['rpcc'] ?? '');
     $resphoneno=$conn -> real_escape_string($_REQUEST['resphoneno'] ?? '');
     $reswhatapp=$conn -> real_escape_string($_REQUEST['reswhatapp'] ?? '');
     $day1M=$conn -> real_escape_string($_REQUEST['monstart'] ?? '');
     $day1E=$conn -> real_escape_string($_REQUEST['monend'] ?? '');
     $day2M=$conn -> real_escape_string($_REQUEST['tuestart'] ?? '');
     $day2E=$conn -> real_escape_string($_REQUEST['tueend'] ?? '');
     $day3M=$conn -> real_escape_string($_REQUEST['wedstart'] ?? '');
     $day3E=$conn -> real_escape_string($_REQUEST['wedend'] ?? '');
     $day4M=$conn -> real_escape_string($_REQUEST['thurstart'] ?? '');
     $day4E=$conn -> real_escape_string($_REQUEST['thurend'] ?? '');
     $day5M=$conn -> real_escape_string($_REQUEST['fristart'] ?? '');
     $day5E=$conn -> real_escape_string($_REQUEST['friend'] ?? '');
     $day6M=$conn -> real_escape_string($_REQUEST['satstart'] ?? '');
     $day6E=$conn -> real_escape_string($_REQUEST['satend'] ?? '');
     $day7M=$conn -> real_escape_string($_REQUEST['sunstart'] ?? '');
     $day7E=$conn -> real_escape_string($_REQUEST['sunend'] ?? '');
     $jsondata = '{"monM":"'.$day1M.'", 
                   "monE":"'.$day1E.'",
                   "tueM":"'.$day2M.'",
                   "tueE":"'.$day2E.'",
                   "wedM":"'.$day3M.'",
                   "wedE":"'.$day3E.'",
                   "thurM":"'.$day4M.'",
                   "thurE":"'.$day4E.'",
                   "friM":"'.$day5M.'",
                   "friE":"'.$day5E.'",
                   "satM":"'.$day6M.'",
                   "satE":"'.$day6E.'",
                   "sunM":"'.$day7M.'",
                   "sunE":"'.$day7E.'"}'; 
    
    // $hours=$conn -> real_escape_string($_REQUEST['hours']);
     $checkNum=$conn->query("select * from operator_reservation where oid='$oid'");


     $row_cnt = $checkNum->num_rows;
     if($row_cnt==0){
      $sql = "INSERT INTO operator_reservation (oid, resfullname,resemail,rpcc,resphoneno,reswhatapp,reslocation,hours, ntabs)
       VALUES ('$oid', '$resfullname', '$resemail', '$rpcc', '$resphoneno', '$reswhatapp','$reslocation', '$jsondata','1')";
              if ($conn->query($sql) === TRUE) {
           
              } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
              }
       }
       else{
          $sql = "UPDATE operator_reservation SET 
             resfullname='$resfullname',
             resemail='$resemail',
             rpcc='$rpcc',
             resphoneno='$resphoneno',
             reswhatapp='$reswhatapp',
             reslocation='$reslocation',
             hours='$jsondata',
             ntabs=1
             WHERE oid='$oid'";
             $conn->query($sql);

 }
 }

 /* Add/Update  Operator Details  Before Full Access*/


 /* Delete  Guide Proile  */



 /* Update Profile Detailss */

if($_REQUEST['Action']=='opdetails'){

     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $name = $_FILES['file']['name'];
     $username=$_REQUEST['username'];
     $fileName = $username."-".basename($_FILES["file"]["name"]); 
     $targetFilePath = $uploadDir . $fileName; 
     $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
     $allowTypes = array( 'jpg', 'png', 'jpeg');
        if(in_array($fileType, $allowTypes)){ 
             move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath); 
        }
      else{
          //echo 'Sorry, only JPG, JPEG, & PNG files are allowed to upload.'; 
      }
                  
     $oprhighlights=$conn -> real_escape_string($_REQUEST['oprhighlights'] ?? '');
     $businessdecp=$conn -> real_escape_string($_REQUEST['businessdecp'] ?? '');
     $trmembership=$conn -> real_escape_string($_REQUEST['trmembership'] ?? '');
     $tripadvisor=$conn -> real_escape_string($_REQUEST['tripadvisor'] ?? '');
     $founded=$conn -> real_escape_string($_REQUEST['founded'] ?? '');
     $staffsize=$conn -> real_escape_string($_REQUEST['staffsize'] ?? '');;
     $gudies=$conn -> real_escape_string($_REQUEST['gudies'] ?? '');
     $transport=$conn -> real_escape_string($_REQUEST['transport'] ?? '');
     $googlecidno=$conn -> real_escape_string($_REQUEST['googlecidno'] ?? '');
     $faqs=$conn -> real_escape_string($_REQUEST['faqs'] ?? '');
     if($_FILES["file"]["name"]) {
        $sqlopdt = "UPDATE operator_details  SET 
                     file='$fileName',
                     oprhighlights='$oprhighlights',
                     businessdecp='$businessdecp',
                     trmembership='$trmembership',
                     founded='$founded',
                     tripadvisor='$tripadvisor', 
                     googlecidno='$googlecidno',
                     staffsize='$staffsize',
                     gudies='$gudies',
                     transport='$transport',
                     faqs='$faqs'
                     WHERE oids='$oid'";
                     $conn->query($sqlopdt);
     }
     else
     {
          $sqlopdt = "UPDATE operator_details  SET 
                     oprhighlights='$oprhighlights',
                     businessdecp='$businessdecp',
                     trmembership='$trmembership',
                     founded='$founded',
                     tripadvisor='$tripadvisor', 
                     staffsize='$staffsize',
                     gudies='$gudies',
                     transport='$transport',
                      googlecidno='$googlecidno',
                     faqs='$faqs'
                     WHERE oids='$oid'";
                     $conn->query($sqlopdt);
     }
    
}
   /* Update Operator FAQS */

if(($_REQUEST['Action']=='addopfaqs')){

     $oid=$conn -> real_escape_string($_REQUEST['oid'] ?? '');
     $getData=$conn->query("select * from operator_details where oids='$oid'");
     $fetchFaqs=$getData -> fetch_assoc();
     $oldfaqs = $fetchFaqs['faqs'];
     $newfaqs = array();
     $quest = $_REQUEST['quest'];
     $answer= $_REQUEST['answer'];
     $count = count($quest);
     for ( $i = 0; $i < $count; $i++ ) {
         if ( $quest[$i] != '' ) :
         $newfaqs[$i]['quest'] = stripslashes($quest[$i]);
         $newfaqs[$i]['answer'] = stripslashes( $answer[$i] ); // and however you want to sanitize 
         endif;
   }
 
   if ( !empty( $newfaqs ) && $newfaqs != $oldfaqs ){
             $newfaqs= json_encode($newfaqs);
              $sqlfaq = "UPDATE operator_details  SET 
              faqs='$newfaqs'
              WHERE oids='$oid'";
   }
   elseif ( empty($newfaqs) && $oldfaqs ){
            $oldfaqs= json_encode($oldfaqs);
             $sqlfaq = "UPDATE operator_details  SET 
             faqs='$oldfaqs'
             WHERE oids='$oid'";
    }
       $conn->query($sqlfaq);
     
}

  /* Update Opearter Tax and Payment */


if(($_REQUEST['Action']=='taxdetails')){
   $oid=$conn -> real_escape_string($_REQUEST['oid']);
   $taxdetails =    '{"gstpr":"'.$conn -> real_escape_string($_REQUEST['gstpr']).'", 
                     "paytax":"'.$conn -> real_escape_string($_REQUEST['paytax']).'",
                     "trno":"'.$conn -> real_escape_string($_REQUEST['trno']).'",
                     "gstin":"'.$conn -> real_escape_string($_REQUEST['gstin']).'",
                     "ytaxpan":"'.$conn -> real_escape_string($_REQUEST['ytaxpan']).'",
                     "ntaxpan":"'.$conn -> real_escape_string($_REQUEST['ntaxpan']).'",
                     "gsttax":"'.$conn -> real_escape_string($_REQUEST['gsttax']).'",
                     "taxname":"'.$conn -> real_escape_string($_REQUEST['taxname']).'",
                     "taxpercentage":"'.$conn -> real_escape_string($_REQUEST['taxpercentage']).'",
                     "legalname":"'.$conn -> real_escape_string($_REQUEST['legalname']).'",
                     "trenqemial":"'.$conn -> real_escape_string($_REQUEST['trenqemial']).'",
                     "invemail":"'.$conn -> real_escape_string($_REQUEST['invemail']).'", 
                     "invcountry":"'.$conn -> real_escape_string($_REQUEST['invcountry']).'",
                     "invstate":"'.$conn -> real_escape_string($_REQUEST['invstate']).'",
                     "invpincode":"'.$conn -> real_escape_string($_REQUEST['invpincode']).'",
                     "payname":"'.$conn -> real_escape_string($_REQUEST['payname']).'",
                     "bankname":"'.$conn -> real_escape_string($_REQUEST['bankname']).'",
                     "accno":"'.$conn -> real_escape_string($_REQUEST['accno']).'",
                     "ifsccode":"'.$conn -> real_escape_string($_REQUEST['ifsccode']).'",
                     "swtccode":"'.$conn -> real_escape_string($_REQUEST['swftccode']).'",
                     "braddress":"'.$conn -> real_escape_string($_REQUEST['braddress']).'",
                     "bankcity":"'.$conn -> real_escape_string($_REQUEST['bankcity']).'",
                     "bankstate":"'.$conn -> real_escape_string($_REQUEST['bankstate']).'",
                      "bankcountry":"'.$conn -> real_escape_string($_REQUEST['bankcountry']).'"

                 }'; 

  
   $sqltax = "UPDATE operator_details  SET 
             taxdetails='$taxdetails'
             WHERE oids='$oid'";
   $conn->query($sqltax);              
         
} 
 
/* Add Opearor Guides */

 
 
/* Add Opeartor Guides */

 if(($_REQUEST['delProfile'])){
      $id=$conn -> real_escape_string($_REQUEST['gid']);
      $conn->query("DELETE FROM operator_guide_profile WHERE id='$id'");
      
     
}


 
/* Add Opeartor Tour Images*/

 if(($_REQUEST['thisaction']=='tourphotos')){
        $oid=$conn -> real_escape_string($_REQUEST['oid']);
        $file=$conn -> real_escape_string($_REQUEST['file']);
       
       $conn->query("DELETE FROM operator_guide_profile WHERE id='$id'");
     
}



if($_REQUEST['rmimage']){
   
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $lid=$conn -> real_escape_string($_REQUEST['lid']);
     $cust_currency=$conn -> real_escape_string($_REQUEST['currency']); 
     $getaddons=$conn->query("select * from touraddons where oid='$oid' and  tid='$tid'");
     $countData= $getaddons->num_rows;
     $fetchAddons=$getaddons -> fetch_assoc();
     $decodeData=json_decode($fetchAddons['roomtypes']);

     $arr_index = array();
     foreach ($decodeData as $key => $value) {
      
           if ($key == $lid) {
               $arr_index[] = $key;
           }
       }
        // print_r($arr_index);
       // delete data
       foreach ($arr_index as $i) {
           unset($decodeData[$i]);
           
       }
       $decodeData = array_values($decodeData);
       $jsonrmtypes= $conn -> real_escape_string(json_encode($decodeData));
       if($jsonrmtypes=='[]')
       {
        
           $jsonrmtypes='';
       }
       else
       {
            $jsonrmtype= $jsonrmtype;
       }
        $sqlopdt = "UPDATE touraddons  SET  roomtypes='$jsonrmtypes' WHERE oid='$oid' and  tid='$tid'";
        $conn->query($sqlopdt);
         echo room_reload($oid,$tid,$cust_currency);
}

if($_REQUEST['serviceaddons']){
   
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $lid=$conn -> real_escape_string($_REQUEST['lid']);
     $serviceid=$conn -> real_escape_string($_REQUEST['serviceid']);
    
     $cust_currency=$conn -> real_escape_string($_REQUEST['currency']);
     $getaddons=$conn->query("select * from touraddons where oid='$oid' and  tid='$tid'");
     $countData= $getaddons->num_rows;
     $fetchAddons=$getaddons -> fetch_assoc();
     $decodeData=json_decode($fetchAddons['optionaltypes']);

     $arr_index = array();
     foreach ($decodeData as $key => $value) {
      
           if ($key == $lid) {
               $arr_index[] = $key;
           }
       }
        // print_r($arr_index);
       // delete data
       foreach ($arr_index as $i) {
           unset($decodeData[$i]);
           
       }
       $decodeData = array_values($decodeData);
   
       $jsonrmtypes= $conn -> real_escape_string(json_encode($decodeData));
       if($jsonrmtypes=='[]')
       {
        
           $jsonrmtypes='';
       }
       else
       {
            $jsonrmtype= $jsonrmtype;
       }
       $sqlopdt = "UPDATE touraddons  SET  optionaltypes='$jsonrmtypes' WHERE oid='$oid' and  tid='$tid'";
       $conn->query($sqlopdt);
       $conn->query("DELETE FROM othserviceaddon WHERE serviceid='$serviceid'"); 
       echo reload_addon_options($oid,$tid,$cust_currency);
   
}
if($_REQUEST['trasnddons']){
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $lid=$conn -> real_escape_string($_REQUEST['lid']);
      $cust_currency=$conn -> real_escape_string($_REQUEST['currency']); 
     $getaddons=$conn->query("select * from touraddons where oid='$oid' and  tid='$tid'");
     $countData= $getaddons->num_rows;
     $fetchAddons=$getaddons -> fetch_assoc();
     $decodeData=json_decode($fetchAddons['transfertypes']);
      $arr_index = array();
     foreach ($decodeData as $key => $value) {
        if ($key == $lid) {
               $arr_index[] = $key;
           }
       }
        // print_r($arr_index);
       // delete data
       foreach ($arr_index as $i) {
           unset($decodeData[$i]);
           
       }
       $decodeData = array_values($decodeData);
       $jsonrmtypes= $conn -> real_escape_string(json_encode($decodeData));
       if($jsonrmtypes=='[]')
       {
        
           $jsonrmtypes='';
       }
       else
       {
            $jsonrmtype= $jsonrmtype;
       }
        $sqlopdt = "UPDATE touraddons  SET  transfertypes='$jsonrmtypes' WHERE oid='$oid' and  tid='$tid'";
        $conn->query($sqlopdt);
        echo reload_addon_tras($oid,$tid,$cust_currency);    
       
        
}

if(($_REQUEST['Action']=='Accphotos')){


     $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
     $tid=$conn -> real_escape_string($_REQUEST['tid']?? '');
     $lid = $conn->real_escape_string($_REQUEST['lid'] ?? '');
     $cust_currency=$conn -> real_escape_string($_REQUEST['cust_currency'] ?? '');
     $checkup=$conn -> real_escape_string($_REQUEST['checkup'] ?? '');
     $getaddons=$conn->query("select * from touraddons where oid='$oid' and  tid='$tid'");
     $countData= $getaddons->num_rows;
     $fetchAddons=$getaddons -> fetch_assoc();
     $oldRmtypes = $fetchAddons['roomtypes'];
     $newRmtypes= array();
     $addonrooms= $_REQUEST['addonrooms'];
     $roomcounts = count($addonrooms);

     if($checkup=='Yes')
     { 
         $decodeData=json_decode($fetchAddons['roomtypes']);
         $decodeData[$lid]= array ('name' => stripslashes($_REQUEST['addonrooms'][0]),
                                 'numberpax' => stripslashes($_REQUEST['numberpax'][0]),
                                 'perguestroom' => stripslashes($_REQUEST['perguestroom'][0]),
                                 'occuppancy' =>stripslashes($_REQUEST['addonocctype'][0]),
                                 'price' =>stripslashes($_REQUEST['roomprice'][0]),
                                 'privateprice' => stripslashes($_REQUEST['privateprice'][0]),
                                 'rmdecp' => stripslashes($_REQUEST['rmdecp'][0]),
                                 'imgid' => stripslashes($_REQUEST['imgId'][0])
                         );
                        
                        
       }
       else
       {
                 for ( $i = 0; $i < $roomcounts; $i++ ) {
                         if ( $addonrooms[$i] != '' ) :
                         $newRmtypes[$i]['name'] = stripslashes($addonrooms[$i]);
                         $newRmtypes[$i]['numberpax'] = stripslashes($_REQUEST['numberpax'][$i]);
                         $newRmtypes[$i]['perguestroom'] = stripslashes($_REQUEST['perguestroom'][$i]);
                         $newRmtypes[$i]['occuppancy'] = stripslashes($_REQUEST['addonocctype'][$i]);
                         $newRmtypes[$i]['price'] = stripslashes($_REQUEST['roomprice'][$i]);
                         $newRmtypes[$i]['privateprice'] = stripslashes($_REQUEST['privateprice'][$i]);
                         $newRmtypes[$i]['rmdecp'] = stripslashes($_REQUEST['rmdecp'][$i]);
                         $newRmtypes[$i]['imgid'] = stripslashes($_REQUEST['imgId'][$i]);
                        endif;
                     }
                    if($oldRmtypes!=''){
                        $decodethis=json_decode($oldRmtypes);
                        $mergejson=array_merge($decodethis,$newRmtypes);
                         $jsonrmtypes= $conn -> real_escape_string(json_encode($mergejson));
                       }
                       else
                       {
                           $jsonrmtypes= $conn -> real_escape_string(json_encode($newRmtypes));
                           
                       }
         }
                   if($countData==0) {
                      echo  $sql = "INSERT INTO touraddons (oid,tid,roomtypes,transfertypes,optionaltypes,goodtoknow,faqs)
                       VALUES ('$oid', '$tid','$jsonrmtypes','', '','','')";
                         $conn->query($sql);
                   }
               else{
                   if($checkup=='Yes'){  
                        $jsonrmtypes= $conn -> real_escape_string(json_encode($decodeData));
                    }
                   $sqlopdt = "UPDATE touraddons  SET 
                                roomtypes='$jsonrmtypes'
                                WHERE oid='$oid' and  tid='$tid'";
                                $conn->query($sqlopdt);
              }
               echo room_reload($oid,$tid,$cust_currency);
}  
if($_REQUEST['Action']=='addontrasport'){

     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $checkup=$conn -> real_escape_string($_REQUEST['checkup']); 
     $lid=$conn -> real_escape_string($_REQUEST['lid']);
     $cust_currency=$conn -> real_escape_string($_REQUEST['cust_currency']); 
     $getaddons=$conn->query("select * from touraddons where oid='$oid' and  tid='$tid'");
     $fetchAddons=$getaddons -> fetch_assoc();
    
     $oldRmtypes = $fetchAddons['transfertypes'];
     $newRmtypes= array();
     
     $addonrooms= $_REQUEST['trname'];
     $roomcounts = count($addonrooms);
     if($checkup=='Yes')
     { 
      $decodeData=json_decode($fetchAddons['transfertypes']);
      $decodeData[$lid]= array ('trname' => $conn -> real_escape_string($_REQUEST['trname'][0]),
                             'transtranporttype' => $conn -> real_escape_string($_REQUEST['transtranporttype'][0]),
                             'trrmdecp' => $conn -> real_escape_string($_REQUEST['trrmdecp'][0]),
                             'trroomprice' => $conn -> real_escape_string($_REQUEST['trroomprice'][0]),
                             'imgid' => $conn -> real_escape_string($_REQUEST['imgId'][0]),
                         );
     
     }
     else
     {
         for ( $i = 0; $i < $roomcounts; $i++ ) {
             if ( $addonrooms[$i] != '' ) :
             $newRmtypes[$i]['trname'] = stripslashes($addonrooms[$i]);
             $newRmtypes[$i]['transtranporttype'] = stripslashes($_REQUEST['transtranporttype'][$i]);
             $newRmtypes[$i]['trrmdecp'] = stripslashes($_REQUEST['trrmdecp'][$i]);
             $newRmtypes[$i]['trroomprice'] = stripslashes($_REQUEST['trroomprice'][$i]);
             $newRmtypes[$i]['imgid'] = stripslashes($_REQUEST['imgId'][$i]);
             endif;
       }    
         if($oldRmtypes!=''){
            $decodethis=json_decode($oldRmtypes);
            $mergejson=array_merge($decodethis,$newRmtypes);
            $jsontrnstypes= $conn -> real_escape_string(json_encode($mergejson));
           }
           else
           {
                $jsontrnstypes= $conn -> real_escape_string(json_encode($newRmtypes));
               
           }
     }    
           if($checkup=='Yes'){  
                         $jsontrnstypes= $conn -> real_escape_string(json_encode($decodeData));
                    }
           $sqlopdt = "UPDATE touraddons  SET 
                       transfertypes='$jsontrnstypes'
                       WHERE oid='$oid' and  tid='$tid'"; 
           $conn->query($sqlopdt);
           
   echo reload_addon_tras($oid,$tid,$cust_currency);        

}

if(($_REQUEST['Action']=='Optionaladdons')){

     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $checkup=$conn -> real_escape_string($_REQUEST['checkup']); 
     $lid=$conn -> real_escape_string($_REQUEST['lid']);
     $cust_currency=$conn -> real_escape_string($_REQUEST['cust_currency']); 
     $arrayserviceid= $_REQUEST['serviceid'];
      $serviceid= $arrayserviceid[0];
     $getaddons=$conn->query("select * from touraddons where oid='$oid' and  tid='$tid'");
     $fetchAddons=$getaddons -> fetch_assoc();
    
     $oldRmtypes = $fetchAddons['optionaltypes'];
     $newRmtypes= array();
     $addonrooms= $_REQUEST['servicename'];
     $roomcounts = count($addonrooms);
     if($checkup=='Yes')
     { 
      $decodeData=json_decode($fetchAddons['optionaltypes']);
      $decodeData[$lid]= array ('servicename' => $conn -> real_escape_string($_REQUEST['servicename'][0]),
                                'servicdecp' => $conn -> real_escape_string($_REQUEST['servicdecp'][0]),
                                'perguest' => $conn -> real_escape_string($_REQUEST['perguest'][0]),
                                'serviceid' => $conn -> real_escape_string($_REQUEST['serviceid'][0]),
                              );
     
      }
     else
     {  
             for ( $i = 0; $i < $roomcounts; $i++ ) {
                 if ( $addonrooms[$i] != '' ) :
                 $newRmtypes[$i]['servicename'] = stripslashes($addonrooms[$i]);
                 $newRmtypes[$i]['servicdecp'] = stripslashes($_REQUEST['servicdecp'][$i]);
                 $newRmtypes[$i]['perguest'] = stripslashes($_REQUEST['perguest'][$i]);
                  $newRmtypes[$i]['serviceid'] = stripslashes($_REQUEST['serviceid'][$i]);
                  endif;
           }    
             if($oldRmtypes!=''){
                $decodethis=json_decode($oldRmtypes);
                $mergejson=array_merge($decodethis,$newRmtypes);
                $jsonoptional= $conn -> real_escape_string(json_encode($mergejson));
             }
                       
               else{
                          $jsonoptional= $conn -> real_escape_string(json_encode($newRmtypes));
                }
        }
          if($checkup=='Yes'){  
                           
                           $jsonoptional= $conn -> real_escape_string(json_encode($decodeData));
                    }
           $sqlopdt = "UPDATE touraddons  SET 
                        optionaltypes='$jsonoptional'
                        WHERE oid='$oid' and  tid='$tid'"; 
           $conn->query($sqlopdt);
           
       /* Service Other Category Addons */
     
      $query=$conn->query("select * from othserviceaddon where serviceid='$serviceid'");
      
      $othercataddon=$query -> fetch_assoc(); 
      $countaddon= $query->num_rows;
     
     
      $newotheritem= array();
      $oldotheritem= $othercataddon['otherservicemeta'];
      $otheritem= $_REQUEST['otheritem']; 
      $itemcount = count($otheritem);
     
      
        for ( $i = 0; $i < $itemcount; $i++ ) {
                 if ( $otheritem[$i] != '' ) :
                     $newotheritem[$i]['itemname'] = stripslashes($otheritem[$i]);
                     $newotheritem[$i]['age'] = stripslashes($_REQUEST['otherage'][$i]);
                     $newotheritem[$i]['price'] = stripslashes($_REQUEST['otherprice'][$i]);
                     $newotheritem[$i]['unid'] = uniqid();;
                    
                  endif;
            } 
            
               if ( !empty( $newotheritem ) && $newotheritem != $oldotheritem ){
                    $otheroptional=  $conn -> real_escape_string(json_encode($newotheritem));
                
                }
           elseif ( empty($newPriceCat) && $oldPriceCat ){
                    $jsonPriceCat=  $conn -> real_escape_string(json_encode($oldPriceCat));
                    
            }
       
               if($countaddon>0){
                      $othersqlopdt = "UPDATE othserviceaddon  SET  otherservicemeta='$otheroptional' WHERE  serviceid='$serviceid'"; 
                      $conn->query($othersqlopdt);
                 }
                 else{
                      $conn->query("INSERT INTO othserviceaddon (oid,tid,serviceid, otherservicemeta) VALUES ('$oid','$tid','$serviceid','$otheroptional')");
                 }
           
           
       echo reload_addon_options($oid,$tid,$cust_currency);     
}

if(($_REQUEST['Action']=='addonfaq')){

     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $getaddons=$conn->query("select * from touraddons where oid='$oid' and  tid='$tid'");
     $fetchAddons=$getaddons -> fetch_assoc();
    
     $oldRmtypes = $fetchAddons['faqs'];
     $newRmtypes= array();
     $addonrooms= $_REQUEST['rmfaqs'];
     $roomcounts = count($addonrooms);
     for ( $i = 0; $i < $roomcounts; $i++ ) {
         if ( $addonrooms[$i] != '' ) :
         $newRmtypes[$i]['quest'] = stripslashes($addonrooms[$i]);
         $newRmtypes[$i]['answe'] = stripslashes($_REQUEST['rmanswer'][$i]);
         endif;
   }    
     if($oldRmtypes!=''){
        $decodethis=json_decode($oldRmtypes);
        $mergejson=array_merge($decodethis,$newRmtypes);
        $jsonfaq= json_encode($mergejson);
       }
       else
       {
            $jsonfaq= json_encode($newRmtypes);
       }
       $sqlopdt = "UPDATE touraddons  SET 
                   faqs='$jsonfaq'
                   WHERE oid='$oid' and  tid='$tid'";
                  $conn->query($sqlopdt);

}
if(($_REQUEST['rmseats'])){
 

    $rmseats= $_REQUEST['rmseats']+1;
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tid=$conn -> real_escape_string($_REQUEST['tid']);

    $getdata=$conn->query("select * from tours_price_data where oid='$oid' and  tid='$tid'");
    $fetchSeats=$getdata -> fetch_assoc();
    $seats=$fetchSeats['seats'];
   ?>
    <option selected="selected" value="">Select One</option>
      <?php for($i=$rmseats;$i<=$seats; $i++){?>
              <option value="<?php echo $i;?>">Group of <?php echo $i;?></option>
       <?php }  ?>
   
       <?php
}


if(isset($_REQUEST['seats'])){

 include('db.php');
 $countopt =$_REQUEST['seats'];
    $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
    $tid=$conn -> real_escape_string($_REQUEST['tid']?? '');
    $getdata=$conn->query("select mulpricecal from tours_price_data where oid='$oid' and  tid='$tid'");
    $fetchSeats=$getdata -> fetch_assoc();
    $countData= $fetchSeats->num_rows;
  
       $conn->query("DELETE FROM group_price_data WHERE tid=$tid");
       //$conn->query("DELETE FROM group_price_data_active WHERE tid=$tid");
    ?>
       <option selected="selected" value="">Select One</option>
        <?php for($i=1;$i<=$countopt; $i++){
             $data[]= array ('perperson' =>$i,'price'=> 0, 'key'=> $i);
           ?>   
          <option value="<?php echo $i;?>">Group of <?php echo $i;?></option>
       <?php } ?> 
   <?php
   if($countData==0)
   {
        $jsondata= json_encode($data);
        
       $conn->query("INSERT INTO group_price_data (tid,price_meta) VALUES ('$tid','$jsondata')");
    }
        $sqlopdt = "UPDATE tours_price_data  SET 
                     seats='$countopt'
                     WHERE oid='$oid' and  tid='$tid'";
                      $conn->query($sqlopdt);
                  
}

if((isset($_REQUEST['Action']) && $_REQUEST['Action']=='PriceDetails')){
    $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
    $tid=$conn -> real_escape_string($_REQUEST['tid']?? '');
    $trtype=$conn -> real_escape_string($_REQUEST['trtype']);
    $instbooking=$conn -> real_escape_string($_REQUEST['instbooking']?? '');
    $mindaysinst=$conn -> real_escape_string($_REQUEST['mindaysinst']?? '');
    $private_tr_booking=$conn -> real_escape_string($_REQUEST['private_tr_booking']?? '');
    $howman_private=$conn -> real_escape_string($_REQUEST['howman_private']?? '');
    $min_private_booking=$conn -> real_escape_string($_REQUEST['min_private_booking']?? '');
    $trcancel_days=$conn -> real_escape_string($_REQUEST['trcancel_days']?? '');
    $percentage=$conn -> real_escape_string($_REQUEST['percentage']?? '');
    $change_policy=$conn -> real_escape_string($_REQUEST['change_policy']?? '');
    $days_change_policy=$conn -> real_escape_string($_REQUEST['days_change_policy']?? '');
    $pay_change_policy=$conn -> real_escape_string($_REQUEST['pay_change_policy']?? ''); 
    $fromage=$conn -> real_escape_string($_REQUEST['fromage']?? '');  
    $endage=$conn -> real_escape_string($_REQUEST['endage']?? '');  
    $cancellation=$conn -> real_escape_string($_REQUEST['cancellation']?? '');

    $getdata=$conn->query("select * from tours_price_data where oid='$oid'  and  tid='$tid'");
    $countData= $getdata->num_rows;
    if($countData==0)
    {
         

     $conn->query("INSERT INTO tours_price_data (oid,tid,tourdates,tourtime,seats,tourprice,priceoption,multiprice,otherpricecat,mulpricecal,
                      instbooking ,mindaysinst,private_tr_booking,howman_private, min_private_booking,trcancel_days,percentage,
                       change_policy,days_change_policy,pay_change_policy,fromage,endage,cancellation)  VALUES    ('$oid','$tid','','','','','','','','','','$instbooking','$mindaysinst','$private_tr_booking',
                     '$howman_private','$min_private_booking','$trcancel_days','$percentage'
                ,'$change_policy','$days_change_policy','$pay_change_policy','$fromage','$cancellation')");
      


      
      
        
    }
    else
    {

        if($instbooking==1)  {
            $passminday= "mindaysinst=".$mindaysinst.",";
            
        }
        if($private_tr_booking==1) {
            $passhowmany= "howman_private=".$howman_private.",";
            $passminprivate= "min_private_booking=".$min_private_booking.",";  
        }
         if($change_policy==1){
            $pass_change_policy= "days_change_policy=".$days_change_policy.",";  
        }
       $sqlopdt = "UPDATE tours_price_data  SET 
                instbooking='$instbooking',
                $passminday
                private_tr_booking='$private_tr_booking',
                $passhowmany
                $passminprivate
                trcancel_days='$trcancel_days',
                percentage='$percentage',
                change_policy='$change_policy',
                $pass_change_policy
                pay_change_policy='$pay_change_policy',
                fromage='$fromage',
                endage='$endage',
                cancellation='$cancellation'
                WHERE oid='$oid' and  tid='$tid'";
               $conn->query($sqlopdt);
    }
    

}     

if(($_REQUEST['Action']=='multisubmit')){
    $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
    $tid=$conn -> real_escape_string($_REQUEST['tid']);
    $mulperson=$conn -> real_escape_string($_REQUEST['mulperson']);
    
    $price=$conn -> real_escape_string($_REQUEST['price']);
    $sqlprice = "INSERT INTO tour_multi_price (oid, tid,perperson,price)  VALUES ('$oid', '$tid','$mulperson','$price')";
    $getdata=$conn->query("select * from tour_multi_price where oid='$oid' and  tid='$tid'");
    ?>
    <table class="table">
    <?php
     while($fetchmulti=$getdata -> fetch_assoc()){ ?>
        <tr>
             <td><?php echo $fetchmulti['perperson'];?></td>
             <td><?php echo $fetchmulti['price'];?></td>
             <td><a class="button   button-disabled" href="#">Remove</a></td>
       </tr>                              
    <?php
     }
     ?>
    </table>
     <?php                            
     $conn->query($sqlprice);
}

/* Insert Map Value in Database */

   if(isset($_REQUEST['mapaction'])){
     error_reporting(E_ALL);
     ini_set('display_errors', 1);
     ini_set('display_startup_errors', 1);
     include('db.php');
     ?>
         <style>
          .loclist li{
                   list-style: none;
                   border-bottom: 1px solid #ddd;
                   line-height: 35px;
                   position:relative;
             }
              .loclist li:first-child:after
              {
                  content:'';
                  position:absolute;
                  
              }
              .loclist li:last-child:after
              {
                  
              }
          </style>
      <?php 
     
       $tid=$conn -> real_escape_string($_REQUEST['tid']?? '');
       $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
       $getmaps=$conn->query("select * from tour_itinerary_maps where oid='$oid' and  tid='$tid'");
       $row_cnt = $getmaps->num_rows;
    
       $fetchmaps=$getmaps -> fetch_assoc();
       
       $durquery=$conn->query("select * from tours where oid='$oid' and  tid='$tid'");
       $fetduration=$durquery -> fetch_assoc();
     
       $decodempdata = [];

       if ($fetchmaps && isset($fetchmaps['mapdata'])) {
           $decoded = json_decode($fetchmaps['mapdata'], true); // decode as array
           if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
               $decodempdata = $decoded;
           }
       }
    
      if(!empty($_REQUEST['getplacename']) && !empty($_REQUEST['lat']) && !empty($_REQUEST['lng']))
       {
         $data[$row_cnt]= array ('location' => $conn -> real_escape_string($_REQUEST['getplacename']),
                               'lat' => $conn -> real_escape_string($_REQUEST['lat']),
                               'lng'=> $conn -> real_escape_string($_REQUEST['lng'])
                              );
             if($row_cnt==0)  {
                 $jsondata= json_encode($data);
                   
                    if($_REQUEST['getplacename']!=''){
                         $conn->query("INSERT INTO tour_itinerary_maps (oid, tid ,mapdata) VALUES ('$oid', '$tid','$jsondata')");
                         
                     }
               }
               else{
                      $decodethis=json_decode($fetchmaps['mapdata']);
                      $mergejson=array_merge($decodethis,$data);
                      $jsondata= $conn -> real_escape_string(json_encode($mergejson));
                      $sqlopdt = "UPDATE tour_itinerary_maps  SET  mapdata='$jsondata' WHERE oid='$oid' and  tid='$tid'";  
                      $conn->query($sqlopdt);
                     }
              
             
          }
        ?>
        <script>
              jQuery(document).ready(function(){
       
                     document.getElementById("lat").value='';
                     document.getElementById("lng").value='';
                    document.getElementById("getplacename").value='';
                    document.getElementById("searchbox").value='';
                });
                      
        </script>
        <div class="col-sm-4"> 
           <ul class="loclist" id="post_list">
                 <?php
                   $getmaps=$conn->query("select * from tour_itinerary_maps where oid='$oid' and  tid='$tid'");
                   $fetduration=$getmaps -> fetch_assoc();
                   $decodempdata=json_decode($fetduration['mapdata']);
                  $k=0;
                          foreach($decodempdata as $showloc){ ?>
                             <li data-post-id="<?php echo $k; ?>" <?php if(count($decodempdata)==1):?> class="firstElement"  <?php endif;?>   data-tid="<?php echo $tid;?>" data-userid="<?php echo $oid;?>">
                                 <?php  echo stripslashes ($showloc->location);?>
                                 <span class="del-loc-check" data-locid="<?php echo $k; ?>" data-tid="<?php echo $tid;?>"  data-userid="<?php echo $oid;?>"> 
                                     <i class="fa fa-trash" aria-hidden="true"></i> 
                                   </span>
                                </li>
                            <?php
                            $k++;
                            }   
                        ?>
               </ul>    
           </div>
       <div class="col-sm-8"><div class="reordermap"><?php  showroutes($tid, $oid);?></div>
                <script>
                     
                       /* Delete  Map Location */
                       
                 jQuery( '.del-loc-check' ).on('click', function() {
                                jQuery('.mapresonse').html("<b>Loading response...</b>")
                                 var oid = jQuery(this).data("userid");
                                 var tid = jQuery(this).data("tid");     
                                 var locid = jQuery(this).data("locid"); 
                                 var delMapsid="yes"; 
                                 $.ajax({
                                    type: 'POST',
                                    url: '/wp-content/themes/adventure-republiq/operator/process.php',
                                    data :{oid:oid,tid:tid,locid:locid,delMapsid:delMapsid},
                                         success: function(data){
                                            document.getElementById("minlocation").value='';
                                          $('.mapresonse').html(data);
                                    }   
                             });
                               
                           });
                             
                   $( "#post_list" ).sortable({
                 placeholder : "ui-state-highlight",
                 update  : function(event, ui)
                 {
                     var post_order_ids = new Array();
                     var tid = new Array();
                     var userid = new Array();
                   $('#post_list li').each(function(){
                       post_order_ids.push($(this).data("post-id"));
                     tid.push($(this).data("tid"));
                     userid.push($(this).data("userid"));
                   });
                     jQuery('.mapresonse').html("<b>Loading response...</b>");
                   $.ajax({
                     url: '/wp-content/themes/adventure-republiq/operator/process.php',
                     method:"POST",
                     data:{post_order_ids:post_order_ids, tid:tid, userid:userid},
                     success:function(data)
                     {
                       $('.mapresonse').html(data);
                     }
                   });
                 }
               });
               </script>
                      
    <?php        
     }
     
     
     /*  Delete a Map Location  */ 

if(!empty($_REQUEST['delMapsid'])) {
    
       $tid=$conn -> real_escape_string($_REQUEST['tid']);
       $oid=$conn -> real_escape_string($_REQUEST['oid']);
       $locid=$conn -> real_escape_string($_REQUEST['locid']);
       $getmaps=$conn->query("select * from tour_itinerary_maps where oid='$oid' and  tid='$tid'");
       $fetchmaps=$getmaps -> fetch_assoc();
       $decodempdata=json_decode($fetchmaps['mapdata']);
       $arr_index = array();
         foreach ($decodempdata as $key => $value) {
     
               if ($key == $locid) {
                   $arr_index[] = $key;
               }
           }
           foreach ($arr_index as $i) {
               unset($decodempdata[$i]);
               
           }
           $decodempdata = array_values($decodempdata);
           $jsonrmtypes= $conn -> real_escape_string(json_encode($decodempdata));
         
           if($jsonrmtypes=='[]')
           {
            
                $conn->query("DELETE FROM tour_itinerary_maps  WHERE oid='$oid' and  tid='$tid'"); 
           }
           else
           {
                $jsonrmtypes= $jsonrmtypes;
           }
            $sqlopdt = "UPDATE tour_itinerary_maps  SET  mapdata='$jsonrmtypes' WHERE oid='$oid' and  tid='$tid'";
               
                $conn->query($sqlopdt);
       
         ?>
                <div class="col-sm-4"> 
                       <ul class="loclist" id="post_list">
                         <?php $k=0;
                          foreach($decodempdata as $showloc){ ?>
                             <li data-post-id="<?php echo $k; ?>" data-tid="<?php echo $tid;?>"  <?php if(count($decodempdata)==1):?> class="firstElement"  <?php endif;?>   data-userid="<?php echo $oid;?>">
                                 <?php  echo stripslashes ($showloc->location);?>
                                 <span class="del-loc-check" data-locid="<?php echo $k; ?>" data-tid="<?php echo $tid;?>"  data-userid="<?php echo $oid;?>"> 
                                     <i class="fa fa-trash" aria-hidden="true"></i> 
                                   </span>
                                </li>
                            <?php
                            $k++;
                            }   
                          ?>
                       </ul>   
                 </div>
                      <div class="col-sm-8"><div class="reordermap"><?php showroutes($tid, $oid);?></div>
                      <script>
                     
                       /* Delete  Map Location */
                
                 jQuery( '.del-loc-check' ).on('click', function() {
                          jQuery('.mapresonse').html("<b>Loading response...</b>")
                                 var oid = jQuery(this).data("userid");
                                 var tid = jQuery(this).data("tid");     
                                 var locid = jQuery(this).data("locid"); 
                                 var delMapsid="yes"; 
                                 $.ajax({
                                    type: 'POST',
                                    url: AjaxUrl,
                                    data :{oid:oid,tid:tid,locid:locid,delMapsid:delMapsid},
                                         success: function(data){
                                          $('.mapresonse').html(data);
                                    }   
                             });
                               
                           });
                            $( "#post_list" ).sortable({
                 placeholder : "ui-state-highlight",
                 update  : function(event, ui)
                 {
                     var post_order_ids = new Array();
                     var tid = new Array();
                     var userid = new Array();
                   $('#post_list li').each(function(){
                       post_order_ids.push($(this).data("post-id"));
                     tid.push($(this).data("tid"));
                     userid.push($(this).data("userid"));
                   });
                     jQuery('.mapresonse').html("<b>Loading response...</b>");
                   $.ajax({
                     url: '/wp-content/themes/adventure-republiq/operator/process.php',
                     method:"POST",
                     data:{post_order_ids:post_order_ids, tid:tid, userid:userid},
                     success:function(data)
                     {
                       $('.mapresonse').html(data);
                     }
                   });
                 }
               });
               </script>
                      
<?php
}   
   
/* Reorder Update Map value in database */

   if($_POST["tid"])
   {
    
       $post_order = isset($_POST["post_order_ids"]) ? $_POST["post_order_ids"] : [];
       $tid = isset($_POST["tid"]) ? $_POST["tid"] : [];
       $oid = isset($_POST["userid"]) ? $_POST["userid"] : [];
      if(!empty($oid)){
       $getrID=$tid[0];
       $getoID=$oid[0];
       
       $getmaps=$conn->query("select * from tour_itinerary_maps where tid='$getrID'");
       $fetchmaps=$getmaps -> fetch_assoc();
       $decodempdata=json_decode($fetchmaps['mapdata']);
       $newData=rerderArray($decodempdata, $post_order, true);
       $jsondata= json_encode($newData);
    
       $conn->query("UPDATE tour_itinerary_maps  SET  mapdata='$jsondata' WHERE oid='$getoID' and  tid='$getrID'"); 
       //showroutes($getrID, $getoID);
       $getmaps=$conn->query("select * from tour_itinerary_maps where oid='$getoID' and  tid='$getrID'");
       $fetchmaps=$getmaps -> fetch_assoc();
       $decodempdata=json_decode($jsondata);
     
       ?>
        <div class="col-sm-4">
                       <ul class="loclist" id="post_list">
                         <?php $k=0;
                          foreach($decodempdata as $showloc){ ?>
                             <li data-post-id="<?php echo $k; ?>" data-tid="<?php echo $getrID;?>" data-userid="<?php echo $getoID;?>">
                                 <?php  echo stripslashes ($showloc->location);?>
                                 <span class="del-loc-check" data-locid="<?php echo $k; ?>" data-tid="<?php echo $getrID;?>"  data-userid="<?php echo $getoID;?>"> 
                                     <i class="fa fa-trash" aria-hidden="true"></i> 
                                   </span>
                                </li>
                            <?php
                            $k++;
                            }   
                          ?>
                       </ul>   
                 </div>
                      <div class="col-sm-8"><div class="reordermap"><?php showroutes($getrID, $getoID);?></div>
                      
                        <script>
                     
                       /* Delete  Map Location */
                
                 jQuery( '.del-loc-check' ).on('click', function() {
                          jQuery('.mapresonse').html("<b>Loading response...</b>")
                                 var oid = jQuery(this).data("userid");
                                 var tid = jQuery(this).data("tid");     
                                 var locid = jQuery(this).data("locid"); 
                                 var delMapsid="yes"; 
                                 $.ajax({
                                    type: 'POST',
                                    url: AjaxUrl,
                                    data :{oid:oid,tid:tid,locid:locid,delMapsid:delMapsid},
                                         success: function(data){
                                          $('.mapresonse').html(data);
                                    }   
                             });
                               
                           });
                            $( "#post_list" ).sortable({
                 placeholder : "ui-state-highlight",
                 update  : function(event, ui)
                 {
                     var post_order_ids = new Array();
                     var tid = new Array();
                     var userid = new Array();
                   $('#post_list li').each(function(){
                       post_order_ids.push($(this).data("post-id"));
                     tid.push($(this).data("tid"));
                     userid.push($(this).data("userid"));
                   });
                     jQuery('.mapresonse').html("<b>Loading response...</b>");
                   $.ajax({
                     url: '/wp-content/themes/adventure-republiq/operator/process.php',
                     method:"POST",
                     data:{post_order_ids:post_order_ids, tid:tid, userid:userid},
                     success:function(data)
                     {
                       $('.mapresonse').html(data);
                     }
                   });
                 }
               });
               </script>
<?php                       
}
   }
  function rerderArray(array &$array, array $orderArray, $strict = null)
{
   if (!empty($array) && !empty($orderArray)) {
       $ordered = [];
       foreach ($orderArray as $key) {
          $ordered[$key] = $array[$key];
           unset($array[$key]);
       }

       $array = array_merge($ordered, $array);
      return $array;
   }
}

/* Update Language */

if(!empty($_REQUEST['langid'])) {

 include('db.php');

       $tid = $_REQUEST["tourid"];
       $checklng=$conn->query("select guide_language from tours where tid='$tid'");
       $fetchLang=$checklng -> fetch_assoc();
       if(!empty($fetchLang['guide_language']))
       {
            $langid = $fetchLang['guide_language'].",".$_REQUEST["langid"];
       }
       else
       {
           $langid = $_REQUEST["langid"];
       }
       $conn->query("UPDATE tours  SET  guide_language='$langid' WHERE tid='$tid'");
       $arrayData=array_map('intval', explode(',', $langid));
       $array = implode("','",$arrayData);
       echo get_guidelanguage_chekboxes('guidelanguage', "passval", $fetchLang['guidelanguage'], $tid, $arrayData, $check=0);
          
}

if(!empty($_REQUEST['dellang'])) {
 
       $removeData=array();
       $tid = $_REQUEST["tourid"];
       $checklng=$conn->query("select guide_language from tours where tid='$tid'");
      
       $fetchLang=$checklng -> fetch_assoc();
       $removeData[]=$_REQUEST['selectID'];
       $updateArray=array();
       $selected_language=explode(",",$fetchLang['guide_language']);
        foreach($selected_language as $ShowData)
        {
               if(!in_array( $ShowData, $removeData)){
                  $updateArray[]=$ShowData;
               }
         }
        
        $List = implode(', ', $updateArray); 
        $conn->query("UPDATE tours  SET  guide_language='$List' WHERE tid='$tid'");
        $arrayData=array_map('intval', explode(',', $List));
        $array = implode("','",$arrayData);
       echo get_guidelanguage_chekboxes('guidelanguage', "passval", $fetchLang['guidelanguage'], $tid, $arrayData, $check=0);
      
       
   }
   if(!empty($_REQUEST['priceboxload'])) {  
     include('db.php'); 
    
    $tid=$conn -> real_escape_string($_REQUEST['tourid']?? '');
    $crval=$conn -> real_escape_string($_REQUEST['crval']?? '');
    $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
    echo showPriceTable($tid,$oid);  
   
}

if(!empty($_REQUEST['UpdatePrice'])) {   

 include('db.php');
    
    $tid=$conn -> real_escape_string($_REQUEST['tourid']?? '');
    $price=$conn -> real_escape_string($_REQUEST['price']?? '');
    $member=$conn -> real_escape_string($_REQUEST['member']?? '');
    $oid=$conn -> real_escape_string($_REQUEST['oid']?? '');
    $memberkey=$conn -> real_escape_string($_REQUEST['memberkey']?? '');
    $lastkey=$conn -> real_escape_string($_REQUEST['lastkey']?? '');
    $lastprice=$conn -> real_escape_string($_REQUEST['lastprice']?? '');
    $mainprice=$conn -> real_escape_string($_REQUEST['oneprice']?? '');
    $nextkey=$conn -> real_escape_string($_REQUEST['nextkey']?? '');
    
    
    $priceQuery=$conn->query("select tourprice,priceoption from tours_price_data where  tid='$tid'");
    $fetchPrice =$priceQuery -> fetch_assoc();
 
    $groupData = $conn->query("SELECT * FROM group_price_data WHERE tid='$tid'");

    if ($groupData && $groupData->num_rows > 0) {
        $row_cnt = $groupData->num_rows;  // ✅ correct usage
        $fetchData = $groupData->fetch_assoc();  // now get the data
        $array = json_decode($fetchData['price_meta']);
    } else {
        $row_cnt = 0;
        $array = []; // to avoid foreach() on null later
    }
    ;


    $i=1;
    $decodepriceopt = [];

    if (!empty($fetchPrice['priceoption']) && is_string($fetchPrice['priceoption'])) {
        $decodepriceopt = json_decode($fetchPrice['priceoption'], false);
    }
    $perpeson='';
    foreach($decodepriceopt as $priceoption) {
      $perpeson= $priceoption->perpeson;
      break; 
    }
    if($_REQUEST['recheck']==1){
         $i=1;
           foreach($array as $updatejson){
              $updatPrice=$updatejson->price;
              $data[]= array ('perperson' =>$i,'price'=> $fetchPrice['tourprice'], 'key'=> $member);
               $i++;
         }
          $encodJson=json_encode($data);
          $sqlopdt = "UPDATE group_price_data  SET  price_meta='$encodJson'  WHERE tid='$tid'"; $conn->query($sqlopdt);
      }
      
    else{
      $i=1;
      if($price){
        
         if(!empty($lastkey)){
            $fetchData = $groupData->fetch_assoc();  
            $getarray = [];

            if (!empty($fetchData) && !empty($fetchData['price_meta'])) {
                $getarray = json_decode($fetchData['price_meta'], true);
            }
                    foreach($getarray as &$a){
                         $btkey=$lastkey-1;
                         $perkey= $a['key'];
                       
                        if($a['perperson']==$btkey){
                             $perPrice=$a['price'];
                          
                           }
                        if($a['key'] == $memberkey){
                         
                             $a['price'] = $lastprice;
                             $a['key'] =$memberkey;
                       }
                       if($a['perperson'] == $memberkey){
                          
                             $a['price'] = $lastprice;
                             $a['key'] =$memberkey;
                       }
                       if($lastkey>$memberkey)
                       { 
                           if($a['perperson']>=$memberkey && $a['perperson']<$lastkey){
                                $a['price'] = $lastprice;
                               $a['key'] =$memberkey;
                           }
                       }
                       if($a['key'] == $lastkey){
                           
                             $perval=$a['key']-1;
                             if($lastkey==2 && $memberkey==1 ){
                                   $a['price'] = $lastprice;
                                   $a['key'] =$memberkey;
                             }
                             else{
                         
                                     if($lastkey==1 && $a['perperson']<=$memberkey) {
                                           $a['price'] = $mainprice;
                                           $a['key'] =$memberkey;
                                       }
                                     
                                    elseif($a['perperson']>=$lastkey && $a['perperson'] <$lastkey ){
                                        //echo $memberkey."-->".$lastkey."-->".$a['perperson'];
                                              $a['price'] = $mainprice;
                                             $a['key'] =$memberkey;
                                      }
                                      else{
                                          if($a['perperson']>=1 && $a['perperson']<=$memberkey){
                                             if($memberkey>$lastkey){
                                          
                                                      $a['price'] = $perPrice;
                                                      $a['key'] =$memberkey;
                                            }
                                               else{
                                                     if($perPrice==0){
                                                      $perPrice=$mainprice;
                                                  }  
                                                 
                                                      $a['price'] = $perPrice;
                                                      $a['key'] =1;
                                               }
                                          }
                                          else{
                                            
                                              $a['price'] = $lastprice;
                                              $a['key'] =$memberkey;
                                          
                                          }
                                        
                                        
                                      } 
                               }  
                       
                       }
                    }
                  $encodJson=json_encode($getarray);
              
         }
         
         else{
      
              if($member==$memberkey && $lastprice==''){
               $data = [];
                   foreach($array as $updatejson){
                               if($i==$member || $i>$member){
                                    $updatPrice=$price;
                                }
                               elseif($i<$member){
                                   $updatPrice=$updatejson->price;
                                }
                               else{
                                  $updatPrice=$fetchPrice['tourprice'];;
                               }
                               if($i>=$member){
                              
                                    $data[]= array ('perperson' =>$i,'price'=> $updatPrice, 'key'=> $member);
                                }
                               elseif($i<$member){
                                   $data[]= array ('perperson' =>$i,'price'=> $updatPrice, 'key'=> $updatejson->key);
                               }
                               else{
                                    $data[]= array ('perperson' =>$i,'price'=> $updatPrice, 'key'=> $i);
                                }
                            $i++; 
                       }
                 $encodJson=json_encode($data);
            }
            else{
              echo "no";
                $valkey=array();
                $getarray = json_decode($fetchData['price_meta'], true);
                $i=2;
                  foreach($getarray as &$a){
                         $valkey[$i]=$a['key'];
                         $i++;
                  }
             
                 $unsortarray=array_unique($valkey);
              
                 $sortarray=array_values(array_filter($unsortarray));
                 $mergval=array();
                 $maxmergval=array();
                  foreach($sortarray as $getArray){
                      if($getArray!=$memberkey )
                       {
                           $mergval[]=$getArray;
                       }
                        if($getArray!=$memberkey && $getArray>$memberkey)
                       {
                           $maxmergval[]=$getArray;
                       }
                  }
                   $minindex= min($mergval);
                   $maxindex= min($maxmergval);
                 
                    foreach($getarray as &$a){
                         $btkey=$nextkey-1;
                            if($a['perperson']==$btkey){
                                  $perPrice=$a['price'];
                               }
                               if($a['price']==$lastprice){
                                   echo "yes";
                                $a['price']=$price;
                               }
                               // if($nextkey==1)
                               //   {  
                               //      if($a['perperson']>=1 && $a['perperson']<$memberkey){
                               //       $a['price'] =$mainprice;
                               //   }
                               //   else
                               //   { 
                               //       echo "yes";
                               //       if($a['key']==$memberkey && $a['perperson']<= $minindex ){
                               //           $a['price']=$price;
                               //         }
                               //   }
                                
                               // }
                               // else{
                             
                               //     if($a['key'] == $memberkey && !($a['key'] < $memberkey)){
                               //           if($nextkey>$memberkey){
                               //           echo $a['key']."-->".$nextkey."-->" .$memberkey."-->".$a['perperson']."<br>";
                               //           $a['price'] =$price;
                               //       }
                               //       elseif($nextkey<$memberkey){
                                         
                               //           echo $a['key']."-->".$nextkey."-->" .$memberkey."-->".$a['perperson']."<br>";
                               //           if($a['perperson']>=$nextkey && $a['perperson']<$memberkey){
                               //               $a['price'] =$perPrice;
                               //               }
                               //           else {
                               //                   echo "sssno";
                               //               $a['price'] =$price;
                               //           }
                               //       }
                               //      else {    //$a['price'] =22222;
                               //      }
                               //   }
                               // }
                      
                    }
                 $encodJson=json_encode($getarray);
            }
         }
         $sqlopdt = "UPDATE group_price_data  SET  price_meta='$encodJson' WHERE tid='$tid'";
                    $conn->query($sqlopdt);
        
   //   if($row_cnt>0){
          
   //               $sqlopdt = "UPDATE group_price_data  SET           price_meta='$encodJson'
   //                   WHERE tid='$tid'";
   //                  $conn->query($sqlopdt);
   //       }
   }
}
  sleep(1);
     ?> <script>
       jQuery(document).ready(function(){
               jQuery(".thisprice").prop('disabled', false);
               jQuery(".thisprice").removeClass("loaderpro");
              
        });
        </script>
        <?php
     echo showPriceTable($tid,$oid);
}
if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'trasimage') {

     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $transtranporttype=$conn -> real_escape_string($_REQUEST['transtranporttype']);
     $trddecp=$conn -> real_escape_string($_REQUEST['trddecp']);
     $transname=$conn -> real_escape_string($_REQUEST['transname']);
     $imgId=$conn -> real_escape_string($_REQUEST['imgid']);
 
           $sql = "INSERT INTO operator_transport (oid,transname,transports,description,imgId)
           VALUES ('$oid', '$transname', '$transtranporttype','$trddecp', '$imgId')";
    $conn->query($sql);
    echo  guide_transport($oid);
}

if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'Updatetrasimage') {
  
     $id=$conn -> real_escape_string($_REQUEST['id']);
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $transtranporttype=$conn -> real_escape_string($_REQUEST['transtranporttype']);
     $trddecp=$conn -> real_escape_string($_REQUEST['trddecp']);
     $imgId=$conn -> real_escape_string($_REQUEST['imgid']);
     $transname=$conn -> real_escape_string($_REQUEST['transname']);
     $sqlopdt = "UPDATE operator_transport  SET 
                    transname='$transname',
                     transports='$transtranporttype',
                     description= '$trddecp',
                     imgId='$imgId'
                     WHERE id='$id'";
                    $conn->query($sqlopdt);
           
    echo  guide_transport($oid);
}
if(!empty($_REQUEST['transId'])) {  

    $tid=$conn -> real_escape_string($_REQUEST['transId']);
    $oid=$conn -> real_escape_string($_REQUEST['oid']);
    $imgid=$conn -> real_escape_string($_REQUEST['imgid']);
    $conn->query("DELETE FROM operator_transport WHERE id='$tid'"); 
    $conn->query("DELETE FROM tour_images WHERE imgid='$imgid'"); 
   ?>
   <script>
        jQuery(".deltransport").click(function() {
          jQuery('#trasntable').html("<b>Loading response...</b>");
           var tid = jQuery(this).data("tid");
           var imgid = jQuery(this).data("imgid");
           var oid = jQuery(this).data("oid");
           jQuery('.trasntable').html("<b>Loading response...</b>"); 
           
             $.ajax({
                  type: 'POST',
                  url:  '/wp-content/themes/adventure-republiq/operator/process.php',
                  data : {transId:tid,imgid:imgid,oid:oid},
                  success: function(data){
                      jQuery('#trasntable').html(data);
                   }
           
       });
      
  }); 
   </script>
  
<?php
 echo guide_transport($oid);
}
if(!empty($_REQUEST['prid'])) {  

    $prid=$conn -> real_escape_string($_REQUEST['prid']);
    $oid=$conn -> real_escape_string($_REQUEST['oid']);
    $conn->query("DELETE FROM operator_guide_profile WHERE id='$prid'");
   ?>
   <script>
jQuery(".delgdprofile").click(function() {
     jQuery('#profiletable').html("<b>Loading response...</b>");
         var prid = jQuery(this).data("prid");
        var oid = jQuery(this).data("oid");
        $.ajax({
              type: 'POST',
              url: AjaxUrl,
              data : {prid:prid,oid:oid},
              success: function(data){
                  jQuery('#profiletable').html(data);
               }
       
       });
      
  });  
   </script>
<?php
  echo  guide_reload($oid) ;
}
if(!empty($_REQUEST['crstatus'])) { 
   $checktrstatus=$conn -> real_escape_string($_REQUEST['checktrstatus']);
   $tid=$conn -> real_escape_string($_REQUEST['tid']);
   if($checktrstatus=='no'){
       $checktrstatus=0;
   }
   $conn->query("UPDATE tours  SET  tourstatus='$checktrstatus'  WHERE tid='$tid'");
}
if(!empty($_REQUEST['checktrstatus'])) { 

   $checktrstatus=$conn -> real_escape_string($_REQUEST['checktrstatus']);
   $tid=$conn -> real_escape_string($_REQUEST['tid']);
   if($checktrstatus=='no'){
       $checktrstatus=0;
   }
   $conn->query("UPDATE tours  SET  tourstatus='$checktrstatus'  WHERE tid='$tid'");
}
if(!empty($_REQUEST['randid']))
{
?>
    <input type="hidden"   name="imgId[]"  value="<?php echo uniqid();?>">
<?php
}
if(!empty($_REQUEST['trasnImgId']))
{
?>
    <input type="hidden"   name="imgid"  value="<?php echo uniqid();?>">
<?php
}
if(!empty($_REQUEST['serviceid']))
{
?>
    <input type="hidden"   name="serviceid[]"  value="<?php echo uniqid();?>">
<?php
}
if(!empty($_REQUEST['viewpop']))
{   
   $PaidAmount=0;
   $adulttotal=0;
   $totaltrans=0;
   $roomtotal=0;
   $mainothtotal=0;
   $servicetotal=0;
   $othercattotal=0;
   $orderid=$_REQUEST['orderid'];
   $opname=$_REQUEST['opname'];    
   $opemail=$_REQUEST['opemail'];
   $checktour=$_REQUEST['checktour'];
   $inrconvert=$_REQUEST['inrconvert'];
   if($checktour>0){
   $result = $conn->query("SELECT * FROM cartSession LEFT JOIN tour_itinerary ON tour_itinerary.tid=cartSession.tid  
             LEFT JOIN cartuserifo ON cartuserifo.orderid='$orderid'  LEFT JOIN customize_trip ON customize_trip.id=cartSession.tid 
             LEFT JOIN cartAddon ON cartAddon.orderid='$orderid' WHERE cartSession.orderid='$orderid'");
    }
  else {
   $result = $conn->query("SELECT * FROM cartSession LEFT JOIN tour_itinerary ON tour_itinerary.tid=cartSession.tid  
             LEFT JOIN cartuserifo ON cartuserifo.orderid='$orderid' LEFT JOIN cartAddon ON cartAddon.orderid='$orderid' WHERE cartSession.orderid='$orderid'");
      }
   
  
              
   $fetchdata=$result -> fetch_assoc();
   $opmsg="New booking has been received:";

   $tid=$fetchdata['tid'];
   $geimages = $conn->query("SELECT * FROM tour_images  WHERE tid='$tid'");
   echo "SELECT * FROM tour_images  WHERE tid='$tid'";
   $fetchimages=$geimages -> fetch_assoc();
   $allImages=explode (",", $fetchimages['tourimages']);

   $checktour=$fetchdata['checktour'];
   $totalpax=$fetchdata['adult']+$fetchdata['othcount'];
   $jsondestination=json_decode($fetchdata['destination']);
   $metatravllerinfo=json_decode($fetchdata['metatravllerinfo']);
   $pickupmsg=$metatravllerinfo->pickupmsg;
   $customer_dob=$metatravllerinfo->dob;
   $customer_country=$metatravllerinfo->nationality;
   $gender=$metatravllerinfo->mngender;
   $customer_phone=$metatravllerinfo->travelpcc.$metatravllerinfo->mobileno;
   $customer_name=$fetchdata['custfname']."&nbsp;" .$fetchdata['custlname']; 
   $customer_email=$fetchdata['custemail'];
   $metacustinfo=json_decode($fetchdata['metacustinfo']);
   $opcurrency=$_REQUEST['opcurrency'];
   $metacustinfo=json_decode($fetchdata['metacustinfo']);
   $jsonothercat=json_decode($fetchdata['othercat']);
   $jsontrasadons=json_decode($fetchdata['trasadons']);
   $jsonroomsaddon=json_decode($fetchdata['roomsaddon']);
   $jsonothaddons=json_decode($fetchdata['othaddons']);
   $jsonotherservicemeta=json_decode($fetchdata['otherservicemeta']);
   $passport=$metatravllerinfo->passportno;
   $passport_start_date=$metatravllerinfo->issuedate;
   $passport_end_date=$metatravllerinfo->expiredate;     
   
   if($fetchdata['disprice']>0){
             $mainprice=$fetchdata['disprice'];
         }
         else{
             $mainprice=$fetchdata['mainprice'];
         }
  
    $fnsybol=$fetchdata['custcrncy'];
    $totalAdult=str_replace( ',', '', $mainprice) *  $fetchdata['adult'];
    $promocode=$fetchdata['promocode'];
    $promovalue=$fetchdata['promovalue'];
    $discountpromo=$fetchdata['discountpromo'];
    $oid=$fetchdata['oid'];
    $grandtotal=str_replace( ',', '', $fetchdata['grandtotal']);
    $totalprice=str_replace( ',', '', $fetchdata['totalprice']);
    $promototal=$totalprice-str_replace(',', '', $discountpromo);
    $tcsper= $fetchdata['tcsper'];
    $tcsval=str_replace( ',', '', $fetchdata['tcsval']);
    $tcstotal=str_replace( ',', '', $fetchdata['tcstotal']);
    $country=$fetchdata['country']; 
   ?>
    <div id="printMe">
          <table  style="color: #4a4a4a;font-size: 14px;font-family: Roboto, sans-serif; margin: auto; background: #fff" width="800" cellspacing="10" cellpadding="0">	                
            <tbody>
                <tr>			          
                    <td align="center"><img src="https://dashboard.adventurerepubliq.com/wp-content/uploads/2018/07/newLogo.png"> </td>	           	  
                 </tr>
               </tbody>
           </table>	
           <table  style="color: #4a4a4a; border:1px solid #eee; font-size: 14px;font-family: Roboto, sans-serif; margin: auto; box-shadow: 1px 0px 13px 6px #eeed;" width="800" cellspacing="10" cellpadding="5">					
                    <tbody>
           <tr>
             <td colspan="4"><h2 style="padding-top: 16px; margin: 0">Dear <?php echo $opname;?>,</h2>
               <p style="margin: 10px 0;font-size:14px">You have received a new booking</p>
                 <b style="display: block; background: #0056b3;color: #fff; line-height: 29px; padding-left: 10px; border-radius: 2px;margin-bottom: 8px;">#<?php echo $orderid;?></b>
           
             </td>
           </tr>
          <tr>
                  <td colspan="2" style="border-bottom:1px solid #eee"></td>
                </tr>
                   <tr>
            <td colspan="4">
           <table style="color:#4a4a4a;line-height:30px;font-size:14px;font-family:Roboto,sans-serif;background:#fff" width="100%" cellspacing="0" cellpadding="0">
               <tbody>
                  <tr>
                   <td valign="top" style="width:40%">
                   <img src="/wp-content/themes/adventure-republiq/operator/uploads/<?php echo $allImages[0];?>" style="border-radius: 3px;width: 300px;">
                       <br>
                     </td>
                <td style="width:60%; padding-left:16px">
                  <table style="color:#4a4a4a;line-height:30px;font-size:14px;font-family:Roboto,sans-serif;background:#fff" width="100%" cellspacing="0" cellpadding="0">
               <tr>
                   <td style="border-bottom:1px solid #eee; width: 38%"><b>Itinerary</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $fetchdata['tourname'];?></td>
                 </tr>
                          <tr>
                   <td style="border-bottom:1px solid #eee"><b>Itinerary Duration</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $fetchdata['duration'];?> Days</td>
                </tr>
                         <tr>
               <td style="border-bottom:1px solid #eee"><b>Itinerary Date</b></td>
               <td style="border-bottom:1px solid #eee"><?php echo $fetchdata['startdate'];?></td>
                </tr>
                        <tr>
               <td style="border-bottom:1px solid #eee"><b>Country</b></td>
                                 <td style="border-bottom:1px solid #eee">
                                     <p style="word-wrap: anywhere;margin: 0;max-width: 304px"><?php 
                                       if($country) {
                                           $starttime=date("h:i a", strtotime($fetchdata['starttime']));
                                           echo $country;
                                       }
                                       else{
                                           $starttime=$fetchdata['starttime'];
                                           custermshow($jsondestination);
                                       }
                                     ?></p>
                                </td>
                     </tr>
                   <tr>
                       <td style="border-bottom:1px solid #eee"><b>Start In</b></td>
                       <td style="border-bottom:1px solid #eee"><?php echo $fetchdata['startdate'];?></td>
                     </tr>
                              <tr>
                       <td style="border-bottom:1px solid #eee"><b>End In</b></td>
                       <td style="border-bottom:1px solid #eee"><?php echo $fetchdata['endate'];?></td>
                      </tr>
                                <tr>
                       <td style="border-bottom:1px solid #eee"><b>Tour Type</b></td>
                       <td style="border-bottom:1px solid #eee"><?php echo $fetchdata['trtype'];?></td>
                     </tr>
                              
                               <tr>
                       <td style="border-bottom:1px solid #eee"><b>Booking </b></td>
                       <?php
                        if($country) { ?>
                             <td style="border-bottom:1px solid #eee">Custom</td>
                        <?php } 
                         else { ?>
                            <td style="border-bottom:1px solid #eee"><?php echo $fetchdata['instbooking'];?></td>
                       <?php } ?>
                       
                       </tr>
                            <tr>
                       <td style="border-bottom:1px solid #eee"><b>Itinerary Time</b></td>
                       <td style="border-bottom:1px solid #eee"><?php echo $starttime;?></td>
                     </tr>
                           <tr>
                   <td style="border-bottom:1px solid #eee"><b>Itinerary Member(s)</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $totalpax;?></td>
                 </tr>
              </table>
            </td>
          </tr>
          <tr>
                     <td colspan="2"><b>Special Request/Pickup Details:</b>
                          <p style="margin: 0;text-align: justify;"><?php echo $pickupmsg;?></p>
                       </td>			 
            </tr> 
             </tbody>
       </table></td>
      </tr>
                 <tr>
                <td colspan="4" style="border-bottom:1px solid #eee"></td>
                </tr>
                   <tr>
                     <td align="left" colspan="4" >
                       <h3 style="font-size:16px;margin:0; display: block; background: #0056b3;color: #fff;position: relative; padding-left: 11px;line-height: 30px; border-radius: 2px;">Lead Traveller Details:</h3></td>
                      </tr>
                   <tr>
             <td colspan="4" style="padding: 10px;">
             <table style="color:#4a4a4a;line-height:30px;font-size:14px;font-family:Roboto,sans-serif;background:#fff" width="100%" cellspacing="0" cellpadding="0">
               <tbody>
                 <tr>
                   <td style="border-bottom:1px solid #eee"><b>Name</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $customer_name;?></td>
                 </tr>
                 <tr>
                   <td style="border-bottom:1px solid #eee"><b>Date of Birth</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $customer_dob;?></td>
                 </tr>
                   <tr>
                   <td style="border-bottom:1px solid #eee"><b>Gender</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $gender;?></td>
                 </tr>
                 <tr>
                   <td style="border-bottom:1px solid #eee"><b>Email</b></td>
                   <td style="border-bottom:1px solid #eee"><a href="mailto:<?php echo $customer_email;?>" target="_blank"><?php echo $customer_email;?></a></td>
                 </tr>
                 <tr>
                   <td style="border-bottom:1px solid #eee"><b>Phone</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $customer_phone;?></td>
                 </tr>
                   <?php 
                 if($passport_start_date && $passport_end_date){ ?>
                 <tr>
                   <td style="border-bottom:1px solid #eee"><b>Passport</b></td>
                   <td style="border-bottom:1px solid #eee"><?php echo $passport;?></td>
                    </tr>
                     <tr>
                       <td style="border-bottom:1px solid #eee"><b>Issue Date</b></td>
                       <td style="border-bottom:1px solid #eee"><?php echo $passport_start_date;?></td>
                     </tr>
                     <tr>
                       <td style="border-bottom:1px solid #eee"><b>Expiry Date</b></td>
                       <td style="border-bottom:1px solid #eee"><?php echo $passport_end_date;?></td>
                     </tr>
                    <?php } ?>
                       <tr>
                       <td><b>Country</b></td>
                       <td><?php echo $customer_country;?></td>
                    </tr>
           </tbody>
     </table></td>
      </tr>
   <?php	if(!empty($metacustinfo)){?>
 <tr><td colspan="4" style="border-bottom:1px solid #eee"></td></tr>
                    <tr>
                        <td align="left" colspan="4" style="padding:10px 0 15px;width:100%">
              <h3 style="font-size:16px;margin:0; display: block; background: #0056b3;color: #fff;position: relative; padding: 0 0 0 13px;line-height: 30px;border-radius: 2px;">Traveller Details:</h3></td>
              </tr>
                   <tr>
                 <td colspan="4">
                        <table style="color:#4a4a4a;line-height:30px;font-size:14px;font-family:Roboto,sans-serif;background:#fff" width="100%" cellspacing="0" cellpadding="0">
                   <tbody>
                 <tr>
                  <td colspan="4" style="padding: 10px;">
                   <table style="color:#4a4a4a;line-height:30px;font-size:14px;font-family:Roboto,sans-serif;background:#fff" width="100%" cellspacing="0" cellpadding="0">
                                <tbody>
                                  <tr>
                                   <td style="padding-bottom: 16px; width:100%">
                                     <?php foreach($metacustinfo as $getinfo){ ?>
                                      <b style="font-size: 18px;border-bottom: 1px solid;display: block;margin: 5px 0 10px 0;"><?php echo $getinfo->typeoftraveller;?></b>
                                            <table width="100%" cellspacing="0" cellpadding="0" > 
                                  <tr> 
                                      <td style="border-bottom:1px solid #eee;width: 33%"><b>First Name</b></td>
                                      <td style="border-bottom:1px solid #eee;width: 33%"><b>Last Name</b></td>
                                      <td style="border-bottom:1px solid #eee;width: 33%"><b>Gender</b></td>
                                   </tr>
                                   <tr> 
                                      <td style="border-bottom:1px dashed #eee;"><?php echo $getinfo->fname;?></td>
                                      <td style="border-bottom:1px dashed #eee;"><?php echo $getinfo->lastname;?></td>
                                      <td style="border-bottom:1px dashed #eee;"><?php echo $getinfo->gender;?></td>
                                    </tr>
                                    <?php if(!empty($getinfo->passportno)):?>
                                        <tr> 
                                          <td style="border-bottom:1px solid #eee;width: 33%"><b>Passport No</b></td>
                                          <td style="border-bottom:1px solid #eee;width: 33%"><b>Issue Date</b></td>
                                          <td style="border-bottom:1px solid #eee;width: 33%"><b>Expiry Date</b></td>
                                          <td style="border-bottom:1px solid #eee;width: 33%;"><b>Nationality</b></td>
                                       </tr>
                                        <tr>
                                          <td style="border-bottom:1px dashed #eee;"><?php echo $getinfo->passportno;?></td>
                                          <td style="border-bottom:1px dashed #eee;"><?php echo $getinfo->issuedate;?></td>
                                          <td style="border-bottom:1px dashed #eee;"><?php echo $getinfo->endate;?></td>
                                          <td style="border-bottom:1px dashed #eee;"><?php echo $getinfo->nationality;?></td>
                                        </tr>
                                       <?php endif;?> 
                               </table>
                              <?php
                              }
                             ?>
                     </td>
                          </tr>
                      </tbody>
                 </table> 
                </td> 
              </tr>
                      </table>
                      </td>
                     </tr>
    <?php 
     }
    ?>
    
 <!--Payment Details-->
                     <tr>
                   <td colspan="2" style="border-bottom:1px solid #eee"></td>
                      </tr>
                    <tr>
             <td align="left" colspan="4" style="padding:10px 0 15px;width:100%">
              <h3 style="font-size:16px;margin:0; display: block; background: #0056b3;color: #fff;position: relative; padding: 0 0 0 13px;line-height: 30px;border-radius: 2px;">Payment Details:</h3></td>
           </tr>
           <?php
            if($country) {?>
             <tr> 
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Particuler</b></td>
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Member(s)</b></td>
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Price</b></td>
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Total</b></td>
              </tr>
              <tr>
                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo str_replace(array( '(', ')' ), '',  $fetchdata['trtype']);?></td>
                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $fetchdata['adult'];?></td>
                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$mainprice,$inrconvert);?></td>
                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$mainprice,$inrconvert);?></td>
               </tr>
            
             <?php } 
             
              else { ?>
                <tr> 
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Particuler</b></td>
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Quantity</b></td>
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Price</b></td>
                 <td style="border-bottom:1px solid #eee; width:25%"><b>Total</b></td>
              </tr>
              <tr>
                <td style="border-bottom: 1px dashed #eee; width:25%">Adults</td>
                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $fetchdata['adult'];?></td>
                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$mainprice,$inrconvert);?></td>
                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$totalAdult,$inrconvert);?></td>
               </tr>
              <?php } ?>
              
               <?php     
                $adulttotal=$adulttotal+str_replace(',', '', operaterpriceconvertor($fnsybol,$opcurrency,$totalAdult, $inrconvert));
                
                ?> 
     
     
       <!--Other Type Travellers Payment Details-->
       
            <?php
           if(!empty($jsonothercat)){
                    foreach($jsonothercat as $othercat){
                          $totalothcat= $othercat->price * $othercat->nopax;
                         if($othercat->nopax>0){?>
                                     <tr>
                                 <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $othercat->title;?></td>
                                 <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $othercat->nopax;?></td>
                                 <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($othercat->price,2);?></td>
                                 <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($othercat->price * $othercat->nopax,2);?></td>
                               </tr>
                               <?php
                              }	  
                               $othercattotal=$othercattotal+$totalothcat;		  
                               } 
                                }
       
          /* Transport Upgrade Payment Details */	
       
           $trasadonscnt=count($jsontrasadons);
             $initialtrans=0;
               for($i=0;$i<=$trasadonscnt; $i++){
                               $initialtrans=$initialtrans+ $jsontrasadons[$i]->nopax;
                           }
           if($initialtrans>0){ ?>
                          <tr>
                           <td colspan="4" style="width: 100%; color:#0056b3;border-bottom: 1px solid #0056b3;"><b>Transport Upgrade </b></td>
                         </tr>
                 <?php 
                    foreach($jsontrasadons as $trasadons){
                          $totaltrasadons=$trasadons->trroomprice * $trasadons->nopax;
                            if($trasadons->nopax>0){?>
                                         <tr>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $trasadons->trname;?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $trasadons->nopax;?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($trasadons->trroomprice,2);?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($trasadons->trroomprice * $trasadons->nopax,2);?></td>
                               </tr>
                             <?php	  
                              }  
                               $totaltrans=$totaltrans+$totaltrasadons;		  
                       
                           } 
                             }
                             
       
         /*  Upgrade Rooms Payment Details */
       
                  $roomcnt=count($jsonroomsaddon);
                     $totalroomcnt=0;
                       for($i=0;$i<=$roomcnt; $i++){
                           $totalroomcnt=$totalroomcnt+ $jsonroomsaddon[$i]->nopax;
                       }
                     
                      if($totalroomcnt>0){  ?>
                           <tr>
                              <td colspan="4" style="width: 100%; color:#0056b3;border-bottom: 1px solid #0056b3;"><b>Rooms Upgrade </b></td>
                         </tr>
                       <?php  
                      foreach($jsonroomsaddon as $roomsaddon){
                           if($roomsaddon->occuppancy=='Shared'){
                                 $roomprice=$roomsaddon->price;
                           }
                            else{
                                 $roomprice=$roomsaddon->privateprice;
                            }
                        if($roomsaddon->nopax>0){ 
                         $getroomtotal= $roomprice * $roomsaddon->nopax;?>  
                                 <tr>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $roomsaddon->name;?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $roomsaddon->nopax;?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($roomprice,2);?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($roomprice * $roomsaddon->nopax ,2);?></td>
                               </tr>
                             <?php		  
                             } 
                               $roomtotal=$roomtotal+$getroomtotal;		  
                           } 
                             }  
           
                
       /* Other Tour Addons Payment Details */
       
       $othcnt=count($jsonothaddons);
       $totalothcnt=0;
       for($i=0;$i<=$othcnt; $i++){
                   $totalothcnt=$totalothcnt+ $jsonothaddons[$i]->nopax;
               }
        if($totalothcnt>0){?>
               
                    <tr>
                 <td colspan="4" style="width: 100%; color:#0056b3;border-bottom: 1px solid #0056b3;"><b>Tour  Addons </b></td>
               </tr> 				      
             <?php	    
                   foreach($jsonothaddons as $othaddons){
                       $serviceid=$othaddons->serviceid;
                           if($othaddons->nopax>0) {
                               $addonlabel='Adult:';  
                            }
                          $getothtotal= $othaddons->perguest * $othaddons->nopax;
                       ?>
                             <tr>
                            <td style="border-bottom: 1px dashed #eee; width:25%"><b><?php echo $othaddons->servicename;?></b><br><?php echo $addonlabel;?></td>
                         <?php
                           if($othaddons->nopax>0) { ?>	
                               <td style="border-bottom: 1px dashed #eee; width:25%"><br><?php echo $othaddons->nopax;?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><br><?php echo  $opcurrency.number_format($othaddons->perguest,2);?></td>
                                <td style="border-bottom: 1px dashed #eee; width:25%"><br><?php echo  $opcurrency.number_format($othaddons->perguest * $othaddons->nopax,2);?></td>
                                 <?php
                                 }
                                ?>
                              </tr>
                             <?php  
                            $mainothtotal=$mainothtotal+$getothtotal;
                            $baskid=$fetchdata['baskid'];
                            $queryoth = $conn->query("select * from cartothsercat where serviceid='$serviceid' and baskid='$baskid'");
                            while($getservicemeta=$queryoth -> fetch_assoc()){
                                  $jsonotherservicemeta=json_decode($getservicemeta['otherservicemeta']);
                           
                                foreach($jsonotherservicemeta as $servicemeta){	
                                      $getservicetotal= $servicemeta->price * $servicemeta->nopax;
                                        if($servicemeta->nopax>0) {  ?>          
                                            <tr>
                                        <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $servicemeta->itemname;?></td>
                                        <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $servicemeta->nopax;?></td>
                                        <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($servicemeta->price,2);?></td>
                                        <td style="border-bottom: 1px dashed #eee; width:25%"><?php echo $opcurrency.number_format($servicemeta->price * $servicemeta->nopax,2) ;?></td>
                                       </tr>
                                    <?php 			  
                                 }
                                 $servicetotal=$servicetotal+$getservicetotal;
                                }
                            }	   
                          }	  
                         } 
                           
                             //	$PaidAmount= $adulttotal+$othercattotal+$totaltrans+$roomtotal+$mainothtotal+$servicetotal;
                             
                         ?>
                           <tr>
                       <td style="border-bottom: 1px dashed #eee"></td>
                       <td style="border-bottom: 1px dashed #eee"></td>
                       <td style="border-bottom: 1px dashed #eee;" ><b>Inclusive of Taxes</b></td>
                       <td style="border-bottom: 1px dashed #eee;"><b>&nbsp;</b></td>
               </tr>
                     <tr>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee;" ><b>Total Price</b></td>
                   <td style="border-bottom: 1px dashed #eee;"><b><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$totalprice,$inrconvert);?></b></td>
                 </tr>
               
                          <?php 
                if($promocode):
                    $promodiscount=$PaidAmount*$promovalue/100;
                   ?> 
                   
                    <tr>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee;" ><b>Discount(<?php echo $promocode;?>%)</td>
                   <td style="border-bottom: 1px dashed #eee; vertical-align: top;"><b><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$discountpromo,$inrconvert);?></b></td>
                 </tr>
                  <tr>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee;"><b>Paid Amount</td>
                   <td style="border-bottom: 1px dashed #eee; vertical-align: top;"><b><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$promototal,$inrconvert);?></b></td>
                 </tr>
                 <?php else:?>
                  <tr>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee"></td>
                   <td style="border-bottom: 1px dashed #eee;"><b>Paid Amount</td>
                   <td style="border-bottom: 1px dashed #eee; vertical-align: top;"><b><?php echo $opcurrency.operaterpriceconvertor($fnsybol,$opcurrency,$grandtotal,$inrconvert);?></b></td>
                 </tr>
                 <?php endif;?>
                   <tr>
                      <td>&nbsp;</td>
                   </tr>
                    <tr>
                     <td colspan="4">
                        <table style="color:#4a4a4a;line-height:30px;font-size:14px;font-family:Roboto,sans-serif;background:#fff" width="100%" cellspacing="0" cellpadding="0">
                       <tbody>
                       <tr>
                       <td colspan="2" align="center" style="padding-top: 14px">
                             <?php
                              if($fetchdata['bookedstatus']=='Pending'){?>
                                   <a href="javascript:void(0);"  class="acceptbook" data-inrconvert="<?php echo $inrconvert;?>" data-opemail="<?php echo $opemail;?>"  data-orderid="<?php echo $orderid;?>" data-oid="<?php echo $oid;?>" data-action="1" style="padding: 0 15px;text-decoration: none; color:#fff;background:#148914;background: #0056b3; display: inline-block; max-width: 200px;font-weight: bold;font-size: 18px;border-radius: 3px;line-height: 46px;">Accept Booking</a> 
                                      <a  href="javascript:void(0);"  class="acceptbook" data-inrconvert="<?php echo $inrconvert;?>" data-opemail="<?php echo $opemail;?>"  data-orderid="<?php echo $orderid;?>" data-oid="<?php echo $oid;?>" data-action="0" style="padding: 0 15px;text-decoration: none; color:#fff;background:#148914;background: #0056b3; display: inline-block; max-width: 200px;font-weight: bold;font-size: 18px;border-radius: 3px;line-height: 46px;">Cancel Booking</a></td>
                                     <?php
                                               }
                                            ?>
                             </tr>
                       </tbody>
                           </table>
                         </td>
                   </tr>					 
                 </table>
               <div class="viewdata"></div>
                 <script>
                     /* Operator Accept/Cancel Booking */

                       jQuery(".acceptbook").click(function () {
                             var orderid = jQuery(this).data("orderid");
                             var bookstatus = jQuery(this).data("action");
                             var oid = jQuery(this).data("oid");
                             var opemail = jQuery(this).data("opemail");
                             var inrconvert = jQuery(this).data("inrconvert");
                             var actiontype="Yes";
                             $.ajax({
                                 type: 'POST',
                                 url: AjaxUrl,
                                 data: {orderid:orderid,bookstatus:bookstatus,actiontype:actiontype,oid:oid,opemail:opemail,inrconvert:inrconvert}, // getting filed value in serialize form
                                 success: function(data){
                                      jQuery('.viewdata').html(data);
                                    //  window.location.href = "https://www.adventurerepubliq.com/tours-booking/";
                                       
                                }
                                
                             });
                         });
                 </script>
<?php  
}


/* Currecny Price Convetor */

function operaterpriceconvertor($savedVal, $opCrVal, $PriceVal,$inrconvert)
{
   $PriceVal=str_replace( ',', '', $PriceVal);
   if($opCrVal=='₹' &&  $savedVal=='USD'){
          $ConvertPrice=   $PriceVal * $inrconvert;
      }
      
      if($opCrVal=='$' &&  $savedVal=='USD'){
          $ConvertPrice=   $PriceVal;
      }
      
       if($opCrVal=='₹' &&  $savedVal=='INR'){
          $ConvertPrice=  $PriceVal;
      }
      
       if($opCrVal=='$' &&  $savedVal=='INR'){
          $ConvertPrice=   $PriceVal / $inrconvert;
      }
      
    return number_format($ConvertPrice,2);
}

function priceConvertor($savedVal,$opCrVal, $PriceVal,$inrconvert)
{
    if($opCrVal=='$' &&  $savedVal=='INR'){
          $ConvertPrice=   $PriceVal * $inrconvert;
      }
       if($opCrVal=='$' &&  $savedVal=='USD'){
          $ConvertPrice=   $PriceVal;
      }
      
       if($opCrVal=='₹' &&  $savedVal=='INR'){
          $ConvertPrice=  $PriceVal;
      }
       if($opCrVal=='₹' &&  $savedVal=='USD'){
          $ConvertPrice=   $PriceVal / $inrconvert;
      }
      
      
   
      
    return number_format($ConvertPrice,2);
}

/* Accept/Cancel Booking */

if (isset($_REQUEST['actiontype']) && $_REQUEST['actiontype'] == 'Yes') {
    
     global $wpdb;
     include('operator-confirm-booking.php');
     if($bookstatus>0){
      
       //$conn->query("UPDATE cartSession  SET  bookedstatus='Confirmed' WHERE orderid= '$orderid'");
        $mailmsg="Your booking has been confirmed.";
       
        /* Send Email To Client */
           
        $to = $customer_email;
        $subject="Booking Confirmed";
        $header = "FROM: Adventure Republiq <".$opemail.">\r\n";
        $header .= "Cc:info@adventurerepubliq.com \r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-type: text/html\r\n";
        $retval = mail ($to,$subject,$message,$header);
        
     }
     else{
        $conn->query("UPDATE cartSession  SET  bookedstatus='Canceled' WHERE orderid= '$orderid'");  
     }

}
if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'sendchat') {
        $oid=$_REQUEST['oid'];
        $opemail=$_REQUEST['opemail'];
        $uemail=$_REQUEST['uemail'];
        $replymsg=$_REQUEST['replymsg'];
        $nowdate=date('d-m-Y h:i:s');
        $unixDate=strtotime($nowdate);
        $uid=$_REQUEST['uid'];
        $sql = "INSERT INTO chatbox (oid,uid,email,msg,unixtime,status,sendertype)  VALUES ('$oid', '$uid','$uemail','$replymsg','$unixDate','1','2')";
        $conn->query($sql);
        sleep(2);
        $query=$conn->query("select * from chatbox where oid='$oid' and email='$uemail' ");
         while($fetchchat=$query -> fetch_assoc()){
               if($fetchchat['sendertype']==1):
                   $typefrom="User";
               else:
                   $typefrom="You";
               endif;  
               if($fetchchat['sendertype']!=''){
                ?>     
            <div class="left-col"><b><?php echo $typefrom;?> :</b><?php echo  $fetchchat['msg'];?></div>
          <?php 
          }
         }
}
/* Open Chatsbox by Opertor */
if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'openchat') {
   $oid=$_REQUEST['oid'];
   $opemail=$_REQUEST['opemail'];
   $uemail=$_REQUEST['uemail'];
   $nowdate=date('d-m-Y h:i:s');
   $unixDate=strtotime($nowdate);
   $username=$_REQUEST['username'];
   $uid=$_REQUEST['uid'];
   $opboxid=$_REQUEST['opboxid'];    
   include('chatbox.php');

}

if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'chatnow') {
        $oid=$_REQUEST['oid'];
        $opemail=$_REQUEST['opemail'];
        $uemail=$_REQUEST['uemail'];
        $replymsg=$_REQUEST['replymsg'];
        $localdate= str_replace( ',', '', $_REQUEST['localdate']);;
        $convertlocdate = str_replace('/', '-', $localdate);
        $unixDate =strtotime($convertlocdate);
      
        $uid=$_REQUEST['uid'];
        if(!empty($replymsg)){
            $sql = "INSERT INTO chatbox (oid,uid,email,msg,unixtime,status,sendertype)  VALUES ('$oid', '$uid','$uemail','$replymsg','$unixDate','0','2')";
            $conn->query($sql);
            
        }
        include('chatbox.php');
    
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'checkseen') {

   $uemail=$_REQUEST['uemail'];
   $conn->query("UPDATE chatbox SET status='1' WHERE email= '$uemail'");

}

/* Add Primotions */ 

if (isset($_REQUEST['Action']) && $_REQUEST['Action'] == 'Promotions') {
    $prname=$conn -> real_escape_string($_REQUEST['prname']);
   
    $promstatus=$conn -> real_escape_string($_REQUEST['promstatus']);
    $valfrom=$conn -> real_escape_string($_REQUEST['valfrom']);
    $valto=$conn -> real_escape_string($_REQUEST['valto']);
    $descripition=$conn -> real_escape_string($_REQUEST['descripition']);
    $terms=$conn -> real_escape_string($_REQUEST['terms']);
    $valuetype=$conn -> real_escape_string($_REQUEST['valuetype']);
    $oid=$conn -> real_escape_string($_REQUEST['oid']);
    $prmtid=$oid."_".uniqid();
   
    $locdatevalfrom = str_replace('/', '-', $valfrom);
    $unixvalform =strtotime($locdatevalfrom);
    
    $locdatevalto = str_replace('/', '-', $valto);
    $unixvalto =strtotime($locdatevalto);
    $prcode = strtoupper(substr($prname, 0, 5)).$valuetype;
     
     $getData=$conn->query("select * from promotion where  prcode='$prcode'");
     $checknum= $getData->num_rows; 
     if($checknum==1){
          $result=0;
         
         
     }
     else{
          $result=1;
          $sql = "INSERT INTO promotion (prname,prcode,prmtid,oid,tid,prstatus,valfrom,valto,unixvalfrom,unixvalto,descripition,terms,valuetype) VALUES ('$prname','$prcode', '$prmtid', '$oid', '', '$promstatus', '$valfrom','$valto','$unixvalform','$unixvalto','$descripition','$terms','$valuetype')";
          $conn->query($sql);
     }
}

/* Open For Edit Primotions */ 
if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'editpromotions') {

    include('edit_promotions.php');

}

/* Assign Primotions */ 
if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'viewassign') {
    $pid=$conn -> real_escape_string($_REQUEST['id']);
    $oid=$conn -> real_escape_string($_REQUEST['oid']);
    include('assign_promo.php');

}
/* Update Primotions */ 

if (isset($_REQUEST['Action']) && $_REQUEST['Action'] == 'update_promotions') {
    $id=$conn -> real_escape_string($_REQUEST['id']);
    $prname=$conn -> real_escape_string($_REQUEST['prname']);
    $promstatus=$conn -> real_escape_string($_REQUEST['promstatus']);
    $valfrom=$conn -> real_escape_string($_REQUEST['valfrom']);
    $valto=$conn -> real_escape_string($_REQUEST['valto']);
    $descripition=$conn -> real_escape_string($_REQUEST['descripition']);
    $terms=$conn -> real_escape_string($_REQUEST['terms']);
    $valuetype=$conn -> real_escape_string($_REQUEST['valuetype']);
    $oid=$conn -> real_escape_string($_REQUEST['oid']);
    
    $checktype=$conn -> real_escape_string($_REQUEST['checktype']);
    $aboveprice=$conn -> real_escape_string($_REQUEST['aboveprice']);
    $belowprice=$conn -> real_escape_string($_REQUEST['belowprice']);


   
   /* From Promotion in Unix */

    $locdatevalfrom = str_replace('/', '-', $valfrom);
    $unixvalform =strtotime($locdatevalfrom);
    
    
    $locdatevalto = str_replace('/', '-', $valto);
    $unixvalto =strtotime($locdatevalto);
    $prcode = strtoupper(substr($prname, 0, 5)).$valuetype;
    
    $conn->query("UPDATE promotion SET  prname='$prname',prcode='$prcode', prstatus= '$promstatus', valfrom='$valfrom', valto='$valto', valuetype='$valuetype'
    ,unixvalfrom='$unixvalform', unixvalto='$unixvalto', descripition='$descripition',terms='$terms', checktype='$checktype', aboveprice='$aboveprice',belowprice='$belowprice' WHERE id= '$id'");  
 
     include('viewpromotions.php');
}

/* Update Primotions */

if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'delpromotion') {
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $id=$conn -> real_escape_string($_REQUEST['id']);
     $conn->query("DELETE FROM promotion WHERE id='$id'");
      $conn->query("DELETE FROM promotion WHERE id='$id'");
     include('viewpromotions.php');
}



/* Assign Primotions */ 

if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'assinpromo') {

   $arrayJson=array();
   $array=array();
   $arraynew=array();
   
   $oid=$conn -> real_escape_string($_REQUEST['oid']);
   $pid=$conn -> real_escape_string($_REQUEST['pid']);
   $tid=$conn -> real_escape_string($_REQUEST['sentid']);
   $checktid=$conn -> real_escape_string($_REQUEST['checktid']);
   $locid=$conn -> real_escape_string($_REQUEST['locid']);
   
   
   $arrayJson[$tid]['tid'] = $tid;
   $encodeJson= json_encode($arrayJson);

   $getData=$conn->query("select * from assign_promotions where oid='$oid' and  pid='$pid'");
   $checknum= $getData->num_rows;

   if($checknum==0){
       $sql = $conn->query("INSERT INTO assign_promotions (tids,pid,oid) VALUES ('$encodeJson', '$pid','$oid')");
   }
   else{
           $newoldjson=array();
           $fetchdata=$getData -> fetch_assoc();
           if($fetchdata['tids']=='null'){
                  $encodeJson= json_encode($arrayJson);
                  $conn->query("UPDATE assign_promotions  SET  tids='$encodeJson' WHERE pid= '$pid'");
            }
           else{
                $oldjson=json_decode($fetchdata['tids'], true);
                 if($checktid==1){
                    $decodempdata=json_decode($fetchdata['tids'], true);
                     $arr_index = array();
                     foreach ($decodempdata as $key => $value) {
                             if ($key == $locid) {
                                $arr_index[] = $key;
                           }
                       }
                        foreach ($arr_index as $i) {
                           unset($decodempdata[$i]);
                           
                       }
                       $decodempdata = array_values($decodempdata);
                       $mergejson= json_encode($decodempdata);
                       $conn->query("UPDATE assign_promotions  SET  tids='$mergejson' WHERE pid= '$pid'");
               }
               else{
               $newjson=array_merge($arrayJson,$oldjson);
               $combinearray=array_merge($arraynew,$array);
               $mergejson=json_encode($newjson);
               $conn->query("UPDATE assign_promotions  SET  tids='$mergejson' WHERE pid= '$pid'");
               }
           }
           
       
     }
     include('assigned_tour_promotions.php');

}   

if (isset($_REQUEST['itnr']) && $_REQUEST['itnr'] === 'yes') {
     $duration=$conn -> real_escape_string($_REQUEST['duration']);
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $custId=$conn -> real_escape_string($_REQUEST['custid']);
     $query = $conn->query("SELECT *  from customize_tour_itinerary where custId='$custId' and oid='$oid'");
     $row_cnt = $query->num_rows;
     $fetchmeta=$query -> fetch_assoc();
   //   if($row_cnt>0){
   //         $decodeItiernary = json_decode($fetchmeta['tourinternary']);
   //         $totalItienery=count($decodeItiernary);
   //         if($duration>$totalItienery){
   //   }
   //   else{
          
   //   }
      for($i=1;$i<=$duration; $i++){
 ?>
<div class="form-group np">
   <div class="row">
         <div class="col-sm-8">
               <label for="name">Day  <?php echo $i;?></label>
                       <div class="form-group errodesp">
                           <input type="text" required name="gettitle[]" class="form-control required" placeholder="Day Plan" value="<?php echo  $itineraryData->gettitle;?>">
                       </div> 
                            <label for="name">Description :</label>
                             <textarea  style="resize: none;height: 250px;"required name="getdescription[]"  class="form-control required"><?php echo stripslashes($itineraryData->description);?></textarea>
            </div>
                         <div class="col-sm-4">
                                <?php if($j==1):?>
                                          <div class="e1dedb6f0 css-1k5xo9g e1uvdqdt0"></div>
                                             <div class="css-14bghfh e1u829440">
                                             <div class="css-1rskh6o e1u829441"></div>
                                             <div class="css-omv1s3 eubkn3g0">Explain what travelers can expect each day on tour.</div>
                                            </div>
                                   <?php endif;?>
                              </div>
                             </div>      
                           </div>          
                        
                    <script>
                         tinymce.init({
                           selector: "#decp<?php echo $i;?>",
                           menubar: false,
                           plugins: 'lists',
                           toolbar: "bold italic underline bullist",
                           resize: false,
                         });
                         
                  </script>
                  <?php 
                 
               }
}

/* Add  Customize Tours Data */ 

if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'add_customize_tour') {	



     $tourname=$conn -> real_escape_string($_REQUEST['tourname']);
     $duration=$conn -> real_escape_string($_REQUEST['duration']);
     $content=$conn -> real_escape_string($_REQUEST['content']);
     $custId=$conn -> real_escape_string($_REQUEST['custId']);
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $duration=$conn -> real_escape_string($_REQUEST['duration']);
     function create_slug($string){
          $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
          return $slug;
     }
     $query = $conn->query("SELECT *  from customize_tour_itinerary where custId='$custId' and oid='$oid'");
     $row_cnt = $query->num_rows;
     $fetchmeta=$query -> fetch_assoc(); 
     $tourslug=strtolower(create_slug($tourname));
     
   
      /* Add Json Days Itinerary */
       
     $gettitle=$_REQUEST['gettitle'];
     $description=$_REQUEST['getdescription'];
   
     
     $oldItinerary  = $fetchmeta['tourinternary'];
     $newItinerary = array();
     $countData = count($gettitle);
    
      for ($j = 0; $j < $countData; $j++ ) {
         if ( $gettitle[$j] != '' ) :
              $newItinerary[$j]['gettitle']  = $gettitle[$j];
              $newItinerary[$j]['description'] =$_REQUEST['getdescription'][$j];
         endif;
      }

     $converitjson=$conn -> real_escape_string(json_encode($newItinerary));  
      if($oldItinerary!=$converitjson){
     
          $jsondata=$converitjson;
      }
      else{
           $jsondata=$oldItinerary;
      }

     if($row_cnt>0){
          $conn->query("UPDATE customize_tour_itinerary SET  tourname='$tourname', tourslug='$tourslug',tourduration='$duration',tourdetails='$content', tourinternary='$jsondata' WHERE custId='$custId' and oid='$oid'");
     }
     else{
         $conn->query("INSERT INTO customize_tour_itinerary(custid,oid,tourname,tourslug,tourduration,tourdetails,tourinternary)
          VALUES ('$custId','$oid','$tourname','$tourslug','$duration','$content','$jsondata')");
     }
     
  
}


/* Assign Primotions */ 
if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'add_customize_tour_price') {	

     $custId=$conn -> real_escape_string($_REQUEST['custId']);
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tourstart=$conn -> real_escape_string($_REQUEST['tourstart']);
     $tourend=$conn -> real_escape_string($_REQUEST['tourend']);
     $tourprice=$conn -> real_escape_string($_REQUEST['tourprice']);
     $tour_includes=$conn -> real_escape_string($_REQUEST['tour_includes']);
     $tour_excludes=$conn -> real_escape_string($_REQUEST['tour_excludes']);
     $starttime=$conn -> real_escape_string($_REQUEST['starttime']);
     $conn->query("UPDATE customize_tour_itinerary SET  tourprice='$tourprice', tourstart='$tourstart',tourend='$tourend'
       ,tour_includes='$tour_includes', tour_excludes='$tour_excludes', starttime='$starttime'  WHERE custId='$custId' and oid='$oid'");

}

/* Assign Primotions */ 
if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'update_addinfo_price') {	

     $custId=$conn -> real_escape_string($_REQUEST['custId']);
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $covid_info=$conn -> real_escape_string($_REQUEST['covid_info']);
     $cancel_policy=$conn -> real_escape_string($_REQUEST['cancel_policy']);
     $conn->query("UPDATE customize_tour_itinerary SET cancel_policy='$cancel_policy', covid_info='$covid_info',status='1' WHERE custId='$custId' and oid='$oid'");


}
if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'delaction') {	
     $removeData=array();
     $delid=$_REQUEST['imgid'];
       $tourid=$_REQUEST['tid'];
       $formid=$_REQUEST['formid'];
   $selectSql = $conn->query("select * from cust_tour_images where tid = '$delid'");
 
    
      $getRow = $selectSql -> fetch_assoc();
     $updateArray=array();
     echo $getRow['tourimages'];
     $delfile='/wp-content/themes/adventure-republiq/operator/uploads/'.$_REQUEST['imagname'];
           $removeData[]=$_REQUEST['imagname'];
               $getimgdata=explode(",",$getRow['tourimages']);
                foreach($getimgdata as $ShowData)
                {
                       if(!in_array( $ShowData, $removeData)){
                          $updateArray[]=$ShowData;
                       }
                 }
                 $List = implode(',',$updateArray); 
                 
               
                 $conn->query("UPDATE cust_tour_images  SET  tourimages='$List' WHERE tid= '$delid'");
                 $get_photos=explode(",",$List);
                 unlink($delfile);
           ?>
          <ul> 
            <?php
                $i=0;
                    foreach($updateArray as $photos ){
                        if($photos) { ?>
                        <li><img src="/wp-content/themes/adventure-republiq/operator/uploads/<?php echo $photos;?>">
                           <a href="javascript:void(0);" data-count="<?php echo count($updateArray);?>" class="delgallery" data-tid="<?php echo $tourid ;?>" data-imgid="<?php echo $delid;?>" data-imagname="<?php echo $photos?>" data-formid="<?php echo $formid;?>">
                              <i class="fa fa-trash" aria-hidden="true"></i>
                            </a>
                         </li>
                        <?php
                        $i++;
                        }
                    }
                
                 ?>
                </ul>
                  <script type="text/javascript" src="https://dashboard.adventurerepubliq.com/wp-content/themes/adventure-republiq/operator/js/scripts.js"></script>
      <?php

   }
if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'cust_publish_tour') {		
     $oid=$conn -> real_escape_string($_REQUEST['oid']);
     $tourstart=$conn -> real_escape_string($_REQUEST['tourstart']);
     $tourend=$conn -> real_escape_string($_REQUEST['tourend']);
     $tourprice=$conn -> real_escape_string($_REQUEST['tourprice']);
   //  $conn->query("UPDATE customize_tour_itinerary SET status='1' WHERE custId='$custId' and oid='$oid'");
     
}


if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'update_activity') {
     $tid=$conn -> real_escape_string($_REQUEST['tid']);
     $getData=$conn->query("select * from tours  WHERE tid='$tid'");
     $fetchmeta=$getData -> fetch_assoc();


      /* Add Json tour activity */

      $oldactivity = $fetchmeta['touractivty'];
      $newactivity = array();
      $activity = $_REQUEST['activity'];
      $count = count($activity);
      for ($i = 0; $i < $count; $i++ ) {
         if ( $activity[$i] != '' ) :
         $newactivity[$i]['activity'] = stripslashes($activity[$i]);
         endif;
      }
     
      $converjson=json_encode($newactivity);  
     
      if($oldactivity!=$converjson){
          $addjsondata=$converjson;
      }
      else{
           $addjsondata=$oldactivity;
      }

        $sql = "UPDATE tours SET   touractivty='$addjsondata'  WHERE tid='$tid'";
        $conn->query($sql);
   
}

if (isset($_REQUEST['Action']) && $_REQUEST['Action'] === 'pdfaction') {
 $slug = $_REQUEST['tourslug'] ?? ''; // fallback to empty string if not set
 echo "slug";
 include('print_brocuher.php');
}

$conn->close();
?>







 
