<?php
$opuserid=$_REQUEST['opuserid'];
$stidch=$_REQUEST['stidch'];
if($stidch) {
$status=$_REQUEST['status'];
$tabstatus=$_REQUEST['tabstatus'];


$conn->query("Update tours set tourstatus= '$status',
                       tabstatus='$tabstatus'  where tid='$stidch'");
}
if(empty($opuserid))
{
       $myquery="SELECT tours.tid,tours.oid, ,tours.tabstatus,tours.tourname, tours.duration, tours.tourslug,tours.tourtype,tours.tourstatus, 
                          tours_price_data.tourprice as price FROM tours, tours_price_data where tours.tid= tours_price_data.tid  and 
                          tours.oid= tours_price_data.oid order by tours.tid DESC ";
}
else
{
    if($opuserid!='All'){
        $myquery="SELECT tours.tid,tours.oid, tours.tabstatus, tours.tourname,tours.duration, tours.tourslug,tours.tourtype,tours.tourstatus, tours_price_data.tourprice as price
                      FROM tours, tours_price_data where tours.oid= '$opuserid' and  tours.tid= tours_price_data.tid order by tours.tid DESC ";
   
    }
    else
        {
        $myquery="SELECT tours.tid,tours.oid,tours.tabstatus, tours.tourname, tours.duration, tours.tourslug,tours.tourtype,tours.tourstatus, 
                          tours_price_data.tourprice as price FROM tours, tours_price_data where tours.tid= tours_price_data.tid  and 
                          tours.oid= tours_price_data.oid order by tours.tid DESC ";
        }
}
$tourQuery=$conn->query($myquery);
$numrows= $tourQuery->num_rows;
$like='a:1:{s:8:"operator";b:1;}';
$totalop=array();
$oprinactive=array();
$opactive=array();
$getopertuery=$conn->query("SELECT wpwr_users.ID  as userid, wpwr_users.user_nicename as fname FROM wpwr_users JOIN wpwr_usermeta ON wpwr_usermeta.user_id = wpwr_users.ID WHERE meta_value ='$like'"); 
while($fetchopid= $getopertuery -> fetch_assoc()){ 
     $totalop[]=$fetchopid['userid'];
     $fullaccess=get_user_meta($fetchopid['userid'],'fullaccess', true);
     if($fullaccess==0){
         //echo $fetchopid['userid']."-->".$fetchopid['fname']."-->".$fullaccess."<br>";
         $oprinactive[]=$fetchopid['userid'];
     }
     else{
         $opactive[]=$fetchopid['userid'];
     }
 }
$numoperator=count($totalop);
$countInq=$conn->query("select * from enquiryform where oid='$opuserid' and status='0'");
$totalEnq= $countInq->num_rows;

if($totalEnq>0):
$unread= '<sup class="unread">'.$totalEnq.' New Enquiry'.'</sup>';
endif;

$countRews=$conn->query("select * from reviews where oid='$opuserid' and  approve='1'");
$totalRvs= $countRews->num_rows;

if($totalRvs>0):
$unreadrws= '<sup class="unread">'.$totalRvs.' New Reviews'.'</sup>';
endif;


/* Count of Active Tours of */

$activeQuery=$conn->query("SELECT * from tours where tourstatus='1' order by id");
$totalActive= $activeQuery->num_rows;

/* Count of inActive Tours of */

$inActiveQuery=$conn->query("SELECT * from tours where tourstatus='0' order by id");
$totalinActive= $inActiveQuery->num_rows;

/* Count of all Tours from webscraptours */

$scrapToursQuery=$conn->query("SELECT * from webscraptours");
$totalScrapTours= $scrapToursQuery->num_rows;



?>
<style>
   table td {
      max-width: 200px;
}
/* Style for Select2 dropdown */
.select2-container--default .select2-selection--single {
    height: 38px;
    padding: 5px 10px;
    border: 1px solid #ced4da;
    border-radius: 4px;
    height: 37px !important;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 36px;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 28px;
    padding-left: 8px;
}

/* Make the dropdown wider */
.select2-container {
    width: 100% !important;
}
</style>
<!-- Add these in the <head> section of your HTML -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<div class="container optabs">
   <div class="row rowbrd">
         <div class="col-sm-4">
             <h3 class="head-sup-login" style="padding:0">
             Total Tours:<?php echo $numrows;?><br>
             Live Tours:<?php echo $totalActive;?><br>
             Inactive Tours:<?php echo $totalinActive + $totalScrapTours;?><br>
             Total Operator:<?php echo $numoperator;?><br>
             Full Access Operator:<?php echo count($opactive);?><br>
             <span style="color:red">Inactive Operator:<?php echo count($oprinactive);?></span><br>
          </h3>
        </div>
        <div class="col-sm-4">
    <div class="form-group">
        <label for="inactiveOperators">Select Inactive Operators: </label>
        <select class="form-control select2-search" id="inactiveOperators" name="opuserid">
            <option value="All">Select One</option> 
            <?php
            $userQuery = $conn->query("SELECT * FROM wpwr_users ORDER BY user_login ASC");
            while($inActiveUserShow = $userQuery->fetch_assoc()) {
                $user_meta = get_userdata($inActiveUserShow['ID']);
                $user_roles = $user_meta->roles;
                $fullaccess = get_user_meta($inActiveUserShow['ID'], 'fullaccess', true);
                if (in_array('operator', $user_roles, true) && $fullaccess == 0) { 
            ?>
                <option value="<?php echo $inActiveUserShow['ID']; ?>" <?php if($inActiveUserShow['ID'] == $opuserid) echo 'selected="selected"'; ?>>
                    <?php echo $inActiveUserShow['user_login']; ?>
                </option>
            <?php
                }
            }
            ?>
        </select>
    </div> 
    </div>
          <div class="col-sm-4">
    <div class="form-group">
        <label for="activeOperators">Select Active Operators: </label>
        <select class="form-control select2-search" id="activeOperators" name="opuserid">
            <option value="All">Select One</option> 
            <?php
            $userQuery = $conn->query("SELECT * FROM wpwr_users ORDER BY user_login ASC");
            while($userShow = $userQuery->fetch_assoc()) {
                $user_meta = get_userdata($userShow['ID']);
                $user_roles = $user_meta->roles;
                $fullaccess = get_user_meta($userShow['ID'], 'fullaccess', true);
                if (in_array('operator', $user_roles, true) && $fullaccess == 1) { 
            ?>
                <option value="<?php echo $userShow['ID']; ?>">
                    <?php echo $userShow['user_login']; ?>
                </option>
            <?php
                }
            }
            ?>
        </select>
    </div> 
</div>
        </div>

<?php 
    if($opuserid):
    $fullaccess= get_user_meta($opuserid, 'fullaccess', 'true');
   
    $tabQuery=$conn->query("select * from operator_reservation where oid='$opuserid'");
    $fetchtab=$tabQuery -> fetch_assoc();
   
    $checkTours=$conn->query("select * from tours where  oid='$opuserid'");
    $countmintours= $checkTours->num_rows;
    
    $mailsent= get_user_meta($opuserid, 'mailsent', 'true');
?>        
  <div class="row">
   <div class="col-sm-3">
        <div class="dashside">
                <ul>
                    <li><b>Currency   :  </b> <?php echo get_user_meta($opuserid, 'cust_currency', 'true');?></li>
                    <li><b>Commission : </b>  <?php echo get_user_meta($opuserid, 'commission', 'true');?>%</li>
                </ul>
         </div>        
     </div>
     <div class="col-sm-9">
                 <?php if($fullaccess>0):?>
                      <div class="row top-op-bg"> 
                          <div class="col-sm-3 supclass"><a href="/add-operator-profile?opuserid=<?php echo $opuserid;?>"> Operator Profile</a></div>
                          <div class="col-sm-3"><a href="/tour-reviews">Reviews <?php echo $unreadrws;?></a></div>
                          <div class="col-sm-3"><a href="javascript:void(0);">My Bookings</a></div>
                          <div class="col-sm-3" style="position:relative;"><a href="/tour-enquiry">My Enquiries <?php echo $unread;?></a></div>
                      </div>
                  <?php else:?>
                      <div class="row"> 
                            <div class="col-sm-4 fticon"><a href="/add-operator-profile?opuserid=<?php echo $opuserid;?>"> Operator Info</a>
                                 <?php  if( $fetchtab['ntabs']==1) { ?><i class="fa fa-check-square-o" aria-hidden="true"></i><?php } ?>
                                </div>
                            <div class="col-sm-4 fticon" <?php if( $fetchtab['ntabs']==0) { ?> style="opacity: 0.5;" <?php } ?>> <a href="javascript:void(0);" data-toggle="modal" data-target="#myModal">Add Tours</a>
                               <?php  if($countmintours>=3) { ?><i class="fa fa-check-square-o" aria-hidden="true"></i><?php } 
                                  else { ?>  <i class="fa fa-window-close-o" aria-hidden="true"></i> <?php } ?>
                            </div>
                            <div class="col-sm-4 fticon">
                                <a <?php if($countmintours>=3){?> href="https://dashboard.adventurerepubliq.com/upload-documents/" <?php  } else { ?> href="javascript:void(0)/"  style="opacity: 0.5;" 
                                 <?php } ?>> Upload Documents & Download Contract</a><?php  if($mailsent==1) { ?><i class="fa fa-check-square-o" aria-hidden="true"></i>
                                <?php }   else { ?> 
                                <i class="fa fa-window-close-o" aria-hidden="true"></i> <?php } ?>
                            </div>
                        </div>    
                  <?php endif;?>
              
        <div class="row aligntop">          
          <div class="col-sm-12"><?php if($numrows==0):?> 0 Tours <?php endif;?>    
                <table class="table viewdash">
		              <thead>
		                  <tr>
			                <th scope="col">Sr No</th>
			                <th scope="col">ID</th>
			                <th scope="col">Name</th>
			                <th scope="col">Operator Name</th>
			                <th scope="col">Price</th>
			                <th scope="col">Full Access</th>
			                <th scope="col">Tour Type</th>
			                <th scope="col">Status</th>
                            <th scope="col">Update</th>
			               </tr>
		                </thead>
		               <?php if($numrows==0):?>
		                   <tr>
		                      <td colspan="5" align="center">No Data</td>
		                   </tr>
		                  <?php endif;?> 
		                  <?php
		                   
		                     $i=1;
		                     while($tourShow=$tourQuery -> fetch_assoc()){
		                         $access= get_user_meta($tourShow['oid'], 'fullaccess', 'true');
		                         $cust_currency= get_user_meta($tourShow['oid'], 'cust_currency', 'true');
		                         $tid=$tourShow['tid'];
		                         $tourtype=$tourShow['tourtype'];
		                         $operator = get_user_by( 'id',  $tourShow['oid'] )->display_name ;
		                        
		                     if($tourShow['tourname']=='') {
		                         $tourname='';
		                         }
		                      else {
		                       $tourname=$tourShow['tourname'];
		                      }
		                      if($tourShow['tourtype']=='1'){ 
		                          $drtype="Days";
		                      }
		                      else{
		                          $drtype="HH/MM";
		                      }
                              if($tourShow['tourstatus']==0) {
                                $changeStatus=1;
                              }
                              else {
                                $changeStatus=0;
                              }
		                   ?>
		                   <tr>
		                       <td><?php echo $i;?></td>
		                       <td><?php echo $tourShow['tid'];?></td>
		                       <td><?php echo stripslashes($tourname);?>
		                           <div class="metadata">
		                                <span>Duration: <?php echo $tourShow['duration']. "/" .$drtype;?></span>
		                                <a href="https://dashboard.adventurerepubliq.com/touritinerary/<?php echo $tourShow['tourslug'];?>">View </a> |  
		                                | <a href="/operator-tour-dashboard/?tourid=<?php echo $tid;?>&thistrtype=<?php echo $tourtype;?>&opid=<?php echo  $tourShow['oid'];?>">Edit </a>  <a href="/operator-contract-download'?checkPDF=1&opid=<?php echo  $tourShow['oid'];?>">Download Contract </a>  
		                               
		                           </div> 
		                    
		                       </td>
		                       <td><?php echo $operator;?></td>
		                       <td><?php echo $cust_currency."".number_format($tourShow['price'],2);?></td>
		                       <td><?php if($access=='1'){ ?> Yes <?php }  else { ?> No <?php }?></td>
		                       <td><?php if($tourShow['tourtype']=='1'){ ?> Multi Day <?php }  else { ?> Day <?php }?></td>
		                       <td><?php if($tourShow['tourstatus']=='0'){ ?><span style="color:red; font-weight: bold;">Not Live</span> <?php }  else { ?> <span style="color:green; font-weight: bold;">Live</span> <?php }?></td>
                               <td><a href="/operator-dashboard/?opuserid=<?php echo $tourShow['oid'];?>&stidch=<?php echo $tourShow['tid'];?>&status=<?php echo $changeStatus;?>&tabstatus=<?php echo $tourShow['tabstatus'];?>">Update Status</a></td>
		                    
		                        
		                   </tr>
		                   <?php $i++; }?>
                            <?php
                        $j=$i;

                        if (!function_exists('render_scrapper_list')) {
                            function render_scrapper_list($value) {
                                if ($value === null || $value === '') return '-';
                                $items = $value;
                                if (is_string($items)) {
                                    $trim = trim($items);
                                    $u = @unserialize($trim);
                                    if ($u !== false || $trim === 'b:0;') {
                                        $items = $u;
                                    } else {
                                        $d = json_decode($trim, true);
                                        if ($d !== null) {
                                            $items = $d;
                                        } else {
                                            $items = array_values(array_filter(array_map('trim', preg_split('/\r?\n|\|/', $trim)), 'strlen'));
                                        }
                                    }
                                }
                                if (!is_array($items)) $items = [$items];
                                if (empty($items)) return '-';
                                $html = '<ul style="margin:0;padding-left:20px;">';
                                foreach ($items as $item) {
                                    if (is_array($item) || is_object($item)) $item = json_encode($item);
                                    if ($item === '' || $item === null) continue;
                                    $html .= '<li>' . nl2br(htmlspecialchars((string)$item)) . '</li>';
                                }
                                $html .= '</ul>';
                                return $html;
                            }
                        }

                        if (!function_exists('render_scrapper_itinerary')) {
                            function render_scrapper_itinerary($value) {
                                if ($value === null || $value === '') return '-';
                                $items = $value;
                                if (is_string($items)) {
                                    $trim = trim($items);
                                    $u = @unserialize($trim);
                                    if ($u !== false || $trim === 'b:0;') {
                                        $items = $u;
                                    } else {
                                        $d = json_decode($trim, true);
                                        if ($d !== null) {
                                            $items = $d;
                                        } else {
                                            return nl2br(htmlspecialchars($trim));
                                        }
                                    }
                                }
                                if (!is_array($items)) return nl2br(htmlspecialchars((string)$items));
                                $html = '';
                                $idx = 1;
                                foreach ($items as $it) {
                                    if (is_object($it)) $it = (array)$it;
                                    if (is_array($it)) {
                                        $title = $it['title'] ?? $it['day_title'] ?? $it['dayTitle'] ?? $it['heading'] ?? $it['name'] ?? ('Day ' . $idx);
                                        $desc  = $it['description'] ?? $it['desc'] ?? $it['content'] ?? $it['details'] ?? '';
                                        if (is_array($desc) || is_object($desc)) $desc = json_encode($desc);
                                        $html .= '<div style="margin-bottom:8px;"><strong>' . htmlspecialchars((string)$title) . '</strong>';
                                        if ($desc !== '' && $desc !== null) {
                                            $html .= '<div>' . nl2br(htmlspecialchars((string)$desc)) . '</div>';
                                        }
                                        $html .= '</div>';
                                    } else {
                                        $html .= '<div><strong>Day ' . $idx . ':</strong> ' . nl2br(htmlspecialchars((string)$it)) . '</div>';
                                    }
                                    $idx++;
                                }
                                return $html !== '' ? $html : '-';
                            }
                        }

                            $scraperQuery=$conn->query("select * from webscraptours where oid='$opuserid' and tranfertour='0'");
                         while($scrapperTour=$scraperQuery -> fetch_assoc()){
                            $skipFields = ['tranfertour', 'destination', 'currency', 'termid'];
                            ob_start();
                            ?>
                            <table class="table table-bordered table-striped">
                            <?php
                            foreach ($scrapperTour as $sKey => $sVal) {
                                $lk = strtolower($sKey);
                                if (in_array($lk, $skipFields, true)) continue;

                                $isImageField = (bool)preg_match('/(image|img|photo|thumb|picture)/i', $lk);
                                if (!$isImageField) {
                                    if (preg_match('/url|link/i', $lk)) continue;
                                    if (is_string($sVal) && preg_match('#^https?://#i', trim($sVal))) continue;
                                }

                                $displayKey = $sKey;
                                $displayValue = null;

                                if ($lk === 'decodedestination') {
                                    $displayKey = 'Destination';
                                    $displayValue = ($sVal === '' || $sVal === null) ? '-' : nl2br(htmlspecialchars((string)$sVal));
                                } elseif ($lk === 'tourtype') {
                                    $displayKey = 'Tour Type';
                                    $displayValue = ($sVal == '1') ? 'Multi Day Tours' : 'Day Tour';
                                } elseif ($lk === 'price' || $lk === 'tourprice') {
                                    $displayKey = 'Price';
                                    $cur = isset($scrapperTour['currency']) ? $scrapperTour['currency'] : '';
                                    $displayValue = htmlspecialchars(trim($cur . ' ' . $sVal));
                                } elseif (in_array($lk, ['highlights', 'languages', 'include', 'inclusions', 'exclude', 'exclusions'], true)) {
                                    $displayValue = render_scrapper_list($sVal);
                                } elseif ($lk === 'itinerary' || $lk === 'itineraries') {
                                    $displayValue = render_scrapper_itinerary($sVal);
                                } elseif ($isImageField) {
                                    if (!empty($sVal)) {
                                        $displayValue = '<img src="' . htmlspecialchars((string)$sVal) . '" style="max-width:300px;max-height:300px;" alt="">';
                                    }
                                } else {
                                    $displayValue = ($sVal === '' || $sVal === null) ? '-' : nl2br(htmlspecialchars((string)$sVal));
                                }

                                if ($displayValue === null) continue;
                                ?>
                                <tr>
                                    <td style="width:30%"><strong><?php echo htmlspecialchars($displayKey); ?></strong></td>
                                    <td><?php echo $displayValue; ?></td>
                                </tr>
                                <?php
                            }
                            ?>
                            </table>
                            <?php
                            $scrapperPopupHtml = ob_get_clean();
                            ?>
                            <tr>
                              <td><?php echo $j; ?></td>
                              <td>-</td>
                              <td><span class="trname"><sup>*</sup>
                                     <?php echo $scrapperTour['tourName']; ?>
                                     <div class="metadata">
                                       <span>Duration: <?php echo $scrapperTour['duration']. "/" .$drtype;?></span>
                                       <a href="javascript:void(0);" class="view-scrapper-tour" data-popup-id="scrapper-popup-<?php echo $scrapperTour['id']; ?>">View</a>
                                       <div id="scrapper-popup-<?php echo $scrapperTour['id']; ?>" style="display:none;"><?php echo $scrapperPopupHtml; ?></div>
                                     </div>
                                   </span>
                              </td>
                               <td>-</td>
                                <td><?php echo ($scrapperTour['tourType']=='1') ? 'Multi Day Tours' : 'Day Tour'; ?></td>
                              <td>Not Live</td>
                            </tr>
                            <?php
                           $j++;
                          }
                           ?>
                    </table>
      
            </div>
           </div>
      </div>
    <?php endif;?>

<!-- Scrapper Tour Info Modal -->
<div class="modal fade" id="scrapperTourModal" tabindex="-1" role="dialog" aria-labelledby="scrapperTourModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="scrapperTourModalLabel">Scrapper Tour Information</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body" id="scrapperTourModalBody"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
$(document).on('click', '.view-scrapper-tour', function(e) {
    e.preventDefault();
    var popupId = $(this).data('popup-id');
    var $source = $('#' + popupId);
    $('#scrapperTourModalBody').html($source.length ? $source.html() : '<p>No data available.</p>');
    $('#scrapperTourModal').modal('show');
});
</script>

    <script>
    $(document).ready(function() {
    // Flag to track if we're setting the value programmatically
    var settingValue = false;
    
    // Initialize Select2 for both dropdowns
    $('.select2-search').select2({
        placeholder: 'Search for an operator...',
        allowClear: true,
        width: '100%'
    });
    
    // Handle dropdown change event
    $('.select2-search').on('change', function() {
        // Only proceed if we're not setting the value programmatically
        if (!settingValue) {
            var selectedValue = $(this).val();
            if (selectedValue) {
                window.location = 'https://dashboard.adventurerepubliq.com/operator-dashboard/?opuserid=' + selectedValue;
            }
        }
        return false;
    });
    
    // If you need to maintain the selected value after form submission
    <?php if(isset($opuserid) && $opuserid != 'All') { ?>
        settingValue = true; // Set flag before changing value
        $('#inactiveOperators').val('<?php echo $opuserid; ?>').trigger('change');
        settingValue = false; // Reset flag after changing value
    <?php } ?>
});
</script>
<?php


require_once dirname( __FILE__ ) . '/footer.php';