<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

$user_id = $_SESSION['user_id'];
$domain_id = (int)($_GET['id'] ?? 0);
$type = $_GET['type'] ?? 'isp'; // 'isp' or 'region'

// Security: Verify domain ownership
$stmt = $pdo->prepare("SELECT * FROM user_domains WHERE id = ? AND user_id = ?");
$stmt->execute([$domain_id, $user_id]);
$domain = $stmt->fetch();
if (!$domain) {
    die("Domain not found or unauthorized.");
}

// Date Range
$start_date = $_GET['start'] ?? date('Y-m-d', strtotime('-30 days'));
$end_date = $_GET['end'] ?? date('Y-m-d');

// Sorting
$sort_col = $_GET['sort'] ?? 'created_at';
$sort_order = $_GET['order'] ?? 'DESC';

// Map sortable columns
$allowed_cols = ['created_at', 'isp', 'region', 'device', 'event_type', 'ip_address'];
if (!in_array($sort_col, $allowed_cols)) $sort_col = 'created_at';
$sort_order = ($sort_order === 'ASC') ? 'ASC' : 'DESC';

// Fetch details
$query = "
    SELECT ip_address, isp, region, device, event_type, created_at 
    FROM link_analytics 
    WHERE domain_id = ? AND DATE(created_at) BETWEEN ? AND ?
";
if ($type === 'isp' && isset($_GET['val'])) {
    $query .= " AND isp = ?";
} elseif ($type === 'region' && isset($_GET['val'])) {
    $query .= " AND region = ?";
}

$query .= " ORDER BY $sort_col $sort_order";

$stmt = $pdo->prepare($query);
$params = [$domain_id, $start_date, $end_date];
if (isset($_GET['val'])) $params[] = $_GET['val'];

$stmt->execute($params);
$details = $stmt->fetchAll();

$pageTitle = "Detailed " . ($type === 'isp' ? 'ISPs' : 'Regions') . " - " . $domain['domain_name'];
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
    .bg-primary-focus { background-color: rgba(99, 102, 241, 0.1) !important; }
    .text-primary-main { color: #6366f1 !important; }
    .bg-danger-focus { background-color: rgba(244, 63, 94, 0.1) !important; }
    .text-danger-main { color: #f43f5e !important; }
    .bg-success-focus { background-color: rgba(16, 185, 129, 0.1) !important; }
    .text-success-main { color: #10b981 !important; }
    .bg-info-focus { background-color: rgba(59, 130, 246, 0.1) !important; }
    .text-info-main { color: #3b82f6 !important; }
</style>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <div>
                    <h6 class="fw-semibold mb-0">Analytics Details: <?= $type === 'isp' ? 'ISP Providers' : 'Visitor Regions' ?></h6>
                    <ul class="d-flex align-items-center gap-2 text-sm mt-4">
                        <li class="fw-medium">
                            <a href="<?= SITE_URL ?>/dashboard" class="d-flex align-items-center gap-1 hover-text-primary text-secondary-light">
                                <iconify-icon icon="solar:home-smile-angle-outline" class="icon"></iconify-icon> Dashboard
                            </a>
                        </li>
                        <li class="text-secondary-light">-</li>
                        <li class="fw-medium">
                            <a href="<?= SITE_URL ?>/analytics?id=<?= $domain_id ?>" class="hover-text-primary text-secondary-light">Analytics</a>
                        </li>
                        <li class="text-secondary-light">-</li>
                        <li class="fw-medium text-primary-600">Detailed Report</li>
                    </ul>
                </div>
                <form class="d-flex align-items-center gap-2 bg-white p-8 radius-8 shadow-sm">
                    <input type="hidden" name="id" value="<?= $domain_id ?>">
                    <input type="hidden" name="type" value="<?= $type ?>">
                    <?php if(isset($_GET['val'])): ?>
                        <input type="hidden" name="val" value="<?= htmlspecialchars($_GET['val']) ?>">
                    <?php endif; ?>
                    <input type="date" name="start" value="<?= $start_date ?>" class="form-control form-control-sm border-0 bg-light">
                    <span class="text-xs fw-bold">-</span>
                    <input type="date" name="end" value="<?= $end_date ?>" class="form-control form-control-sm border-0 bg-light">
                    <button type="submit" class="btn btn-primary btn-sm px-16 radius-6">Filter</button>
                    <a href="<?= SITE_URL ?>/analytics?id=<?= $domain_id ?>" class="btn btn-outline-secondary btn-sm px-16 radius-6">Back</a>
                </form>
            </div>

            <div class="card h-100 radius-12 border-0 shadow-sm">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table bordered-table mb-0 dataTable">
                            <thead>
                                <tr class="bg-light">
                                    <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light">Date & Time</th>
                                    <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light">IP Address</th>
                                    <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light"><?= $type === 'isp' ? 'ISP Provider' : 'Region/City' ?></th>
                                    <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light">Device</th>
                                    <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light">Event Type</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($details)): ?>
                                    <tr><td colspan="5" class="text-center py-24 text-muted">No data found for this range.</td></tr>
                                <?php endif; ?>
                                <?php foreach ($details as $row): ?>
                                <tr>
                                    <td class="px-24 py-12 text-sm fw-medium"><?= date('M d, Y H:i:s', strtotime($row['created_at'])) ?></td>
                                    <td class="px-24 py-12 text-sm text-secondary-light"><?= htmlspecialchars($row['ip_address'] ?: '0.0.0.0') ?></td>
                                    <td class="px-24 py-12">
                                        <div class="d-flex align-items-center gap-8 fw-bold text-dark">
                                            <iconify-icon icon="<?= $type === 'isp' ? 'solar:globus-bold-duotone' : 'solar:map-point-bold-duotone' ?>" class="<?= $type === 'isp' ? 'text-primary-main' : 'text-danger-main' ?> text-lg"></iconify-icon>
                                            <span><?= htmlspecialchars(($type === 'isp' ? $row['isp'] : $row['region'])  ?: 'Unknown') ?></span>
                                        </div>
                                    </td>
                                    <td class="px-24 py-12">
                                        <?php 
                                            $icon = 'solar:monitor-bold-duotone';
                                            if ($row['device'] === 'Mobile') $icon = 'solar:smartphone-bold-duotone';
                                            if ($row['device'] === 'Tablet') $icon = 'solar:tablet-bold-duotone';
                                        ?>
                                        <div class="d-flex align-items-center gap-8 text-sm">
                                            <iconify-icon icon="<?= $icon ?>" class="text-secondary-light"></iconify-icon>
                                            <span><?= $row['device'] ?></span>
                                        </div>
                                    </td>
                                    <td class="px-24 py-12">
                                        <span class="badge <?= $row['event_type'] === 'click' ? 'bg-success-focus text-success-main' : 'bg-info-focus text-info-main' ?> px-12 py-4 radius-4 text-xs fw-bold">
                                            <?= strtoupper($row['event_type']) ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/footer.php'; ?>
    </main>
    <script>
        $(document).ready(function() {
            if ($.fn.DataTable.isDataTable('.dataTable')) {
                $('.dataTable').DataTable().destroy();
            }
            $('.dataTable').DataTable({
                "order": [[ 0, "desc" ]],
                "pageLength": 25,
                "language": {
                    "search": "Search report:",
                    "lengthMenu": "Show _MENU_ entries"
                }
            });
        });
    </script>
</body>
</html>


