<?php
$roomdata=$conn->query("select * from tours_price_data where oid='$user_id' and  tid='$tourid'");
$fetchdetails=$roomdata -> fetch_assoc();

$grpQuery=$conn->query("select * from group_price_data where tid='$tid'");
$fetchPrCount=$grpQuery->num_rows;

$queryCalender=$conn->query("select * from tour_day_price_calender where oid='$oid' and  tid='$tid'");
$checkCountCalender= $queryCalender->num_rows;
$fetchCalenderData=$queryCalender -> fetch_assoc();
     

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

     
      $oid=$conn -> real_escape_string($_REQUEST['oid']);
      $tid=$conn -> real_escape_string($_REQUEST['tid']);
      $operating_type=$conn -> real_escape_string($_REQUEST['operating_type']?? '');
      $howman_private=$conn -> real_escape_string($_REQUEST['howman_private']?? '');
      $min_private_booking=$conn -> real_escape_string($_REQUEST['min_private_booking']?? '');
      
      
      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';
      }

      $singleprice=$_REQUEST['singleprice'];
      $enablemulti=$_REQUEST['enablemulti'];
      
      $tourdates=$_REQUEST['tourdates'];
      $seats=$_REQUEST['seats'];
      $custcurrency=$_REQUEST['custcurrency'];  
      $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] != '' ) :
                $newPriceOpt[$i]['perpeson'] = stripslashes($mulperson[$i]);
                $newPriceOpt[$i]['price'] = stripslashes($price[$i]);
                  endif;
          }    
            if ( !empty( $newPriceOpt ) && $newPriceOpt != $oldtPriceOpt ){
                     $jsonmultiprice=   $conn -> real_escape_string(json_encode($newPriceOpt));
                 
          }
            elseif ( empty($newPriceOpt) && $oldtPriceOpt ){
                     $jsonmultiprice=$conn -> real_escape_string(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=  $conn -> real_escape_string(json_encode($newPriceCat));
                 
          }
            elseif ( empty($newPriceCat) && $oldPriceCat ){
                     $jsonPriceCat=  $conn -> real_escape_string(json_encode($oldPriceCat));
                     
             }
    
       $sqlopdt = "UPDATE tours_price_data  SET 
                    tourdates='$tourdates',
                    tourtime='$jsontimes',
                    seats='$seats',
                    tourprice='$singleprice',
                    priceoption='$jsonmultiprice',
                    multiprice='$enablemulti',
                    otherpricecat='$jsonPriceCat',
                    custcurrency='$custcurrency',
                    min_private_booking='$min_private_booking',   
                    howman_private='$howman_private', 
                   `$operating_type_label` = '$operating_type'
                    WHERE oid='$oid' and  tid='$tid'";
                    
         $conn->query($sqlopdt);
                
            $getPrice=$conn->query("select * from group_price_data WHERE  tid='$tid'");
            $fetchPriceData=$getPrice -> fetch_assoc();
            $priceMeta=$fetchPriceData['price_meta'];
            $getData=$conn->query("select * from group_price_data_active WHERE  tid='$tid'");
            $checknum= $getData->num_rows;
            if($checknum>0)
            {
               // echo  "UPDATE group_price_data_active  SET price_meta= '$priceMeta'  WHERE  tid='$tid'";
                  $conn->query( "UPDATE group_price_data_active  SET price_meta= '$priceMeta'  WHERE  tid='$tid'");
            }
            else
            {
               //  echo  "INSERT INTO group_price_data_active (tid,price_meta,status) VALUES ('$tid','$priceMeta',1)";
                 $conn->query("INSERT INTO group_price_data_active (tid,price_meta,status) VALUES ('$tid','$priceMeta',1)");
               
               
                           
            }   
         ?>
          <script>
         window.location.href = "<?php echo $url;?>/#nav-pricing";
         </script>
<?php         
}
if($fetchdetails['seats']==0 || $fetchdetails['tourprice']==0 )
{
    $fetchdetails['seats']='';
    $fetchdetails['tourprice']='';
    
}


if($fetchdetails['mindaysinst']==0  )
{

    $fetchdetails['mindaysinst']='';
   
   
}
if($fetchdetails['min_private_booking']==0 )
{

    $fetchdetails['min_private_booking']='';
   
}
if($fetchdetails['days_change_policy']==0 )
{
 
  
    $fetchdetails['days_change_policy']='';
    $fetchdetails['pay_change_policy']='';
    
}
// if($fetchdetails['fromage']==0 || $fetchdetails['endage']==0 )
// {

//      $fetchdetails['fromage']='';
//      $fetchdetails['endage']='';
     
// }
if( $fetchdetails['trcancel_days']==0 )
{
     $fetchdetails['trcancel_days']='';
}
if( $fetchdetails['howman_private']==0 )
{
     $fetchdetails['howman_private']='';
}
$GetDates = explode(',', $fetchdetails['tourdates']);
foreach($GetDates as $GetDate){ 
    
}
 $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);

?>
<script>
      function formatDate(odate) {
       var date = odate.split(/\//);
       var newDate = date[1] + '/' + date[0] + '/' + date[2];
       var returndate = new Date(newDate);
       return returndate;
   }
   jQuery(document).ready(function(){
      <?php if($fetchdetails['tourdates']){
          ?>
           var date = new Date();
            date.setDate(date.getDate());
            var datePicker=jQuery('#wp-custom-multiple-dates');
            datePicker.datepicker({language : "en",  inline: true, minDate: new Date(),toggleSelected: true});
        <?php
          foreach($GetDates as $GetDate){ ?>
          var selDate=formatDate('<?php echo $GetDate;?>');
                datePicker.data('datepicker').selectDate(selDate);
          <?php
              }
             }
         ?>
       jQuery(".monthselect").on('click', function(){
        var i;
        var days=document.getElementById('daysmonths').value;
        var monthview=document.getElementById('monthview').value;
        var yearview=document.getElementById('yearview').value;
        var date = new Date();
        date.setDate(date.getDate());
        var datePicker=jQuery('#wp-custom-multiple-dates');
        datePicker.datepicker({language : "en",  inline: true, minDate: new Date() ,toggleSelected: true});
          for (var i =1; i <= days; i++) {
              var selDate=formatDate(i+'/'+monthview+'/'+yearview);
                datePicker.data('datepicker').selectDate(selDate);
               }
        });
     });
</script>

<div class="container">
 <div class="row">
           <div class="col-sm-12 formbg"> 
               <div id="response"></div>
               <form id="PriceDetails" data-tid="<?php echo $_REQUEST['tourid'];?>" data-thistour="<?php echo $_REQUEST['thistrtype'];?>">
              <h4 class="avail showpicker" data-toggle="modal" data-target="#myModal"> Set Dates & Prices. </h4>
                        <div class="form-group tableoverflow">
                            <div class="reloadCalender">
                          <table class="table">
                               <tbody>
                                    <tr class="custom">
                                          <th scope="col">Sr. no</th>
                                          <th scope="col">Date</th>
                                          <th scope="col">Total Seats</th>
                                          <th scope="col">Booked Seats</th>
                                          <th scope="col">Available Seats</th>
                                          <th scope="col">Price</th>
                                         <th scope="col">Add/Edit Day Price</th>
                                     </tr>
                                     <?php
                                     $i=1;
                                      $queryCalender=$conn->query("select * from tour_day_price_calender where oid='$oid' and  tid='$tid'");
                                      $checkCountCalender= $queryCalender->num_rows;
                                      $fetchCalenderData=$queryCalender -> fetch_assoc();

                                      /* Build map of per-day overrides: daypricedate ('d/m/Y') => ['price'=>..., 'seats'=>...] */
                                      $dayPriceMap = array();
                                      $queryCalenderAll = $conn->query("select daypricedate, price, seats from tour_day_price_calender where oid='$oid' and tid='$tid'");
                                      if ($queryCalenderAll && $queryCalenderAll->num_rows > 0) {
                                          while ($rowCal = $queryCalenderAll->fetch_assoc()) {
                                              $dayPriceMap[$rowCal['daypricedate']] = array(
                                                  'price' => $rowCal['price'],
                                                  'seats' => $rowCal['seats'],
                                              );
                                          }
                                      }

                                      /* Booked seats per date from bookings.totaladult.
                                         travel_start_date is stored as "11 Aug 2026" — STR_TO_DATE parses that
                                         with '%d %b %Y' and DATE_FORMAT re-emits it as '2026-08-11' so the map
                                         key matches what the row loop below computes via date('Y-m-d', ...). */
                                      $bookingTourId = !empty($tid) ? $tid : ($_REQUEST['tourid'] ?? '');
                                      $bookingTourId = $conn->real_escape_string($bookingTourId);
                                      $bookedMap = array();
                                      $bookedQ = $conn->query(
                                          "SELECT DATE_FORMAT(STR_TO_DATE(travel_start_date, '%d %b %Y'), '%Y-%m-%d') AS bkey,
                                                  SUM(totaladult) AS booked
                                             FROM bookings
                                            WHERE tour_id = '$bookingTourId'
                                              AND travel_start_date IS NOT NULL
                                              AND travel_start_date <> ''
                                            GROUP BY bkey"
                                      );
                                      if ($bookedQ) {
                                          while ($bRow = $bookedQ->fetch_assoc()) {
                                              if (!empty($bRow['bkey'])) {
                                                  $bookedMap[$bRow['bkey']] = (int)$bRow['booked'];
                                              }
                                          }
                                      }

                                     $UpdateValue=array();
                                     foreach($date as $compareDate)
                                        {
                                          $unixCompareDate=strtotime($compareDate);
                                           if($unixCompareDate>=$unixCrDate)
                                            {
                                                $UpdateValue[]=date('d-m-Y', $unixCompareDate);
                                                $dayPriceDate=date('d/m/Y', $unixCompareDate);
                                                $defaultPrice = $fetchdetails['tourprice'];
                                                $defaultSeats = $fetchdetails['seats'];
                                                $overrideRow  = isset($dayPriceMap[$dayPriceDate]) ? $dayPriceMap[$dayPriceDate] : null;
                                                $hasPriceOverride = $overrideRow
                                                    && $overrideRow['price'] !== null && $overrideRow['price'] !== ''
                                                    && (float)$overrideRow['price'] != (float)$defaultPrice;
                                                $hasSeatsOverride = $overrideRow
                                                    && $overrideRow['seats'] !== null && $overrideRow['seats'] !== ''
                                                    && (int)$overrideRow['seats'] != (int)$defaultSeats;
                                                $hasDayOverride = $hasPriceOverride || $hasSeatsOverride;
                                            ?>
                                                <?php
                                                    $capacityVal  = $hasSeatsOverride ? (int)$overrideRow['seats'] : (int)$defaultSeats;
                                                    $bookedKey    = date('Y-m-d', $unixCompareDate);
                                                    $bookedVal    = isset($bookedMap[$bookedKey]) ? (int)$bookedMap[$bookedKey] : 0;
                                                    $availableVal = max(0, $capacityVal - $bookedVal);
                                                    $isSoldOut    = ($capacityVal > 0 && $availableVal === 0);
                                                    $rowClasses   = array();
                                                    if ($hasDayOverride) { $rowClasses[] = 'hasDayPrice'; }
                                                    if ($isSoldOut)      { $rowClasses[] = 'soldOut'; }
                                                    $rowStyle     = $isSoldOut ? ' style="background:#a12622;color:#fff;font-weight:bold;"' : '';
                                                    $rowClassAttr = !empty($rowClasses) ? ' class="' . implode(' ', $rowClasses) . '"' : '';
                                                ?>
                                                <tr<?php echo $rowClassAttr . $rowStyle; ?>>
                                                   <td><?php echo $i;?></td>
                                                   <td><?php echo date('d-m-Y', $unixCompareDate);?></td>
                                                   <td><?php echo $capacityVal; ?></td>
                                                   <td><?php echo $bookedVal; ?></td>
                                                   <td><?php echo $availableVal; ?></td>
                                                   <td>
                                                     <?php if ($hasPriceOverride): ?>
                                                         <?php echo $cust_currency . number_format((float)$overrideRow['price'], 2); ?>
                                                     <?php else: ?>
                                                       <?php echo $cust_currency . $defaultPrice; ?>
                                                     <?php endif; ?>
                                                   </td>
                                                   <td>
                                                     <?php if ($isSoldOut): ?>
                                                       <span style="color:#fff;pointer-events:none;opacity:0.7;font-weight:bold;">Add/Edit</span>
                                                     <?php else: ?>
                                                       <a herf="javascript:void()" data-pricedata="<?php echo $dayPriceDate;?>" data-toggle="modal" data-target="#caldayPrice" class="dayprice">Add/Edit</a>
                                                     <?php endif; ?>
                                                   </td>
                                                 </tr>
                                            <?php
                                            }
                                            $i++; 
                                          }
                                    ?>
                                 </tbody>
                            </table>
                         </div>    
                      </div>     
                                 
         <div class="insta-booking-block">                    
              <div class="form-group alcl">
                 <div class="row">
                     <div class="col-sm-2">
                       <label for="name" style="margin-bottom: 23px;">Allow Instant Booking <span class="mandtory">Required</span></label><br>
                          <input type="radio"  required name="instbooking" id="instayes" Value="1" <?php if($fetchdetails['instbooking']=='1'):?> checked <?php endif;?>> Yes 
                          <input type="radio" required name="instbooking" id="instano" Value="0"   <?php if($fetchdetails['instbooking']=='0'):?> checked <?php endif;?> style="margin-left: 20px;"> No
                      </div>  
                     <div class="col-sm-7 showbk" <?php if($fetchdetails['instbooking']):?> style="display:block; " <?php else:?> style="display:none; "<?php endif;?> >
                           <span class="plcd nobking" <?php if($fetchdetails['instbooking']=='1'):?> style="display:block; " <?php endif;?>>You will have to confirm your bookings manually on our booking conversation page or enable instant booking.</span>
                           <span class="plcd yesbking" <?php if($fetchdetails['instbooking']=='1'):?> style="display:block; " <?php endif;?>>All your bookings will be confirmed immediately upon the customer clicking "Book now".</span>
                     </div>
                </div>  
            </div>  
               <div class="form-group showinstY"  <?php if($fetchdetails['instbooking']=='1'):?> style="display:block" <?php else:?> style="display:none"<?php endif;?> >
                     <div class="row">
                      <div class="col-sm-3">
                         <label for="name">Minimum days before Departure </label>
                         <br>
                           <input type="number" name="mindaysinst" <?php if($fetchdetails['instbooking']==''):?> required <?php endif;?>  class="form-control drct2" min="0" value="<?php echo $fetchdetails['mindaysinst'];?>"><span class="drys">DAYS</span>
                       </div>
                   <div class="col-sm-7">
                             <div class="e1dedb6f0 css-1k5xo9g e1uvdqdt0"></div>
                                     <div class="css-14bghfh e1u829440">
                                     <div class="css-1rskh6o e1u829441"></div>
                                     <div class="css-omv1s3 eubkn3g0">Define how many days before the tour starts, a booking will confirm instantly</div>
                              </div>
                        </div>
                   </div>
                </div>
           </div>              
           <div class="insta-booking-block">
            <div class="form-group">
               <label for="name">Tour Cancellation Policy  <span class="mandtory">Required</span>
                <span class="plcd"></span>
                 <div class="row tpblock">
                        <div class="col-sm-6 ">
                          <label for="name">How many days in  advance traveler can cancel free of charge ?</label>
                              <input type="number" name="trcancel_days" required class="form-control required drct3" placeholder="No of Days" value="<?php echo $fetchdetails['trcancel_days'];?>">
                               <span class="drys">DAYS</span>
                           </div>
                        
                     <div class="col-sm-4">
                        <label for="name">Or traveler will pay Percentage</label>
                             <select  name="percentage"  required class="form-control required">
                                  <option selected="selected" value="">Select One</option>
                                  <option value="20" <?php if($fetchdetails['percentage']=='20'):?> selected="selected" <?php endif;?>>20% of the  tour amount</option>
                                  <option value="50" <?php if($fetchdetails['percentage']=='50'):?> selected="selected" <?php endif;?>>50% of the  tour amount</option>
                                  <option value="75" <?php if($fetchdetails['percentage']=='75'):?> selected="selected" <?php endif;?>>75% of the  tour amount</option>
                                  <option value="100" <?php if($fetchdetails['percentage']=='100'):?> selected="selected" <?php endif;?>>100% of the  tour amount</option>
                             </select>
                     </div>
                        <div class="col-sm-4">
                          
                        </div>
                 </div>             
              </div>
              
              <div class="form-group">
                <label for="name">Covid/Other Cancellation and Refund Terms</label>
                <textarea name="cancellation" id="cancellation" class="form-control textarea">
<?php echo stripslashes($fetchdetails['cancellation'] ?? ''); ?>
</textarea>
                </div>
                </div>
                  <div class="insta-booking-block">  
               <div class="form-group alcl">
                   <div class="row">
                     <div class="col-sm-6">
                        <label for="name"  style="margin-bottom: 23px;">Tour Date Change Policy <span class="mandtory">Required</span><br>
                       <span class="subheading"> Do you offer flexible booking for this tour?</span></label><br> 
                           <input type="radio" name="change_policy" required class="required" id="flyes" Value="1" <?php if($fetchdetails['change_policy']=='1'):?> checked <?php endif;?>> Yes 
                           <input type="radio" name="change_policy"   required class="required" id="flno" Value="0" <?php if($fetchdetails['change_policy']=='0'):?> checked <?php endif;?> style="margin-left: 20px;"> No
                     </div>
                  
                 </div>
                </div>
           <div class="form-group showflY" <?php if($fetchdetails['change_policy']=='1'):?>  style="display:block" <?php else:?>  style="display:none" <?php endif;?>>
                   <div class="row">
                      <div class="col-sm-6">
                        <label for="name">How many days in advance traveler can change date free of charge ? </label>
                         <input type="number" name="days_change_policy" class="form-control thisrequre drct3" value="<?php echo $fetchdetails['days_change_policy'];?>">
                       <span class="drys">DAYS  </span>
                      </div>
                     <div class="col-sm-4" style="display:none">
                      <label for="name">Or traveler will pay for change date:</label>
                            <input type="number" name="pay_change_policy" class="form-control" value="0">
                     </div>
                         
                </div>    
             
           </div>
           </div>

            <div class="form-group">
               <label for="name">Allowed Age Range <span class="mandtory">Required</span> </label>
                <div class="row">
                       <div class="col-sm-2">
                           <input type="number" required name="fromage" class="form-control required" placeholder="From" value="<?php echo $fetchdetails['fromage'];?>">
                        </div>
                       <div class="col-sm-2">
                              <input type="number" required name="endage" class="form-control required" placeholder="To" value="<?php echo $fetchdetails['endage'];?>">
                       </div>
                       <div class="col-sm-6">
                                 <div class="e1dedb6f0 css-1k5xo9g e1uvdqdt0"></div>
                                 <div class="css-14bghfh e1u829440"  style="margin-top:0px !important">
                                 <div class="css-1rskh6o e1u829441"></div>
                                 <div class="css-omv1s3 eubkn3g0">People outside this age range won't be able to book this tour </div>
                             </div>
                          </div>
                   
                </div>    
              </div>
            
              <input type="hidden" name="oid" value="<?php echo get_current_user_id();?>">
              <input type="hidden" name="tid" value="<?php echo $tourid;?>">
              <input type="hidden" name="Action" value="PriceDetails">
       
              <button type="submit" class="btn btn-primary calvalidate">Save</button>
              </form>
         </div>
        
 </div>
</div>  

<div class="modal" id="caldayPrice">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Add/Edit Day Price</h4>
         <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
         <div class="row">
          <div class="col-sm-12">
             <?php include_once('calander-day-price.php');?>
            </div>
          </div>
      </div>
      </div>
    </div>
  </div>


<!-- The Modal -->
<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Tour Availability </h4>
         <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
         <div class="row">
          <div class="col-sm-12">
              <div id="seatresponse"></div>
         
            <form method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>">
                 <div class="form-group  checkcal">
                      <label for="name">Select Departures <span class="mandtory">Required</span></label>
                     
                      <span class="monthselect"><i class="fa fa-check-circle" aria-hidden="true"></i></span> 
                         <input type="hidden"  id="monthview"   value="<?php echo date("M");?>">
                         <input type="hidden"  id="daysmonths"  value="<?php echo date("t");?>">
                         <input type="hidden"  id="yearview"    value="<?php echo date("Y");?>">
                         <input type="hidden" class="required" name="tourdates" required data-multiple-dates="1000" data-multiple-dates-separator="," data-position="top left" data-language="en" 
                         id="wp-custom-multiple-dates">
                        
                   </div>
                    <div class="form-group">
                      <label for="name">Add Start Time <span class="mandtory">Required</span></label>
                      <div class="insta-booking-block">
                           <ul  class="table" id="time-repeatable">
                               <?php 
                                  $decodePrOpt=json_decode($fetchdetails['priceoption']);
                                  $decodetime=json_decode($fetchdetails['tourtime']);
                                  if($decodetime){
                                  foreach( $decodetime as $getStatTime ) {?>     
                                      <li>
                                           <input type="time" required name="starttime[]" class="form-control required" placeholder="Tour Start Time" value="<?php echo $getStatTime->starttime;?>">
                                      </li>
                                     <?php 
                                     } 
                                  }
                                  else
                                  {
                                ?> <li><input type="time" required name="starttime[]" class="form-control required" placeholder="Tour Start Time" value="<?php echo $fetchData['tourname'];?>">  </li>
                                <?php
                                  }
                                  ?>
                        
                              <li class="repeat-time-empty-row screen-reader-text" id="delt">
                                  <input type="time" name="starttime[]" class="form-control" placeholder="Tour Start Time" value="<?php echo $fetchData['tourname'];?>">
                                   <a href="#" class="opt-remove-row"><i class="fa fa-minus-circle" aria-hidden="true"></i></a>
                              </li>
                          </ul>
                      <a id="add-repeat-time" class="button addmorebt" href="#">Add another</a>
                    </div>
                   </div>
                    <?php
                       $private_tr_booking = $fetchdetails['private_tr_booking'];
                       $grouponly = $fetchdetails['grouponly'];
                       $bothgrpr = $fetchdetails['bothgrpr'];  
                     
                    ?>
                    <div class="form-group">
                        <div class="row">
                            <div class="col-sm-11">
                                <label for="name">Tour Operating Type <span class="mandtory">Required</span></label><br>
                                <label style="margin-right:20px;font-weight:normal;">
                                    <input type="radio" required name="operating_type" class="operatingTypeRadio" value="0" <?php if ($grouponly === '0'): ?>checked<?php endif; ?>>
                                    Group Tour Only
                                </label>
                                <label style="margin-right:20px;font-weight:normal;">
                                    <input type="radio" required name="operating_type" class="operatingTypeRadio" value="1" <?php if ($private_tr_booking === '1'): ?>checked<?php endif; ?>>
                                    Private Tour Only
                                </label>
                                <label style="font-weight:normal;">
                                    <input type="radio" required name="operating_type" class="operatingTypeRadio" value="2" <?php if ($bothgrpr === '2'): ?>checked<?php endif; ?>>
                                    Both Group and Private
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group operatingPrivateBlock">
                        <?php
                            // Private details visible when Private Only (private_tr_booking=1) or Both (bothgrpr=2) is saved.
                            $showPrivateDetails =
                                (string)($fetchdetails['private_tr_booking'] ?? '') === '1'
                                || (string)($fetchdetails['bothgrpr'] ?? '') === '2';
                        ?>
                        <div class="row privateDetailsBlock" style="margin-top:10px;<?php echo $showPrivateDetails ? 'display:flex;' : 'display:none;'; ?>">
                            <div class="col-sm-4">
                                <label for="name" style="font-size: 13px;">How many private tours can be booked in a day ?</label>
                                <input type="number" name="howman_private" value="<?php echo $fetchdetails['howman_private']; ?>" placeholder="" class="form-control" min="0" style="width:300px">
                            </div>
                            <div class="col-sm-4">
                                <label for="name">Minimum Private Tour Seats</label>
                                <input type="number" name="min_private_booking" value="<?php echo $fetchdetails['min_private_booking']; ?>" placeholder="Enter Seats" class="form-control" min="0" style="width:300px">
                            </div>
                            <div class="col-sm-4">
                                <div class="e1dedb6f0 css-1k5xo9g e1uvdqdt0"></div>
                                <div class="css-14bghfh e1u829440">
                                    <div class="css-1rskh6o e1u829441"></div>
                                    <div class="css-omv1s3 eubkn3g0">Minimum number of people needed, to book this tour as Private Tour</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <script>
                    (function(){
                        function syncOperatingType() {
                            var op = jQuery('.operatingTypeRadio:checked').val();
                            var $det = jQuery('.privateDetailsBlock');
                            if (op === '1' || op === '2') {
                                $det.css('display', 'flex');
                            } else {
                                $det.hide();
                            }
                        }
                        jQuery(document)
                            .off('change.optype')
                            .on('change.optype', '.operatingTypeRadio', syncOperatingType);
                        jQuery(function(){ syncOperatingType(); });
                    })();
                    </script>
                    <div class="form-group">
                       <div class="row">
                         <div class="col-sm-4">
                             <label for="name">Available Tour Seats <span class="mandtory">Required</span></label>
                            <input type="number" name="seats" id="seats" required value="<?php echo $fetchdetails['seats'];?>" data-tourid="<?php echo $_REQUEST['tourid'];?>" min="1" max="15" data-oid="<?php echo get_current_user_id();?>" class="form-control required numberclass" placeholder="No of Seats">
                         </div>
                           <div class="col-sm-7">
                               <div class="e1dedb6f0 css-1k5xo9g e1uvdqdt0"></div>
                                     <div class="css-14bghfh e1u829440">
                                     <div class="css-1rskh6o e1u829441"></div>
                                     <div class="css-omv1s3 eubkn3g0">How many number of people can join this tour?</div>
                                   </div>
                            </div>
                      </div>
                      </div>
                      <div class="form-group">
                          <div class="row">
                             <div class="col-sm-4">
                              <label for="name">Price Per Traveller <span class="mandtory">Required</span> </label><br clear="all">
                                  <span class="priceBox"><?php  get_currency_val($cust_currency) ;?></span>
                                  <input type="number" required  name="singleprice" class="form-control crbox required" id="singleprice" data-userid="<?php echo get_current_user_id();?>"  data-tourid="<?php echo $_REQUEST['tourid'];?>" placeholder="Add Price" value="<?php echo $fetchdetails['tourprice'];?>">
                             
                                </div>
                             <div class="col-sm-7">
                               <div class="e1dedb6f0 css-1k5xo9g e1uvdqdt0"></div>
                                     <div class="css-14bghfh e1u829440">
                                     <div class="css-1rskh6o e1u829441"></div>
                                     <div class="css-omv1s3 eubkn3g0">Tour price should be inclusive all taxes, Advenure Republiq Fees and according to the Lowest Price/<a href="https://dashboard.adventurerepubliq.com/best-price-guarantee">Best price</a> guranteed.</div>
                                   </div>
                            </div>
                           </div>
                         </div>  
                           
                       <div class="form-group">
                               <label for="name">Group Discount: Do you offer different or lower prices for different group sizes? <span class="mandtory">Required</span></label><br>
                               <input type="radio"  required class="pboxload" data-tourid="<?php echo $_REQUEST['tourid'];?>"  data-userid="<?php echo get_current_user_id();?>"   data-crval="<?php echo $cust_currency;?>" name="enablemulti" id="enableYes" Value="1" <?php if($fetchdetails['multiprice']==1):?> checked <?php endif;?> > Yes
                               <input type="radio" required  class="pboxload" data-tourid="<?php echo $_REQUEST['tourid'];?>" data-crval="<?php echo $cust_currency;?>"  name="enablemulti" id="enableNo"   value="0"  <?php if($fetchdetails['multiprice']==0 ):?> checked <?php endif;?>  style="margin-left: 20px;"> No

                        </div>
                        <script>
                        (function(){
                            function syncMulti() {
                                var v = jQuery('input[name="enablemulti"]:checked').val();
                                var $showthis = jQuery('.showthis');
                                // Only toggle real rows — skip the .multi-empty-row template used for cloning.
                                var $rows = jQuery('.showthis #multi-repeatable-optional-on tr').not('.multi-empty-row').not('.custom');
                                var $inputs = $rows.find('input[name="mulperson[]"], input[name="price[]"]');
                                var activeCountEl = document.getElementById('activeCount');
                                var activeCount = activeCountEl ? parseInt(activeCountEl.value, 10) || 0 : 0;
                                if (v === '1') {
                                    $showthis.show();
                                    $inputs.prop('required', true);
                                    if (activeCount === 0) {
                                        jQuery('.firstreq').prop('required', true);
                                    }
                                } else {
                                    $showthis.hide();
                                    $inputs.prop('required', false).removeAttr('required');
                                    if (activeCount === 0) {
                                        jQuery('.firstreq').prop('required', false);
                                    }
                                }
                            }
                            jQuery(document)
                                .off('change.enablemulti click.enablemulti')
                                .on('change.enablemulti click.enablemulti', 'input[name="enablemulti"]', syncMulti);
                            jQuery(function(){ syncMulti(); });
                        })();
                        </script>
                   <div class="form-group showthis" <?php if($fetchdetails['multiprice']==1):?> style="display:block"  <?php else:?> style="display:none" <?php endif;?>>
                     <duv class="row">
                         <div class="col-sm-7 PriceGroup">
                               <table id="multi-repeatable-optional-on" class="table" data-lastkey=""  data-tourid="<?php echo $_REQUEST['tourid'];?>">
                                  <tbody>
                                        <tr class="custom">
                                              <th scope="col">Add Group Size</th>
                                              <th scope="col">Price Per Traveler</th>
                                        </tr>
                                     <tr id="last" >
                                          <td>
                                          <?php
                                            $priceQuery=$conn->query("select * from group_price_data_active where tid='$tid'");
                                            $i=1;
                                            $fetchJson=$priceQuery -> fetch_assoc();
                                            $activeCount = 0;
                                            $getjson = [];
                                            
                                            // Run the query
                                            $priceQuery = $conn->query("SELECT * FROM your_table WHERE ...");
                                            
                                            if ($priceQuery) {
                                                $activeCount = $priceQuery->num_rows;
                                                $fetchJson = $priceQuery->fetch_assoc();
                                            
                                                if ($fetchJson && !empty($fetchJson['price_meta'])) {
                                                    $decoded = json_decode($fetchJson['price_meta'], true);
                                                    if (is_array($decoded)) {
                                                        $getjson = $decoded;
                                                    }
                                                }
                                            } else {
                                                error_log("MySQL Query Failed: " . $conn->error);
                                            }
                                                if($fetchdetails['seats']){?>
                                                   <span class="grpof">Group of </span> <input type="text" name="mulperson[]" placeholder="eg.1" 
                                                   <?php if($activeCount==0):?> required <?php endif;?>  class="firstreq grpoftext form-control showseats" data-tourid="<?php echo $_REQUEST['tourid'];?>" data-oid="<?php echo get_current_user_id();?>"  data-crval="<?php echo $cust_currency;?>">
                                                <?php } 
                                                  else {?>
                                                 <span class="grpof"> Group of </span> <input type="text" name="mulperson[]" <?php if(empty($getjson)):?> required <?php endif;?>  placeholder="eg.1"  class=" firstreq  grpoftext form-control showseats" data-tourid="<?php echo $_REQUEST['tourid'];?>"
                                                        data-oid="<?php echo get_current_user_id();?>">   
                                                <?php }?>
                                                 </td>
                                                 <td>
                                                  <span class="priceBox"><?php  get_currency_val($cust_currency) ;?></span>
                                                    <input type="number" <?php if($activeCount==0):?> required <?php endif;?>   name="price[]" id="multiprice" class="form-control thisprice crbox firstreq" placeholder="Add Price">
                                                   </td> 
                                                 <td class=icons>
                                                  <a href="#" class="addmulti bindclass"  data-tourid="<?php echo $_REQUEST['tourid'];?>"
                                                    data-oid="<?php echo get_current_user_id();?>"><i class="fa fa-plus" aria-hidden="true"></i></a> </td>
                                                 
                                       
                                    </tr>
                                     <tr class="multi-empty-row screen-reader-text" id="">
                                          <td>
                                            <span class="grpof"> Group of </span> 
                                            <input type="text" placeholder="eg.1" name="mulperson[]" class="form-control showseats grpoftext" 
                                            data-tourid="<?php echo $_REQUEST['tourid'];?>" data-oid="<?php echo get_current_user_id();?>">

                                            </td>
                                          <td style="width: 300px;"><span class="priceBox"><?php  get_currency_val($cust_currency) ;?></span> 
                                          <input type="number" name="price[]" id="multiprice" class="form-control thisprice crbox resetval" placeholder="Add Price"></td> 
                                          <td class=icons style="width: 61px;"><a href="#" class="addmulti bindclass"  data-tourid="<?php echo $_REQUEST['tourid'];?>" data-oid="<?php echo get_current_user_id();?>"><i class="fa fa-plus" aria-hidden="true"></i></a> 
                                            <a class=" multi-remove-row" href="#"><i class="fa fa-minus" aria-hidden="true"></i></a>
                                          </td>
                                         
                                    </tr>
                                    </tbody>
                                  </table>
                                  
                         
                                   <h6 class="prheading">Saved Tour Price </h6>
                                     <div class="priceboxSummery">
                                    <?php 
                                     $oid=get_current_user_id();
                                     echo ActivePriceTable($tid,$oid);
                                      ?>
                                       </div>  
                                  
                                 
                         </div>
                             <div class="col-sm-5">
                                  <h6 class="prheading">Price Summary</h6>
                                  <div class="pricebox">
                                    <?php
                                     $oid=get_current_user_id();
                                    //  echo showPriceTable($tid,$oid);?>
                                 </div>
                                 
                             </div>
                            <p><input type="hidden" name="oid" value="<?php echo get_current_user_id();?>">
                                   <input type="hidden" name="tid" value="<?php echo $tourid;?>">
                                   <input type="hidden" name="Action" value="multisubmit">      
                                </p>
                                   
                        </div> 
                    <div class="form-group">
                        <h4>Other Price Category<br>
                          <span class="plcd">Add price for: children, seniors, students etc.</span></h4>
                        <table id="repeatable-optional-on" class="table">
                          <tbody>
                           <tr class="custom">
                              <th scope="col">Title</th>
                              <th scope="col">Info</th>
                              <th scope="col">Price</th>
                              <th scope="col">&nbsp;</th>    
                             </tr>
                         
                             <?php
                             $decodePriceCat=json_decode($fetchdetails['otherpricecat']);
                            $k=1;
                             if ($decodePriceCat ) :
                            
                              foreach ( $decodePriceCat as $field ) {
                              ?>
                              <tr>
                                   <td><input type="text"  class="form-control"  placeholder="Title" name="TitleItem[]" value="<?php echo esc_attr( $field->title); ?>"/></td> 
                                   <td><input type="text" class="form-control"  placeholder="Age" name="OptionalAge[]" value="<?php echo esc_attr( $field->age); ?>"/></td>   
                                   <td><span class="priceBox"><?php  get_currency_val($cust_currency) ;?></span> 
                                   <input type="text" class="form-control crbox"  placeholder="Price" name="optprice[]" value="<?php echo esc_attr( $field->price); ?>"  /></td> 
                                  <?php
                                  if($k>1):?>  <td><a class="button opt-remove-row" href="#"><i class="fa fa-minus-circle" aria-hidden="true"></i></td><?php else:?> 
                                 <td><a class="button opt-remove-row" href="#"><i class="fa fa-minus-circle" aria-hidden="true"></i></td><?php endif;?> 
                                  
                            </tr>
                            <?php
                            $k++;
                            }
                            else :
                             ?>
                            <tr>
                                    <td><input type="text"  class="form-control" placeholder="Title" title="Title" name="TitleItem[]" /></td>
                                    <td><input type="text" class="form-control" placeholder="Age" title="Age" name="OptionalAge[]" /></td> 
                                    <td><span class="priceBox"><?php  get_currency_val($cust_currency) ;?></span> <input type="number" class="form-control crbox"  placeholder="Price" name="optprice[]" id="costprice" title="Price"/></td> 
                                     <td><a class="button opt-remove-row" href="#"><i class="fa fa-minus-circle" aria-hidden="true"></i></td>

                            </tr>
                            <?php endif; ?>
                          <!-- empty hidden one for jQuery -->
                             <tr class="opt-empty-row screen-reader-text">
                                    <td><input type="text" class="form-control" placeholder="Title" title="Title" name="TitleItem[]" /></td>
                                    <td><input type="text" class="form-control crbox" placeholder="Age" title="Age" name="OptionalAge[]" /></td> 
                                    <td><span class="priceBox"><?php  get_currency_val($cust_currency) ;?></span> <input type="number" class="form-control crbox"  placeholder="Price" name="optprice[]" id="costprice" title="Price"/></td> 
                                    <td><a class="button opt-remove-row" href="#"><i class="fa fa-minus-circle" aria-hidden="true"></i></td>

                            </tr>
                            
                          </tbody>
                        </table>
                        <p><a id="opt-add-row" class="button" href="#">Add another</a></p>
                      </div>
                        <input type="hidden" name="oid" value="<?php echo get_current_user_id();?>">
                        <input type="hidden" name="tid" value="<?php echo $tourid;?>">
                        <input type="hidden" id="lastkey">
                        <input type="hidden" id="lastprice">
                        <input type="hidden" id="nextkey">
                        <input type="hidden" name="trtpe" value="<?php echo $_REQUEST['thistrtype'];?>">
                        <input type="hidden" name="Action" value="updatePrice">
                        <input type="hidden" id="recheck" value="<?php echo $fetchPrCount;?>">
                        <input type="hidden" id="activeCount" value="<?php echo $activeCount;?>">
                        <input type="hidden"  name="custcurrency"  value="<?php group_price_currency($cust_currency) ;?>">
                        <button type="text"  class="btn btn-primary setcal ">Save</button>
                        <input type="hidden"  id="savedata">
                    </form>
               </div>
          </div>
      </div>
      </div>
    </div>
  </div>
<script>
    jQuery(function() {
     jQuery(".PriceGroup #multi-repeatable-optional-on").attr('data-oneprice', '<?php echo $fetchdetails['tourprice'];?>')
});
</script>