<?php
require 'element/connection.php';
require 'element/header.php';
require 'element/sidebar.php';

// Assuming session already started in header.php
$sessionId = $_SESSION["user_id"]; // From your login system
$user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$sessionId'"));
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <title><?php echo $row[0]; ?> ||TREE</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
 <link href="../img/logo/logo22222.png" rel="icon"> 

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<link rel="stylesheet" href="assets/styles/style.css">
  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="../assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/vendor/simple-datatables/style.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="../assets/vendor/bootstrap/css/bootstrap.min.css">
    <link href="../assets/vendor/fonts/circular-std/style.css" rel="stylesheet">
   
    <link rel="stylesheet" href="../assets/vendor/fonts/fontawesome/css/fontawesome-all.css">
    <link rel="stylesheet" href="../assets/vendor/charts/morris-bundle/morris.css">
    <link rel="stylesheet" href="..assets/vendor/fonts/material-design-iconic-font/css/materialdesignicons.min.css">

  <!-- Template Main CSS File -->
  <link href="../assets/css/style.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
    <link href="../assets/img/favicon.png" rel="icon">
  <link href="../assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="../assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/vendor/simple-datatables/style.css" rel="stylesheet">
<!-- Add this if not already present -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  <link href="assets/styles/style.css" rel="stylesheet">
   <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
.genealogy-tree ul {
  padding-top: 20px;
  position: relative;
  display: flex;
  justify-content: center;
}

.genealogy-tree li {
  list-style-type: none;
  text-align: center;
  position: relative;
  padding: 20px 5px 0 5px;
}

.genealogy-tree li::before, .genealogy-tree li::after {
  content: '';
  position: absolute;
  top: 0;
  width: 50%;
  height: 20px;
  border-top: 1px solid #ccc;
}


.genealogy-tree li::after {
  right: -50%;
  border-left: 1px solid #ccc;
}

.genealogy-tree li:only-child::before,
.genealogy-tree li:only-child::after {
  display: none;
}

.genealogy-tree li:only-child {
  padding-top: 0;
}

.genealogy-tree .member-view-box {
  background: #fdfdfd;
  border: 1px solid #ccc;
  border-radius: 5px;
  display: inline-block;
  padding: 10px;
  width: 271px;
  box-shadow: 2px 2px 5px rgba(0,0,0,0.1);
}

.member-header span {
  color: #fff;
  padding: 2px 5px;
  font-size: 12px;
  display: block;
  margin-bottom: 5px;
}
        .member-image{
            place-self: anchor-center !important;
        }
.member-image img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.member-footer .name span,
.member-footer .downline span {
  font-size: 12px;
  display: block;
}

.genealogy-tree ul ul::before {
  content: '';
  position: absolute;
  top: 0;
  left: 50%;
  border-left: 1px solid #ccc;
  width: 0;
  height: 20px;
}
        .add-user-box {
    border: 1px dashed #ccc;
    background-color: #f9f9f9;
    cursor: pointer;
    opacity: 0.8;
}
.add-user-box:hover {
    opacity: 1;
    background-color: #eef;
}
  
        
        
        
        
        #hoverCard.user-hover-card-mlm {
  position: fixed; /* Use fixed to anchor to cursor */
  top: 0;
  left: 0;
  z-index: 9999;
  background: #fff;
  border-radius: 20px;
  padding: 20px;
  width: 250px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
  display: none;
  opacity: 0;
  transition: opacity 0.3s ease, transform 0.3s ease;
  transform: scale(0.95);
  pointer-events: none;
}

#hoverCard.hover-show {
  display: block;
  opacity: 1;
  pointer-events: auto;
  transform: scale(1);
}

        .tgl{
            display: inline-block;
    cursor: pointer;
    font-weight: bold;
    font-size: 16px;
    margin-right: 6px;
    color: #444;
    margin-left: 132px;
    margin-top: 174px;
    position: absolute;
    height: 23px;
    z-index: 999;
    border: 1px solid #cccccca8;
        }

        .status-red {
    background-color: #d32f2f !important;
    color: white;
}
.status-yellow {
    background-color: #fbc02d !important;
    color: black;
}
.status-orange {
    background-color: #df9000  !important;
    color: white;
}
.status-green {
    background-color: #388e3c !important;
    color: white;
}
.user-node > ul.children-level {
  display: none;
}
.user-node.expanded > ul.children-level {
  display: block;
}
.bg-info.text-white { background-color: #0dcaf0 !important; }
.badge { font-size: 0.9rem; }
</style>

</head>
<body>
<main id="main" class="main">
  <div class="body genealogy-body genealogy-scroll">



  <div id="message-box" style="margin: 10px 0;"></div>
<!-- Fancy Hover Profile Card -->
<div id="hoverCard" class="user-hover-card-mlm">
  <div class="image">
    <img src="php/bmw.jpg" alt="" class="profile-pic" width="111px" />
  </div>
  <div class="data">
    <h2 id="hoverName">...</h2>
    <span id="hoverID">User ID: </span><br>
    <span id="hoverLevels">Levels: </span><br>
    <span id="hoverWallet">Wallet: ₹</span>
  </div>
</div>


  <!-- Tree output -->
  <div id="genealogy-tree-container">
    <?php include("php/load_tree.php"); ?>
  </div>
<!-- Level Progress Section -->
<div class="card mt-4">
  <div class="card-header bg-primary text-white">
    <h5 class="mb-0"><i class="bi bi-bar-chart-steps me-2"></i>Your Level Progress</h5>
  </div>
  <div class="card-body">
    <?php
    // Helper functions (must be defined before use)
    function getDirectCount($conn, $user_id) {
        $res = $conn->query("SELECT COUNT(*) as cnt FROM users WHERE sponsor_id = $user_id");
        return ($res) ? (int)$res->fetch_assoc()['cnt'] : 0;
    }

    function getUsersAtDepth($conn, $user_id, $depth) {
        $current = [$user_id];
        for ($d = 0; $d < $depth; $d++) {
            $next = [];
            foreach ($current as $uid) {
                $r = $conn->query("SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = $uid");
                if ($r && $row = $r->fetch_assoc()) {
                    if ($row['left_1_id'] != 0) $next[] = $row['left_1_id'];
                    if ($row['left_2_id'] != 0) $next[] = $row['left_2_id'];
                    if ($row['right_1_id'] != 0) $next[] = $row['right_1_id'];
                    if ($row['right_2_id'] != 0) $next[] = $row['right_2_id'];
                }
            }
            $current = $next;
            if (empty($current)) break;
        }
        return ($d == $depth) ? $current : [];
    }

    function getNextUnpaidLevel($conn, $user_id) {
        $paid = [];
        $res = $conn->query("SELECT level FROM level_rewards WHERE user_id = $user_id AND paid = 1");
        while ($row = $res->fetch_assoc()) {
            $paid[] = $row['level'];
        }
        for ($l = 1; $l <= 7; $l++) {
            if (!in_array($l, $paid)) return $l;
        }
        return 8; // all paid
    }

    // Level configuration
    $levels = [
        1 => ['members' => 4,   'amount' => 1000,   'rank' => 'STARTER'],
        2 => ['members' => 16,  'amount' => 1600,   'rank' => 'BRONZE'],
        3 => ['members' => 64,  'amount' => 6500,   'rank' => 'SILVER'],
        4 => ['members' => 256, 'amount' => 28000,  'rank' => 'GOLD'],
        5 => ['members' => 1024,'amount' => 130000, 'rank' => 'PLATINUM'],
        6 => ['members' => 4096,'amount' => 540000, 'rank' => 'DIAMOND'],
        7 => ['members' => 16384,'amount' => 2250000,'rank' => 'BLACK DIAMOND']
    ];

    $uid = $user['user_id'];
    $directs = getDirectCount($conn, $uid);
    $nextLevel = getNextUnpaidLevel($conn, $uid);
    $c1_ok = ($directs >= 4);
    ?>

    <!-- C1 Status -->
    <div class="alert <?php echo $c1_ok ? 'alert-success' : 'alert-warning'; ?>">
      <strong>Directs:</strong> <?php echo $directs; ?> / 4 directs 
      <?php echo $c1_ok ? '✅ Completed' : '❌ Not completed (you must have 4 directs to earn level income)'; ?>
    </div>

    <!-- Level Progress Table -->
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <thead class="table-dark">
          <tr>
            <th>Level</th>
            <th>Rank</th>
            <th>Income</th>
            <th>Required</th>
            <th>Your Users at Depth</th>
            
          </tr>
        </thead>
        <tbody>
          <?php for ($lvl = 1; $lvl <= 7; $lvl++): 
            $required = $levels[$lvl]['members'];
            $usersAtDepth = getUsersAtDepth($conn, $uid, $lvl);
            $countAtDepth = count($usersAtDepth);

            $qualified = 0;
            foreach ($usersAtDepth as $subId) {
                if (getDirectCount($conn, $subId) >= 4) $qualified++;
            }

            // Check if this level is already paid
            $paidRes = $conn->query("SELECT 1 FROM level_rewards WHERE user_id = $uid AND level = $lvl AND paid = 1");
            $isPaid = ($paidRes && $paidRes->num_rows > 0);

            // Determine status class and text
            if ($isPaid) {
                $statusClass = 'bg-success text-white';
                $statusText = '✅ Paid';
            } elseif ($lvl == $nextLevel && $c1_ok && $countAtDepth >= $required && $qualified == $countAtDepth) {
                $statusClass = 'bg-info text-white';
                $statusText = '🎯 Ready to claim';
            } elseif ($lvl == $nextLevel && $c1_ok) {
                $statusClass = 'bg-warning';
                $statusText = '⏳ In progress';
            } else {
                $statusClass = 'bg-secondary text-white';
                $statusText = '🔒 Locked';
            }
          ?>
          <tr>
            <td><?php echo $lvl; ?></td>
            <td><?php echo $levels[$lvl]['rank']; ?></td>
            <td>₹<?php echo number_format($levels[$lvl]['amount']); ?></td>
            <td><?php echo $required; ?></td>
            <td><?php echo $countAtDepth; ?></td>
            
          </tr>
          <?php endfor; ?>
        </tbody>
      </table>
    </div>

    <?php if ($nextLevel <= 7 && $c1_ok): ?>
      <div class="mt-3">
        <strong>Next Level:</strong> Level <?php echo $nextLevel; ?> 
        (requires <?php echo $levels[$nextLevel]['members']; ?>)
      </div>
    <?php endif; ?>
  </div>
</div>
</div>

<!-- Tree toggle & refresh -->
<script src="assets/script/tree.js"></script>

<script>
  // Handle Add Member via AJAX
  $('#add-member-form').on('submit', function(e) {
    e.preventDefault();

    $.ajax({
      type: 'POST',
      url: 'php/add_member.php',
      data: $(this).serialize(),
      success: function(response) {
        $('#message-box').html(response);
        $('#genealogy-tree-container').load('php/load_tree.php');
      },
      error: function() {
        $('#message-box').html('<span style="color:red;">Error adding member.</span>');
      }
    });
  });

  // Handle Search Form via fetch
  document.getElementById('searchForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const id = document.getElementById('search_id').value;

    fetch('php/load_tree.php?parent_id=' + id)
      .then(res => res.text())
      .then(html => {
        document.getElementById('genealogy-tree-container').innerHTML = html;
      })
      .catch(err => console.error('Error loading tree:', err));
  });
</script>
</main>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $('#searchForm').on('submit', function(e) {
    e.preventDefault();
    const id = $('#search_id').val();
    $('#genealogy-tree-container').load('php/load_tree.php?parent_id=' + id);
  });
    $(document).ready(function () {
  $('.genealogy-tree ul').hide();
  $('.genealogy-tree > ul').show();
  $('.genealogy-tree ul.active').show();

  $('.genealogy-tree li').on('click', function (e) {
    var children = $(this).find('> ul');
    if (children.length > 0) {
      children.toggle('fast');
      e.stopPropagation();
    }
  });
});
    

</script>



<script>
// Check for success message in URL
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    
    // Check if user was added successfully
    if (urlParams.has('success') && urlParams.get('success') === '1') {
        const newId = urlParams.get('new_id');
        const newName = urlParams.get('new_name');
        const newPhone = urlParams.get('new_phone') || 'Not provided';
        const placement = urlParams.get('placement');
        const position = urlParams.get('position');
        
        // Format position name for display
        let positionDisplay = '';
        switch(position) {
            case 'left_1_id': positionDisplay = 'Left 1'; break;
            case 'left_2_id': positionDisplay = 'Left 2'; break;
            case 'right_1_id': positionDisplay = 'Right 1'; break;
            case 'right_2_id': positionDisplay = 'Right 2'; break;
            default: positionDisplay = position;
        }
        
        // Show success toast with new user details
        Swal.fire({
            icon: 'success',
            title: '✅ New Member Added!',
            html: `
                <div style="text-align: left; padding: 10px;">
                    <p><strong>👤 Name:</strong> ${decodeURIComponent(newName)}</p>
                    <p><strong>🆔 User ID:</strong> ${newId}</p>
                    <p><strong>📱 Phone:</strong> ${newPhone}</p>
                    <p><strong>📍 Placed under:</strong> User ${placement}</p>
                    <p><strong>📌 Position:</strong> ${positionDisplay}</p>
                </div>
            `,
            showConfirmButton: true,
            confirmButtonText: 'View in Tree',
            confirmButtonColor: '#4154f1',
            timer: 5000,
            timerProgressBar: true,
            didOpen: () => {
                // Highlight the new user in the tree
                setTimeout(() => {
                    const newUserElement = $(`.member-view-box:contains("${newId}")`).first();
                    if (newUserElement.length) {
                        newUserElement.css({
                            'border': '3px solid #4caf50',
                            'box-shadow': '0 0 20px rgba(76, 175, 80, 0.5)',
                            'animation': 'pulse 1s 3'
                        });
                        
                        // Scroll to new user
                        $('html, body').animate({
                            scrollTop: newUserElement.offset().top - 200
                        }, 500);
                        
                        // Remove highlight after 5 seconds
                        setTimeout(() => {
                            newUserElement.css({
                                'border': '',
                                'box-shadow': '',
                                'animation': ''
                            });
                        }, 5000);
                    }
                }, 500);
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Scroll to new user if button clicked
                const newUserElement = $(`.member-view-box:contains("${newId}")`).first();
                if (newUserElement.length) {
                    $('html, body').animate({
                        scrollTop: newUserElement.offset().top - 100
                    }, 500);
                }
            }
        });
        
        // Remove parameters from URL without refreshing
        const newUrl = window.location.pathname;
        window.history.replaceState({}, document.title, newUrl);
    }
    
    // Check for error
    if (urlParams.has('error')) {
        Swal.fire({
            icon: 'error',
            title: '❌ Error',
            text: decodeURIComponent(urlParams.get('error')),
            timer: 3000,
            showConfirmButton: false
        });
        
        // Remove error from URL
        const newUrl = window.location.pathname;
        window.history.replaceState({}, document.title, newUrl);
    }
});

// Add pulse animation
const style = document.createElement('style');
style.innerHTML = `
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.02); }
        100% { transform: scale(1); }
    }
`;
document.head.appendChild(style);
</script>
<script>
const hoverCard = document.getElementById('hoverCard');
let activeTimeout = null;

function showHoverCard(e, name, id, levels, wallet) {
  clearTimeout(activeTimeout); // prevent early hide

  // Set the card info
  document.getElementById('hoverName').innerText = name;
  document.getElementById('hoverID').innerText = 'User ID: ' + id;
  document.getElementById('hoverLevels').innerText = 'Levels: ' + levels;
  document.getElementById('hoverWallet').innerText = 'Wallet: ₹' + wallet;

  // Calculate position near cursor
  let mouseX = e.clientX;
  let mouseY = e.clientY;

  let offsetX = 20; // right of cursor
  let offsetY = -250; // slightly above

  // Position the card
  hoverCard.style.left = (mouseX + offsetX) + 'px';
  hoverCard.style.top = (mouseY + offsetY) + 'px';

  hoverCard.classList.add('hover-show');
}

function hideHoverCard() {
  activeTimeout = setTimeout(() => {
    hoverCard.classList.remove('hover-show');
  }, 150);
}
    
</script>

 <script src="assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/chart.js/chart.min.js"></script>
  <script src="assets/vendor/echarts/echarts.min.js"></script>
  <script src="assets/vendor/quill/quill.min.js"></script>
  <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="assets/vendor/php-email-form/validate.js"></script>

  <!-- Template Main JS File -->
  <script src="assets/js/main.js"></script>

</body>
</html>
