<?php 
    include "header.php";
   include "databaseConnect.php";  
   $cczCount ='';  
   $totalRecord='';
   $ccaCount='';
   $source='';

//    print_r($_SESSION);die;

    $numRecordPerPage = 30;
    include "pagination.php";

    $where = '1=1';
    $searchBySlug = '';
    if(isset($_REQUEST['searchBySlug']) && !empty($_REQUEST['searchBySlug'])){
        $searchBySlug = $_REQUEST['searchBySlug'];
        $where .= " AND slug = '$searchBySlug'";
    }else{
        $where .= " AND slug !='' ";
    }

    if(isset($_REQUEST['daterange']) && !empty($_REQUEST['daterange'])){
        $dateRange = $_REQUEST['daterange'];
        list($startDate, $endDate) = explode(' - ', $dateRange);
        $startDate = date('Y-m-d',strtotime($startDate));
        $endDate = date('Y-m-d',strtotime($endDate));
     }else{
        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $dateRange =  date('d-M-y',strtotime($startDate)) .' - '. date('d-M-y',strtotime($endDate));
    }

    if(isset($_REQUEST['source']) && !empty($_REQUEST['source'])){
        $source = $_REQUEST['source'];
    }

    if (empty($numrecords) || !is_numeric($numrecords)) {
        $sql1 = "SELECT count(DISTINCT slug) as total from tblhoteldetails where $where ";
        $result1 = mysqli_query($conn, $sql1);
        $row1 = mysqli_fetch_assoc($result1);
        $totalRecord = $row1["total"];

   
        if($searchBySlug !=''){
        $sql2 = "SELECT count(*) as landingTotal from tbluseractivitylogs where current_url LIKE '%$searchBySlug' and date(created_at) BETWEEN '$startDate' AND '$endDate' and type=' ' ";

        $sql3 = "SELECT count(*) as clickTotal from tbluseractivitylogs where current_url LIKE '%$searchBySlug' and date(created_at) BETWEEN '$startDate' AND '$endDate' and type='click' ";
        

        $sql4 = "SELECT count(*) as totalCount FROM tbluseractivitylogs where current_url LIKE '%$searchBySlug' and date(created_at) BETWEEN '$startDate' AND '$endDate'";
        }else{
        $sql2 = "SELECT count(*) as landingTotal from tbluseractivitylogs where date(created_at) BETWEEN '$startDate' AND '$endDate' and type=' ' ";

        $sql3 = "SELECT count(*) as clickTotal from tbluseractivitylogs where date(created_at) BETWEEN '$startDate' AND '$endDate' and type='click' ";

        $sql4 = "SELECT count(*) as totalCount FROM tbluseractivitylogs where date(created_at) BETWEEN '$startDate' AND '$endDate'";
        }

        if (isset($source) && !empty($source)) {
            $sql2 .= " AND source = '$source' ";
            $sql3 .= " AND source = '$source' ";
            $sql4 .= " AND source = '$source' ";
        }
     
// echo $sql2 .'<br>'. $sql3. '<br>'. $sql4;
        $result2 = mysqli_query($conn, $sql2);
        $row2 = mysqli_fetch_assoc($result2);
        $landingTotal = $row2["landingTotal"];

        
        $result3 = mysqli_query($conn, $sql3);
        $row3 = mysqli_fetch_assoc($result3);
        $clickTotal = $row3["clickTotal"];

        
        $result4 = mysqli_query($conn, $sql4);
        $row4 = mysqli_fetch_assoc($result4);
        $totalCount = $row4["totalCount"];
    }
    //echo $totalRecord . ' ------------'; die;
    $queryLimit = $start.",".$numRecordPerPage;
    $query = "SELECT DISTINCT slug FROM tblhoteldetails where $where limit $queryLimit"; 
    $result = mysqli_query($conn, $query);
    //echo '<pre>';print_r($result); die(' all result is here++++++++');
?>
<style>
    .table-container {
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch;
        max-width: 100%;  
    }
    table {
        width: 100%;
        border-collapse: collapse;
    }
    th, td {
        padding: 8px;
        text-align: left;
        border: 1px solid #ddd;
    }
    th {
        background-color: #f4f4f4;
    }
    .table th:nth-child(2), .table td:nth-child(2) { width: 150px; } /* Hotel Name */
    .table th:nth-child(3), .table td:nth-child(3) { max-width: 300px;max-height: 300px;overflow:auto; } /* Link */
    .table th:nth-child(4), .table td:nth-child(4) { width: 200px; } /* Rating Comment */
    .table th:nth-child(5), .table td:nth-child(5) { width: 100px; } /* Review Number */
    .table th:nth-child(6), .table td:nth-child(6) { width: 100px; } /* Pricing */
    .table th:nth-child(7), .table td:nth-child(7) { width: 150px; } /* Free Cancellation */
    .table th:nth-child(8), .table td:nth-child(8) { width: 150px; } /* No Pre-payment */
    .table th:nth-child(9), .table td:nth-child(9) { width: 200px; } /* Hotel Address */
    .table th:nth-child(10), .table td:nth-child(10) { max-width: 300px; overflow:auto;} /* Image URL */
    .table th:nth-child(11), .table td:nth-child(11) { width: 250px; } /* Amenities */
    .pagination {
        display: flex;
        list-style: none;
        padding: 0;
        margin: 0;
        justify-content: flex-end;
    }

    .pagination li {
        margin: 0 5px;
    }

    .pagination li a {
        color: #007bff;
        padding: 8px 12px;
        text-decoration: none;
        border: 1px solid #ddd;
        border-radius: 4px;
        transition: background-color 0.3s, color 0.3s;
    }

    .pagination li a:hover {
        background-color: #007bff;
        color: white;
        border-color: #007bff;
    }

    .pagination li.active a {
        background-color: #007bff;
        color: white;
        border-color: #007bff;
    }

    .pagination .prev i {
        margin-right: 5px;
    }

</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/daterangepicker/3.1/daterangepicker.min.css">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/daterangepicker/3.1/daterangepicker.min.js"></script>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <div class="card">
        <div class="card-header">
            <div class="row">
                <div class="col-sm-3">
                    <span>Total <strong><?=$totalRecord;?> </strong>Records Found.</strong></span>
                </div>
                <div class="col-sm-9 d-flex">
                    <form method="get">
                        <div class="col-sm-8 d-flex" style="gap:20px;">
                            <select class="form-control" name="searchBySlug" style="width: 150px;">
                                <option value="">Search Slug</option>
                                <?php 
                                    $sql = "select distinct slug from tblhoteldetails where slug != ''";
                                    $query = mysqli_query($conn, $sql);
                                    if(mysqli_num_rows($query)>0){
                                ?>
                                        <?php while($slugs = mysqli_fetch_assoc($query)){?>
                                            <option value="<?=$slugs['slug']?>" <?=$searchBySlug== $slugs['slug'] ? 'selected' : ''?>><?=$slugs['slug']?></option>
                                <?php }}?>
                            </select>
                            <!-- <input type="date" name="date" class="form-control" value="<?= $date ?>" max="<?= date('Y-m-d') ?>" /> -->
                            <input type="text" name="daterange" id="daterange" class="form-control" style="width:auto;margin-left: -15px;display: initial !important;" />
                            <input type="hidden" id="startDate" value="<?= $startDate?>">
                            <input type="hidden" id="endDate" value="<?= $endDate?>">
                            <select class="form-control" name="source" style="width: 100px;">
                                <option value="">Source</option>
                                <option value="myairtrip" <?= isset($source) && $source=='myairtrip'?'selected':'' ?>>myairtrip</option>
                                <option value="tripwus" <?= isset($source) && $source=='tripwus'?'selected':'' ?>>tripwus</option>
                                <option value="top10-comparision" <?= isset($source) &&$source=='top10-comparision'?'selected':'' ?>>top10-comparision</option>
                            </select>
                            <button type="submit" class="btn btn-primary">Search</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="card-body">
            <!-- Main content -->
            <section class="content">
                <div class="container-fluid">
                    <!-- Show data here -->
                <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Slug (Total:<?= $totalCount?>)</th>
                                    <th style="min-width: 240px;">Landing Count (Total:<?= $landingTotal?>)</th>
                                    <th>Clicks Count (Total:<?= $clickTotal?>)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($row = mysqli_fetch_assoc($result)) { ?>
                                    <?php 
                                     $innerLQuery = 'SELECT count(*) as landing_count FROM tbluseractivitylogs WHERE type=\'\' AND date(created_at) BETWEEN "'.$startDate.'" AND "'.$endDate.'" AND current_url LIKE "%' . $row['slug'] . '" '; 
                                     if (isset($source) && !empty($source)) {
                                        $innerLQuery .= " AND source = '$source' ";
                                     }
                                     $innerLResult = mysqli_query($conn, $innerLQuery); 
                                     $innerLrow = mysqli_fetch_assoc($innerLResult);
                                     $totalLandingCount = $innerLrow["landing_count"];   

                                     $innerCQuery = 'SELECT count(*) as click_count FROM tbluseractivitylogs WHERE type=\'click\' AND date(created_at) BETWEEN "'.$startDate.'" AND "'.$endDate.'" AND current_url LIKE "%' . $row['slug'] . '" '; 
                                    // echo $innerCQuery.'<br>';
                                    if (isset($source) && !empty($source)) {
                                        $innerCQuery .= " AND source = '$source' ";
                                     }
                                     $innerCResult = mysqli_query($conn, $innerCQuery); 
                                     $innerCrrow = mysqli_fetch_assoc($innerCResult);
                                     $totalClickCount = $innerCrrow["click_count"];   
                                    ?>
                                    <tr>
                                        <td>
                                            <?php echo str_replace('best-hotel-deals-', "", $row['slug']); ?>
                                        </td>
                                        <td><?php echo $totalLandingCount; ?></td>
                                        <td>
                                            <?php 
                                                if($totalClickCount>0){
                                            ?>
                                            <?= $totalClickCount; ?>
                                            <a href='click-log.php?searchBySlug=<?= $row["slug"] ?>&daterange=<?= $dateRange ?>&type=click'>&nbsp;Details
                                           <?php }else{echo $totalClickCount;}?>
                                        </td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                </div>
                </div><!-- /.container-fluid -->
            </section>
            <!-- /.content -->
        </div>
        <div class="card-footer">
            <div class="row">
                <div class="col-md-12 col-lg-12 dispCenter">
                    <div class="dataTables_paginate paging_simple_numbers">
                        <ul class="pagination">
                            <?php
                            $pageName = "newUserlog.php";
                            $parameters = "searchBySlug=".$searchBySlug."&daterange=".$dateRange."&source=".$source;
                            
                            printPagination($pageName,$numRecordPerPage,$totalRecord,$parameters);
                        ?>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <!-- <div class="card-footer"></div> -->
    </div>

    
</div>

<!-- Modal -->
<div class="modal fade" id="clickEvent" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document" style="width:1250px;">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Click Event</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div class="form-group"><span id="processclick" style="display: none;"></span></div>
            <div class="form-group col-sm-12">
                <div class="row">
                    <div class="table-responsive">
                        <div class="clicksList"></div>

                    </div>
                </div>
            </div>
        </div>
    </div>
  </div>
</div>
<script type="text/javascript">
    function clickEventFun(slug,date,type='click'){
        $(".clicksList").html(''); 
        $('#processclick').show().html('<span class="alert alert-card alert-info">Please wait......</span>');
        $.ajax({
            url: "server-log.php", 
            type: "POST",             
            data: {                  
                slug: slug,
                date: date,
                type: type
            },
            cache: false,
            dataType: 'html',
            success: function(response){
              $(".clicksList").append(response); 
              $("#processclick").hide();  
            }

        });
   
        $('#clickEvent').modal({
            backdrop: 'static',
            keyboard: false,  
            show: true
        });
    }

    $(function() {

        var start = $("#startDate").val();
        var end = $("#endDate").val();

       
        if(start && end ){
            var start = moment(start);
            var end = moment(end);
        }else{
            var start = moment().subtract(0, 'days');
            var end = moment();
        }
        

        function cb(start, end) {
            $('#daterange').html(start.format('DD-MMMM-YYYY') + ' - ' + end.format('DD-MMMM-YYYY'));
            $('#startDate').val(start.format('YYYY-MM-DD'));
            $('#endDate').val(end.format('YYYY-MM-DD'));
        }

        $('#daterange').daterangepicker({
            locale: {
                format: 'DD-MMM-YY'
            },
            startDate: start,
            endDate: end,
            ranges: {
            'Today': [moment(), moment()],
            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 Days': [moment().subtract(6, 'days'), moment()],
            'Last 30 Days': [moment().subtract(29, 'days'), moment()],
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        }, cb);

        cb(start, end);

});
</script>
<?php include "footer.php"?>


