<?php
session_start();
include 'connect.php';

if (empty($_SESSION['user_login'])) {
    header("Location: login.php");
    exit;
}

$start = 0;
$limite = 500;
$pageNow = 1;

if (isset($_GET['page']) && is_numeric($_GET['page'])) {
    $pageNow = max(1, (int)$_GET['page']);
    $start = ($pageNow - 1) * $limite;
}

$filterby = "";
$addUrl = "";

// Date filter - reliable parsing
$selectedDateRange = trim($_GET['filterbydate'] ?? '');
if ($selectedDateRange) {
    $parts = explode(' - ', $selectedDateRange);
    if (count($parts) === 2) {
        $startStr = trim($parts[0]);
        $endStr   = trim($parts[1]);

        $startDt = DateTime::createFromFormat('F j, Y', $startStr);
        $endDt   = DateTime::createFromFormat('F j, Y', $endStr);

        if ($startDt && $endDt) {
            $startDate = $startDt->format('Y-m-d');
            $endNext   = (clone $endDt)->modify('+1 day');
            $endDate   = $endNext->format('Y-m-d');

            $filterby .= " AND request_date >= '$startDate' AND request_date < '$endDate'";
            $addUrl   .= "&filterbydate=" . urlencode($selectedDateRange);
        }
    }
}

// Multiple sources
$selectedSources = [];
if (!empty($_GET['source'])) {
    $sources = array_filter(array_map('trim', explode(',', $_GET['source'])));
    if ($sources) {
        $escaped = array_map(fn($s) => "'" . mysqli_real_escape_string($conn, $s) . "'", $sources);
        $filterby .= " AND utm_source IN (" . implode(',', $escaped) . ")";
        $addUrl   .= "&source=" . urlencode(implode(',', $sources));
        $selectedSources = $sources;
    }
}

$sql = "SELECT * FROM requests 
        WHERE span_status = '0' AND delete_status = 0 
        $filterby 
        ORDER BY id DESC 
        LIMIT $start, $limite";

$result = mysqli_query($conn, $sql);

$total_sql = "SELECT COUNT(id) as total FROM requests 
              WHERE span_status = '0' AND delete_status = 0 $filterby";
$totalRes = mysqli_fetch_assoc(mysqli_query($conn, $total_sql));
?>

<!DOCTYPE html>
<html lang="en" class="light-style layout-menu-fixed" dir="ltr" data-theme="theme-default"
      data-assets-path="assets/" data-template="vertical-menu-template-free">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />

    <title>Microsites</title>

    <link rel="icon" type="image/x-icon" href="assets/img/favicon/favicon.ico" />
    <link href="https://fonts.googleapis.com/css2?family=Public+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet"/>
    <link rel="stylesheet" href="assets/vendor/fonts/boxicons.css" />
    <link rel="stylesheet" href="assets/vendor/css/core.css" />
    <link rel="stylesheet" href="assets/vendor/css/theme-default.css" />
    <link rel="stylesheet" href="assets/css/demo.css" />
    <link rel="stylesheet" href="assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <script src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <style>
        .filter-card { border-radius: 10px; }
        .btn-apply { min-width: 150px; }
    </style>
</head>
<body>

<div class="layout-wrapper layout-content-navbar">
    <div class="layout-container">
        <div class="layout-page">

            <?php include 'navbar.php'; ?>

            <div class="content-wrapper">
                <div class="container-xxl flex-grow-1 container-p-y">

                    <div class="card mb-3" id="offerAcceptDenyResultDiv">
                        <div class="card-body text-center">
                            <span id="offerAcceptDenyResult"></span>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="card filter-card shadow-sm mb-4">
                        <div class="card-body">
                            <div class="row g-3 align-items-end">

                                <div class="col-lg-4 col-md-4">
                                    <label class="form-label fw-bold">Date Range</label>
                                    <div id="reportrange" class="form-control d-flex align-items-center cursor-pointer">
                                        <i class="fa fa-calendar-days me-2 text-muted"></i>
                                        <span><?= htmlspecialchars($selectedDateRange ?: 'Select date range...') ?></span>
                                        <i class="fa fa-chevron-down ms-2 text-muted small"></i>
                                    </div>
                                </div>

                                <div class="col-lg-4 col-md-4">
                                    <label class="form-label fw-bold">Source (multiple allowed)</label>
                                    <select id="sourceSelect" class="form-select select2-multiple" multiple>
                                        <option value="xd" <?= in_array('xd', $selectedSources)?'selected':'' ?>>XD</option>
                                        <option value="xdd" <?= in_array('xdd', $selectedSources)?'selected':'' ?>>XDD</option>
                                        <option value="xdp" <?= in_array('xdp', $selectedSources)?'selected':'' ?>>XDP</option>
                                        <option value="xddaw" <?= in_array('xddaw', $selectedSources)?'selected':'' ?>>XDDAW</option>
                                        <option value="xdaw" <?= in_array('xdaw', $selectedSources)?'selected':'' ?>>XDAW</option>
                                        <option value="xdpl" <?= in_array('xdpl', $selectedSources)?'selected':'' ?>>XDPL</option>
                                        <option value="xddpl" <?= in_array('xddpl', $selectedSources)?'selected':'' ?>>XDDPL</option>
                                        <option value="BTS DMXD" <?= in_array('BTS DMXD', $selectedSources)?'selected':'' ?>>BTS DMXD</option>
                                        <option value="BTS XD" <?= in_array('BTS XD', $selectedSources)?'selected':'' ?>>BTS XD</option>
                                        <option value="BTS XDD" <?= in_array('BTS XDD', $selectedSources)?'selected':'' ?>>BTS XDD</option>
                                        <option value="Digital Marketing XD" <?= in_array('Digital Marketing XD', $selectedSources)?'selected':'' ?>>Digital Marketing XD</option>
                                    </select>
                                </div>

                                <div class="col-lg-4 col-md-4 d-flex align-items-end gap-2 flex-wrap">
                                    <button id="btnApplyFilters" class="btn btn-primary btn-apply">
                                        <i class="fa fa-filter me-1"></i> Apply Filters
                                    </button>

                                    <form action="export_excel.php" method="get" class="">
                                        <input type="hidden" name="filterbydate" value="<?= htmlspecialchars($selectedDateRange ?? '') ?>">
                                        <input type="hidden" name="source" value="<?= htmlspecialchars(implode(',', $selectedSources)) ?>">
                                        <button type="submit" class="btn btn-success">
                                            <i class="fas fa-download me-1"></i> Export to Excel
                                        </button>
                                    </form>
                                </div>

                            </div>
                        </div>
                    </div>

                    <!-- Table + Pagination (your original style kept) -->
                    <div class="card" style="margin-top: 20px;">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Project</th>
                                        <th>Sender</th>
                                        <th>Source</th>
                                        <th>Date</th>
                                        <th>Location</th>
                                        <th>Mobile</th>
                                        <th>IP</th>
                                        <th>Email</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($result) > 0): ?>
                                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                                            <tr id="tr<?= $row['id'] ?>">
                                                <td><?= $row['id'] ?></td>
                                                <td><?= htmlspecialchars($row['project_name'] ?? '-') ?></td>
                                                <td><?= htmlspecialchars($row['name'] ?? '-') ?></td>
                                                <td><?= htmlspecialchars($row['utm_source'] ?: 'N/A') ?></td>
                                                <td><?= htmlspecialchars($row['request_datetime'] ?? '-') ?></td>
                                                <td><?= htmlspecialchars($row['city'] ?? '-') ?> (<?= htmlspecialchars($row['country'] ?? '-') ?>)</td>
                                                <td>(<?= htmlspecialchars($row['calling_code'] ?? '') ?>) XXXXXX<?= substr($row['mobile'] ?? '0000', -4) ?></td>
                                                <td><?= htmlspecialchars($row['ip_address'] ?? '-') ?></td>
                                                <td><?= $row['email'] ? substr($row['email'], 0, 3) . 'xxxx@gmail.com' : '-' ?></td>
                                                <td>
                                                    <a href="javascript:void(0);" onclick="sendSpam(<?= $row['id'] ?>)">
                                                        <img src="assets/img/spam.jpg" width="24">
                                                    </a>
                                                    <?php if ($_SESSION['admin_id'] == 1): ?>
                                                    <a href="javascript:void(0);" onclick="deletefunction(<?= $row['id'] ?>)">
                                                        <img src="assets/img/delete.jpg" width="24">
                                                    </a>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr><td colspan="10" class="text-center">No Found Data</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Your original pagination -->
                        <div class="pagination p-3 d-flex justify-content-center">
                            <?php
                            $totalpages = ceil($totalRow['total'] / $limite);
                            if ($totalpages > 1) {
                                echo '<a class="btn btn-primary mx-1" href="?page=1'.$addUrl.'">First</a>';

                                $num = 1;
                                if ($pageNow > 2) {
                                    $startfor = $pageNow - 2;
                                    for ($num = $startfor; $num < $startfor + 2; $num++) {
                                        $active = ($pageNow == $num) ? 'btn-dark active' : 'btn-primary';
                                        echo '<a class="btn '.$active.' mx-1" href="?page='.$num.$addUrl.'">'.$num.'</a>';
                                    }
                                }

                                for (; $num <= $totalpages; $num++) {
                                    if ($num > $pageNow + 2) break;
                                    $active = ($pageNow == $num) ? 'btn-dark active' : 'btn-primary';
                                    echo '<a class="btn '.$active.' mx-1" href="?page='.$num.$addUrl.'">'.$num.'</a>';
                                }

                                echo '<a class="btn btn-primary mx-1" href="?page='.$totalpages.$addUrl.'">Last</a>';
                            }
                            ?>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<script>
// DateRangePicker + restore value
$('#reportrange').daterangepicker({
    startDate: moment().subtract(29, 'days'),
    endDate: moment(),
    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')]
    }
}, function(start, end) {
    $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
});

<?php if ($selectedDateRange): ?>
    $('#reportrange span').html(<?= json_encode($selectedDateRange) ?>);
<?php endif; ?>

// Select2 multiple
$('#sourceSelect').select2({
    placeholder: "Select one or more sources...",
    allowClear: true,
    closeOnSelect: false
});

// Apply button
$('#btnApplyFilters').click(function(){
    let dateStr = $('#reportrange span').text().trim();
    let sources = $('#sourceSelect').val() || [];

    if (dateStr === 'Select date range...') dateStr = '';

    let url = new URL(window.location.href);
    url.searchParams.delete('page');

    if (dateStr) url.searchParams.set('filterbydate', dateStr);
    else url.searchParams.delete('filterbydate');

    if (sources.length) url.searchParams.set('source', sources.join(','));
    else url.searchParams.delete('source');

    window.location = url;
});

// Your spam/delete functions (unchanged)
function sendSpam(id){
    if(!confirm("Are you sure you want to send in spam?")) return;
    document.getElementById('tr'+id).style.display = "none";
    $.ajax({
        url: "microsites.php",
        data: {spanRequests:"true", id:id},
        type: 'post',
        dataType: "json",
        success: function(data){
            if(data.status == 'success'){
                $("#offerAcceptDenyResultDiv").addClass('alert-success').show();
                $("#offerAcceptDenyResult").text(data.message);
                setTimeout(()=>location.reload(),1000);
            } else {
                $("#offerAcceptDenyResultDiv").addClass('alert-danger').show();
                $("#offerAcceptDenyResult").text('Some error occurred');
            }
        }
    });
}

function deletefunction(id){
    if(!confirm("Are you sure you want to delete this?")) return;
    document.getElementById('tr'+id).style.display = "none";
    $.ajax({
        url: "microsites.php",
        data: {deleteRequests:"true", id:id},
        type: 'post',
        dataType: "json",
        success: function(data){
            if(data.status == 'success'){
                $("#offerAcceptDenyResultDiv").addClass('alert-success').show();
                $("#offerAcceptDenyResult").text(data.message);
                setTimeout(()=>location.reload(),1000);
            } else {
                $("#offerAcceptDenyResultDiv").addClass('alert-danger').show();
                $("#offerAcceptDenyResult").text('Some error occurred');
            }
        }
    });
}
</script>

</body>
</html>