<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

file_put_contents('debug_log.txt', "Script started\n", FILE_APPEND);

if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 31536000);
    ini_set('session.cookie_lifetime', 31536000);
    session_start();
}

require_once 'db.php';


// ✅ Check if user is logged in
if (!isset($_SESSION['logged_in_user'])) {
    header("Location: user-login.php");
    exit;
}

$loggedInUsername = $_SESSION['logged_in_user'];

$stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUsername]);
$userData = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$userData) {
    die("<p style='color: red;'>❌ ERROR: No user found in the database with session ID ($loggedInUsername)!</p>");
}

$user_id_string = $userData['user_id']; // like "edkeyte"
$user_id = $userData['id'];             // numeric ID like 127




file_put_contents('debug_log.txt', "Logged in session: $loggedInUsername\n", FILE_APPEND);

function timeAgo($datetime) {
    $timestamp = strtotime($datetime);
    $diff = time() - $timestamp;

    if ($diff < 60) return $diff . ' seconds ago';
    if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
    if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
    return date('M d, Y H:i', $timestamp); // fallback full date
}


// Convert timestamp into “time ago” (e.g., "5 minutes ago")

// Detect Device Type
function detectDevice($userAgent) {
    $userAgent = strtolower($userAgent);
    if (strpos($userAgent, 'mobile') !== false) return '📱 Mobile';
    if (strpos($userAgent, 'tablet') !== false || strpos($userAgent, 'ipad') !== false) return '📱 Tablet';
    return '💻 Desktop';
}


function getCountryFlagByCode($code) {
    if (empty($code)) return '❓'; // Unknown
    $code = strtolower($code); // e.g., 'us'
    return "<img src='https://flagcdn.com/16x12/$code.png' alt='$code' title='$code' style='width: 20px; height: 14px; margin-right: 5px;'>";
}




$referrerId = $userData['referrer_id'] ?? null;

// Fetch the referrer's LeadsLeap ID if a referrer exists
// Default LeadsLeap ID if sponsor does not have one
$defaultLeadsLeapId = 'keyte';

$referrerLeadsLeapId = $defaultLeadsLeapId; // Set default first

if ($referrerId) {
    $stmt = $pdo->prepare("SELECT leadsleap_user_id FROM users WHERE user_id = ?");
    $stmt->execute([$referrerId]);
    $referrerData = $stmt->fetch(PDO::FETCH_ASSOC);

    // Only override default if the sponsor has a valid LeadsLeap ID
    if (!empty($referrerData['leadsleap_user_id'])) {
        $referrerLeadsLeapId = $referrerData['leadsleap_user_id'];
    }
}




// ✅ Process Profile Update Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    if (empty($first_name) || empty($last_name) || empty($email)) {
        $errorMessage = "All fields except password are required.";
    } else {
        // ✅ Check if email is already taken by another user
        $stmt = $pdo->prepare("SELECT user_id FROM users WHERE email = ? AND user_id != ?");
        $stmt->execute([$email, $user_id]);
        if ($stmt->fetch()) {
            $errorMessage = "Email is already in use by another user.";
        } else {
            // ✅ Prepare update query
            $updateColumns = ["first_name = ?", "last_name = ?", "email = ?"];
            $updateValues = [$first_name, $last_name, $email];

            // ✅ Hash new password if provided
            if (!empty($password)) {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                $updateColumns[] = "edit_token = ?";
                $updateValues[] = $hashedPassword;
            }

            // ✅ Update user info in database
            $updateValues[] = $user_id;
            $stmt = $pdo->prepare("UPDATE users SET " . implode(", ", $updateColumns) . " WHERE user_id = ?");
            if ($stmt->execute($updateValues)) {
                // ✅ Redirect to avoid form resubmission on refresh
                header("Location: profile.php?profile_saved=1");
                exit;
            } else {
                $errorMessage = "Failed to update profile.";
            }
        }
    }
}

// ✅ Process LeadsLeap Update Form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_leadsleap'])) {
    $leadsleap_user_id = trim($_POST['leadsleap_user_id'] ?? '');
    $leadsleap_list_id = trim($_POST['leadsleap_list_id'] ?? '');
    $leadsleap_list_id_referrals = trim($_POST['leadsleap_list_id_referrals'] ?? ''); // ✅ New field for referrals


    if (!empty($leadsleap_user_id) && !empty($leadsleap_list_id)) {
        // ✅ Update the database
        $stmt = $pdo->prepare("UPDATE users SET leadsleap_user_id = ?, leadsleap_list_id = ?, leadsleap_list_id_referrals = ? WHERE user_id = ?");
        $result = $stmt->execute([$leadsleap_user_id, $leadsleap_list_id, $leadsleap_list_id_referrals, $user_id]);

        if ($result) {
            header("Location: profile.php?leadsleap_saved=1");
            exit;
        } else {
            $errorInfo = $stmt->errorInfo();
            file_put_contents('debug_log.txt', "DB Error: " . print_r($errorInfo, true) . "\n", FILE_APPEND);
            header("Location: profile.php?leadsleap_saved=0");
            exit;
        }
    } else {
        $errorMessage = "Both LeadsLeap User ID and List ID are required!";
    }
}

// ✅ Fetch Branding Settings
$stmt = $pdo->query("SELECT logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch(PDO::FETCH_ASSOC);
$logoImage = $branding['logo_image'] ?? ''; // Default to empty if not set

// ✅ Generate Gravatar URL
$gravatarEmail = strtolower(trim($userData['email']));
$gravatarHash = md5($gravatarEmail);
$gravatarURL = "https://www.gravatar.com/avatar/$gravatarHash?s=150&d=mp"; // Default to 'mp' mystery person if no Gravatar exists

$errorMessage = "";
$successMessage = "";

?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Click Stats and Conversion Tracking</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="assets/css/nav-style.css">

        <style>
    
    body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.container-fluid {
    flex-grow: 1;
}


    /* Ensure the sidebar stays fixed properly */
    .sidebar {
        width: 250px !important;
        min-height: 100vh;
        background-color: #f8f9fa;
    }

    /* Fix the main content so it doesn't shrink */
    .container-fluid {
        flex-grow: 1 !important;
        padding: 20px !important;
    }

    /* Ensure widgets and buttons stay aligned */
    .card {
        border-radius: 10px !important;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
    }

    /* Fix footer width */
    footer {
        width: 100% !important;
    }
    
    /* Floating Copy Notification */
.copy-notification {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background-color: #28a745; /* Green (Success) */
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    font-size: 16px;
    display: none; /* Initially hidden */
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.2);
    z-index: 1000;
    transition: opacity 0.5s ease-in-out;
}

.copy-notification.show {
    display: block;
    opacity: 1;
}

.copy-notification i {
    margin-right: 8px;
}

/* Footer */
.footer {
    background-color: #343a40; /* Dark background */
    color: #ffffff; /* White text */
    text-align: center;
    padding: 15px;
    font-size: 14px;
    width: 100%;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    position: relative; /* Ensures it stays below content */
    margin-top: 20px; /* Adds space above the footer */
}

.rounded-circle {
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #ddd;
    transition: 0.3s;
}
.rounded-circle:hover {
    border-color: #007bff;
}


</style>


</head>
<body>

<!-- Floating Notification -->
<div id="copyNotification" class="copy-notification">
    <i class="fa fa-check-circle"></i> Copied to clipboard!
</div>


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

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


<!-- Sidebar Toggle Button (Mobile Only) -->
<button onclick="toggleSidebar()" class="sidebar-toggle-btn">
    <i class="fas fa-bars"></i>
</button>

<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
        <div class="container-fluid p-4" style="background: #fff; min-height: 100vh;">
        <h2>Click Stats and Conversion Tracking<?php include 'google-translate-widget.php'; ?>
</h2>
<?php
file_put_contents('debug_log.txt', "user_id from userData: $user_id\n", FILE_APPEND);

// ✅ Fetch clicks for the logged-in user
// ✅ Pagination logic
$limit = 20; // max results per page
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Get total count
$stmt = $pdo->prepare("SELECT COUNT(*) FROM clicks WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
$stmt->execute([$user_id]);
$totalClicks = $stmt->fetchColumn();
$totalPages = ceil($totalClicks / $limit);

// Get paginated results
$stmt = $pdo->prepare("SELECT * FROM clicks WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $user_id, PDO::PARAM_INT);
$stmt->bindValue(2, $limit, PDO::PARAM_INT);
$stmt->bindValue(3, $offset, PDO::PARAM_INT);
$stmt->execute();
$clicks = $stmt->fetchAll(PDO::FETCH_ASSOC);
file_put_contents('debug_log.txt', "Clicks found: " . count($clicks) . " for user ID: $user_id\n", FILE_APPEND);

?>

<h3 class="mt-4 mb-3"><i class="fas fa-mouse-pointer"></i> Your Click Stats</h3>



<?php if (count($clicks) > 0): ?>

<?php
// Quick stat summary (last 30 days)
$summaryStmt = $pdo->prepare("
    SELECT 
        COUNT(*) AS total,
SUM(CASE 
    WHEN LOWER(user_agent) LIKE '%mobile%' THEN 1
    WHEN LOWER(user_agent) LIKE '%tablet%' THEN 1
    WHEN LOWER(user_agent) LIKE '%ipad%' THEN 1
    ELSE 0
END) AS mobile,
SUM(CASE 
    WHEN LOWER(user_agent) LIKE '%mobile%' THEN 0
    WHEN LOWER(user_agent) LIKE '%tablet%' THEN 0
    WHEN LOWER(user_agent) LIKE '%ipad%' THEN 0
    ELSE 1
END) AS desktop,

        COUNT(DISTINCT country) AS unique_countries
    FROM clicks
    WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
");
$summaryStmt->execute([$user_id]);
$stats = $summaryStmt->fetch(PDO::FETCH_ASSOC);
?>

<div class="alert alert-info">
    <strong>Last 30 Days Summary:</strong><br>
    Total Clicks: <?= $stats['total'] ?? 0 ?> |
    Mobile: <?= $stats['mobile'] ?? 0 ?> |
    Desktop: <?= $stats['desktop'] ?? 0 ?> |
    Countries Reached: <?= $stats['unique_countries'] ?? 0 ?>
</div>

        <table class="table table-striped table-hover">
<thead class="table-dark">
    <tr>
        <th>#</th>
        <th>When</th>
        <th>Device</th>
        <th>Country</th>
    </tr>
</thead>

            <tbody>
<?php foreach ($clicks as $index => $click): ?>
    <?php file_put_contents('debug_log.txt', "Rendering click row $index\n", FILE_APPEND); ?>

                   <tr>
    <td><?= $index + 1 ?></td>
    <td><?= timeAgo($click['created_at'] ?? '') ?></td>

   <td><?= detectDevice($click['user_agent'] ?? '') ?></td>

<?php
$country = $click['country'] ?? 'Unknown';
$countryCode = $click['country_code'] ?? '';
?>
<td><?= getCountryFlagByCode($countryCode) . htmlspecialchars($country) ?></td>


                <?php endforeach; ?>
            </tbody>
        </table>
<small class="text-muted d-block mt-2">Showing last 30 days of activity. Old data auto-deleted after 500 entries.</small>

<!-- ✅ Pagination Links -->
<nav aria-label="Page navigation">
  <ul class="pagination justify-content-center">
    <?php if ($page > 1): ?>
      <li class="page-item"><a class="page-link" href="?page=<?= $page - 1 ?>">« Prev</a></li>
    <?php endif; ?>

    <?php
$maxVisiblePages = 5;
$startPage = max(1, $page - floor($maxVisiblePages / 2));
$endPage = min($totalPages, $startPage + $maxVisiblePages - 1);

if ($endPage - $startPage < $maxVisiblePages - 1) {
    $startPage = max(1, $endPage - $maxVisiblePages + 1);
}
?>

<?php for ($i = $startPage; $i <= $endPage; $i++): ?>
      <li class="page-item <?= $i === $page ? 'active' : '' ?>">
        <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
      </li>
    <?php endfor; ?>

    <?php if ($page < $totalPages): ?>
      <li class="page-item"><a class="page-link" href="?page=<?= $page + 1 ?>">Next »</a></li>
    <?php endif; ?>
  </ul>
</nav>

        
    </div>
<?php else: ?>
    <div class="alert alert-warning">
        <i class="fa fa-info-circle"></i> No clicks recorded yet. Start sharing your referral link to track activity.
    </div>
<?php endif; ?>

        
 </div>

    </div>
</div>

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>


<script>
function toggleSidebar() {
  const sidebar = document.querySelector('.sidebar');
  const overlay = document.querySelector('.sidebar-overlay');
  const toggleBtn = document.querySelector('.sidebar-toggle-btn');

  sidebar.classList.toggle('open');
  overlay.classList.toggle('show');
  document.body.classList.toggle('sidebar-opened');

  // Optional: toggle button visibility while sidebar is open
  if (document.body.classList.contains('sidebar-opened')) {
    toggleBtn.style.display = 'none';
  } else {
    toggleBtn.style.display = 'block';
  }
}

// ✅ Hide sidebar if top navbar is toggled (on mobile)
document.querySelector('.navbar-toggler')?.addEventListener('click', function () {
  document.querySelector('.sidebar')?.classList.remove('open');
  document.querySelector('.sidebar-overlay')?.classList.remove('show');
  document.body.classList.remove('sidebar-opened');
});
</script>

<?php
// Auto-delete old click records beyond 500 per user
$cleanupStmt = $pdo->prepare("
    DELETE FROM clicks
    WHERE id NOT IN (
        SELECT id FROM (
            SELECT id FROM clicks
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT 500
        ) AS recent_clicks
    )
    AND user_id = ?
");
$cleanupStmt->execute([$user_id, $user_id]);
?>

</body>
</html>
