<?php
/**
 *  Template Name: Add Tours/Edit Tours
 *
 *  This page template has a sidebar built into it,
 *  and can be used as a home page, in which case the title will not show up.
 *
 */

// This fxn gets the header.php file and renders it
require_once dirname( __FILE__ ) . '/header.php';
if(current_user_can('administrator')):
  include_once('admin/view-operator-tour.php');
 // require_once dirname( __FILE__ ) . '/footer.php';
exit;
endif;
$url= $_SERVER['REQUEST_URI']; 
$tourid=$_REQUEST['tourid'];
$opname=$current_user->user_firstname;
$tourQuery=$conn->query("select * from tours where oid='$user_id' and tid='$tourid'");
$tourData=$tourQuery -> fetch_assoc();

$cust_currency=get_user_meta(get_current_user_id(),'cust_currency' ,true);
$tourImage=$conn->query("select * from tour_images where tid='$tourid' and  imgid=1");
$countData= $tourImage->num_rows;

$setImges = $tourImage->fetch_assoc();

$get_photos = [];
if (!empty($setImges) && !empty($setImges['tourimages'])) {
    $get_photos = explode(",", $setImges['tourimages']);
}

// ini_set('display_errors', 1); // Hide from user
// ini_set('log_errors', 1);

// error_reporting(E_ALL);
if($_REQUEST['Action']=='tourphotos'){ 

    $uploadDir =$_SERVER['DOCUMENT_ROOT']."/wp-content/themes/adventure-republiq/operator/uploads/"; 
        $fileName =$tourid.$_FILES['file']['name'];
        $uploadFilePath = $uploadDir.$fileName; 
   
   
    // Upload file to server 
   if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)){ 
    echo "yes";
    echo "select * from tour_images where oid='$user_id' and  tid='$tourid' and imgid= '1'";
        // Insert file information in the database 
          $getaddons=$conn->query("select * from tour_images where oid='$user_id' and  tid='$tourid' and imgid= '1'");
          $countData= $getaddons->num_rows;
          $fetchAddons=$getaddons -> fetch_assoc();
          if($countData>0)
           {
                echo "no";
                  $newtourimages = $fetchAddons['tourimages'].",".$fileName;
                  $sqlopdt = "UPDATE tour_images  SET 
                              tourimages='$newtourimages'
                              WHERE oid='$user_id' and  tid='$tourid' and imgid= '1'";
                              $conn->query($sqlopdt);
                                 exit;
           }
           else
           {
                 echo "yes";
                   $sql = "INSERT INTO tour_images (oid,tid,tourimages,imgid) VALUES ('$user_id','$tourid','$fileName','1')"; 
            
                   $conn->query($sql);
           }
    } 


} 

if($_REQUEST['Action']=='AccommodationPhoto'){ 
       $uploadDir =$_SERVER['DOCUMENT_ROOT']."/wp-content/themes/adventure-republiq/operator/uploads/"; 
        $fileName =$tourid.$_FILES['file']['name'];
        $uploadFilePath = $uploadDir.$fileName; 
       
      if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)){ 
        // Insert file information in the database 
          $getaddons=$conn->query("select * from tour_images where oid='$user_id' and  tid='$tourid' and imgid= '2'");
          $countData= $getaddons->num_rows;
          $fetchAddons=$getaddons -> fetch_assoc();
          if($countData>0)
           {
                  $newtourimages = $fetchAddons['tourimages'].",".$fileName;
                  $sqlopdt = "UPDATE tour_images  SET 
                              tourimages='$newtourimages'
                              WHERE oid='$user_id' and  tid='$tourid' and imgid= '2'";
                              $conn->query($sqlopdt);
           }
           else
           {
                   $sql = "INSERT INTO tour_images (oid,tid,tourimages,imgid) VALUES ('$user_id','$tourid','$fileName','2')"; 
                   $conn->query($sql);
           }
    }
}
 if($_REQUEST['Action']=='TrasportPhoto'){ 
       $uploadDir =$_SERVER['DOCUMENT_ROOT']."/wp-content/themes/adventure-republiq/operator/uploads/"; 
        $fileName =$tourid.$_FILES['file']['name'];
        $uploadFilePath = $uploadDir.$fileName; 
       
      if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)){ 
        // Insert file information in the database 
          $getaddons=$conn->query("select * from tour_images where oid='$user_id' and  tid='$tourid' and imgid= '3'");
          $countData= $getaddons->num_rows;
          $fetchAddons=$getaddons -> fetch_assoc();
          if($countData>0)
           {
                  $newtourimages = $fetchAddons['tourimages'].",".$fileName;
                  $sqlopdt = "UPDATE tour_images  SET 
                              tourimages='$newtourimages'
                              WHERE oid='$user_id' and  tid='$tourid' and imgid= '3'";
                              $conn->query($sqlopdt);
           }
           else
           {
                   $sql = "INSERT INTO tour_images (oid,tid,tourimages,imgid) VALUES ('$user_id','$tourid','$fileName','3')"; 
                   $conn->query($sql);
           }
    }
} 
 if($_REQUEST['Action']=='Accphotos' || $_REQUEST['Action']=='addontrasport'){ 
       $uploadDir =$_SERVER['DOCUMENT_ROOT']."/wp-content/themes/adventure-republiq/operator/uploads/"; 
        $imgId =$_REQUEST['imgId'][0];
        $fileName =$imgId."-".$_FILES['file']['name'];
        $uploadFilePath = $uploadDir.$fileName; 
  
     // Upload file to server 
 
      $getaddons=$conn->query("select * from tour_images where oid='$user_id' and  tid='$tourid' and imgid= '$imgId'");
      $countData= $getaddons->num_rows;
      $fetchAddons=$getaddons -> fetch_assoc();
      
     if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)){ 
          if($countData>0)
           {
                  $newtourimages = $fetchAddons['tourimages'].",".$fileName;
                  $sqlopdt = "UPDATE tour_images  SET 
                              tourimages='$newtourimages'
                              WHERE oid='$user_id' and  tid='$tourid' and imgid= '$imgId'";
                              $conn->query($sqlopdt);
           }
           else
           {
                   $sql = "INSERT INTO tour_images (oid,tid,tourimages,imgid) VALUES ('$user_id','$tourid','$fileName','$imgId')"; 
                   $conn->query($sql);
           }
        
         ?>
          <script>
              window.location.href = "https://dashboard.adventurerepubliq.com/".$url;
         </script>
         <?php
    } 
 } 
 
  if($_REQUEST['Action']=='Optionaladdons'){ 
       $uploadDir =$_SERVER['DOCUMENT_ROOT']."/wp-content/themes/adventure-republiq/operator/uploads/"; 
        $imgId =$_REQUEST['imgId'];
        $fileName =$imgId."-".$_FILES['file']['name'];
        $uploadFilePath = $uploadDir.$fileName; 
  
     // Upload file to server 
 
   if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)){ 
         $sql = "INSERT INTO tour_images (oid,tid,tourimages,imgtype) VALUES ('$user_id','$tourid','$fileName','2')"; 
         $insert = $conn->query($sql);
         ?>
          <script>
             window.location.href = "https://dashboard.adventurerepubliq.com/".$url;
         </script>
         <?php
    } 
 } 
 $tabInfotip="You have some required information missing in this tab";
if($request == 2){ 
  $filename = $target_dir.$_POST['name'];  
  unlink($filename); 
}
if($tourData['tourstatus']==0):
?>
    <style>
    .onoffswitch-inner:before {
          content: "Pause";
            padding-left: 8px;
            background-color: red;
            color: #FFFFFF;
        }
    .onoffswitch-inner:after {
            content: "Live";
          padding-right: 17px;
            background-color: green; color: #FFFFFF;
            text-align: right;
        }
</style>
<?php endif;
 if($fullaccess==1){?>
        <script>
        var count = $('nav sup:hidden').length;
        if(count==5){
             $('.onoffswitch').show();
             $('.pause').hide();
        }
  
        </script>
<?php }?>
<div class="container">
    <div class="row">
          <div class="col-sm-9">
          <h1 class="trheasd" id="trheasd"><?php echo stripslashes($tourData['tourname'] ?? ''); ?></h1>

            </div>
           <div class="col-sm-3">
                <div class="chtrstatus">
                  <strong>Tour status:</strong>
                  <?php 
                   if($fullaccess==-0 ){?> <div class="pause">Pause</div>
                  <?php }
                   elseif($fullaccess==1 &&  $tourData['tabstatus']==0){ ?> <div class="pause">Pause</div>
                  <?php } 
                  else {?>
                       <div class="onoffswitch">
                        <input type="checkbox" <?php if($tourData['tourstatus']==1):?> data-status="no" <?php else:?> data-status="1" <?php endif;?> name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" tabindex="0" data-tid="<?php echo $tourid;?>" data-trtype="<?php echo $_REQUEST['thistrtype'];?>" checked>
                            <label class="onoffswitch-label" for="myonoffswitch">
                                <span class="onoffswitch-inner"></span>
                                <span class="onoffswitch-switch" data-off="0"></span>
                            </label>
                        </div>
                        <?php }?>
                </div>    
               <a href="https://dashboard.adventurerepubliq.com/operator-dashboard/" class="backbtn">Back</a>
             </div>
     </div>

         <?php
          // Add Activity gate: tab stays disabled + shows required marker until
          // Tour Name, Introduction, Highlights are filled. For multi-day tours
          // (tourtype=1) also require at least one itinerary day; day tours
          // (tourtype=2) skip the itinerary check.
          $activityTabReady = true;
          $activityTabWhy   = '';
          if (trim(stripslashes($tourData['tourname'] ?? '')) === '') {
              $activityTabReady = false;
              $activityTabWhy   = 'Add a Tour Name in Details first.';
          }
          if ($activityTabReady && trim(strip_tags(stripslashes($tourData['content'] ?? ''))) === '') {
              $activityTabReady = false;
              $activityTabWhy   = 'Add a Tour Introduction in Details first.';
          }
          if ($activityTabReady && trim(strip_tags(stripslashes($tourData['highlights'] ?? ''))) === '') {
              $activityTabReady = false;
              $activityTabWhy   = 'Add Tour Highlights in Details first.';
          }
          $isMultiDay = ((int)($tourData['tourtype'] ?? 0) === 1) || ((int)($_REQUEST['thistrtype'] ?? 0) === 1);
          if ($activityTabReady && $isMultiDay) {
              $itinDecoded = null;
              $itinQ = $conn->query("SELECT itineraryData FROM tour_itinerary WHERE tid='" . intval($tourid) . "' LIMIT 1");
              if ($itinQ) {
                  $itinRow  = $itinQ->fetch_assoc();
                  $itinData = $itinRow['itineraryData'] ?? '';
                  if ($itinData !== '') { $itinDecoded = json_decode($itinData, true); }
              }
              if (!is_array($itinDecoded) || count($itinDecoded) === 0) {
                  $activityTabReady = false;
                  $activityTabWhy   = 'Add a Tour Itinerary in Itinerary tab first.';
              }
          }
          ?>
          <nav>
                 <div class="nav nav-tabs nav-fill" id="nav-tab" role="tablist">
                      <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Details <sup style="display:none" class="blinker"  data-toggle="tooltip" title="<?php echo $tabInfotip;?>">*</sup></a>
                      <a class="nav-item nav-link nav-profile-tab" id="nav-profile-tab"     data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false" data-oid="<?php echo $user_id;?>"  data-tid="<?php echo $tourid;?>">Itinerary <sup style="display:none"  class="blinker" data-toggle="tooltip" title="<?php echo $tabInfotip;?>">*</sup></a>
                        <?php if($user_id==770):?>
                      <?php if ($activityTabReady): ?>
                      <a class="nav-item nav-link" id="nav-activity-tab"    data-toggle="tab" href="#nav-activity" role="tab" aria-controls="nav-activity" aria-selected="false" data-tid="<?php echo $tourid;?>">Add Activity <sup style="display:none" class="blinker" data-toggle="tooltip" title="<?php echo $tabInfotip;?>">*</sup></a>
                      <?php else: ?>
                      <a class="nav-item nav-link disabled" id="nav-activity-tab" aria-disabled="true" role="tab" aria-controls="nav-activity" aria-selected="false" data-tid="<?php echo $tourid;?>" style="pointer-events:none; opacity:0.55; cursor:not-allowed;" data-toggle="tooltip" title="<?php echo htmlspecialchars($activityTabWhy, ENT_QUOTES);?>">Add Activity <sup class="blinker" style="display:inline-block" data-toggle="tooltip" title="<?php echo htmlspecialchars($activityTabWhy, ENT_QUOTES);?>">*</sup></a>
                      <?php endif; ?>
                      <?php endif;?>
                      <a class="nav-item nav-link" id="nav-included-tab"    data-toggle="tab" href="#nav-included" role="tab" aria-controls="nav-included" aria-selected="false"   data-tid="<?php echo $tourid;?>">Includes/Excludes <sup style="display:none" data-toggle="tooltip" title="<?php echo $tabInfotip;?>">*</sup></a>
                      <a class="nav-item nav-link" id="nav-photos-tab"      data-toggle="tab" href="#nav-photos" role="tab" aria-controls="nav-photos" aria-selected="false" data-tid="<?php echo $tourid;?>">Gallery <sup  class="blinker" <?php if(empty($setImges['tourimages'])):?> style="display:inline-block" <?php else:?>  style="display:none" <?php endif;?> data-toggle="tooltip" title="<?php echo $tabInfotip;?>">*</sup></a>
                      <a class="nav-item nav-link" id="nav-pricing-tab"     data-toggle="tab" href="#nav-pricing" role="tab" aria-controls="nav-pricing" aria-selected="false" data-tid="<?php echo $tourid;?>">Dates  & Prices <sup  class="blinker" style="display:none"  data-toggle="tooltip" title="<?php echo $tabInfotip;?>" >*</sup></a>
                      <a class="nav-item nav-link" id="nav-rooms-tab"       data-toggle="tab" href="#nav-rooms" role="tab" aria-controls="nav-rooms" aria-selected="false"> Addons & Info <?php if($tourData['tabstatus']==0 && $fullaccess==1):?><span  class="blinker" style="display:none" data-toggle="tooltip" title="Publish your tour"> * </span>  <?php endif;?></a>
                  
                  </div>
            </nav>
             <div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
                   <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
                        <?php require_once dirname( __FILE__ ) . '/operator-tours/tours-details.php';?>
                   </div>
                  <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
                          <?php require_once dirname( __FILE__ ) . '/operator-tours/itinerary.php';?>
                   </div>
                   <?php if($user_id==770):?>
                     <div class="tab-pane fade" id="nav-activity" role="tabpanel" aria-labelledby="nav-activity-tab">
                          <?php require_once dirname( __FILE__ ) . '/operator-tours/addactivity.php';?>
                     </div>
                   <?php endif;?>
                   <div class="tab-pane fade" id="nav-photos" role="tabpanel" aria-labelledby="nav-photos-tab">
                          <?php require_once dirname( __FILE__ ) . '/operator-tours/photos.php';?>
                   </div>
                   <div class="tab-pane fade" id="nav-included" role="tabpanel" aria-labelledby="nav-included-tab">
                           <?php 
                          
                           if($tourData['tourtype']==2 || $_REQUEST['thistrtype']==2){
                              require_once dirname( __FILE__ ) . '/operator-tours/day_included.php';
                            }
                            else{
                              require_once dirname( __FILE__ ) . '/operator-tours/included.php';
                               
                            }
                          
                          ?>
                   </div>
                   <div class="tab-pane fade" id="nav-pricing" role="tabpanel" aria-labelledby="nav-pricing-tab">
                          <?php require_once dirname( __FILE__ ) . '/operator-tours/price_included.php';?>
                   </div>
                    <div class="tab-pane fade" id="nav-rooms" role="tabpanel" aria-labelledby="nav-pricing-tab">
                          <?php require_once dirname( __FILE__ ) . '/operator-tours/rooms_addons.php';?>
                   </div>
              </div>  
      
  </div>


        
<?php
require_once dirname( __FILE__ ) . '/footer.php';
?>

