<?php
session_start();
include("script/condb.php");
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Transparent Quantities</title>
<link href="css/styles.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
h1 {
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, "sans-serif";
  color: #FFF;
  font-size: 14px;
  letter-spacing: 1px;
  font-weight: 300;
  text-align: center;
  margin-top: 35%;
}

/* Page Background */
body {
  background: #99b4d1;
  margin: 0;
  font-family: Arial, sans-serif;
}

.project-number {
  word-break: break-word;
  white-space: normal;
  max-width: 140px;
  display: inline-block;
}
</style>

<script>
setTimeout(function(){ 
  document.getElementById('app').style['display'] = 'block';
  document.getElementById('splash').style['display'] = 'none';
}, 5000);
</script>

<script>
function isvalid(){
  var userN = document.form.userN.value;
  var pswd = document.form.pswd.value;
  if (userN.length=="" && pswd.length==""){
    alert("username and pasword field is empty!!");
    return false;
  } else {
    if(userN.length==""){
      alert("username field is empty!!");
      return false;
    }
    if(pswd.length==""){
      alert("password field is empty");
      return false;
    }
  }
}
</script>
</head>

<body>
<div id="app">
<div class="page-wrap-login">
  <div class="login-wrapper">
    <!--ring div starts here-->
    <div class="ring">
      <i style="--clr:#00ff0a;"></i>
      <i style="--clr:#ff0057;"></i>
      <i style="--clr:#fffd44;"></i>
    </div>
    <!--ring div ends here-->
    <div class="pagewrap">
      <div class="left-side">
        <div class="logo"><img src="images/logo.png" width="343" height="50" alt=""/></div>
        <div class="left_bottom">

          <!--<div class="bottom_body">
            Here is a place to write more information about the above header, giving more insight to products and services.
            Also as a medium of advertisement regarding updates and other product features.
          </div>-->
          <div class="bottom-btn"><a href="logout.php">Log Out</a></div>
         
        </div>
      </div>
      
      <div class="right-side-var">
     <div class="profile-image" ><?php
		$sel= "SELECT * FROM upline_app_users where person_id ='{$_SESSION['person_id']}' ";
		$query =mysqli_query($con, $sel);
		$result =mysqli_fetch_assoc($query);
		
		?> Online | Welcome back, <?php echo $result['first_name']; ?></div>
    <div class="projects-display">

        <!-- MOVED BUTTONS ABOVE TABLE (DO NOT CHANGE ANYTHING ELSE) -->
        <div class="splash-btn-sec" style="float:left; margin-right:10px;">
            <a href="#" onclick="openModal('viewprojects.php', true); return false;">View Projects</a>
        </div>

        <div class="splash-btn" style="float:left;">
            <a href="#" onclick="openModal('project-informations.php', true); return false;">Create New Project</a>
        </div>

        <div style="clear:both;"></div>
        <!-- END OF BUTTON MOVE -->

        <div class="project-header">Displaying Created Projects</div>
          <div class="projects-scroll-container" id="scrollBox">
            <table class="projects-table">
              <thead>
                <tr>
                  <th>Project Ref</th>
                  <th>Type</th>
                  <th>Name</th>
                  <th>Date Added</th>
                  <th>Duplicate</th>
                  <th>Delete</th>
                </tr>
              </thead>
              <tbody id="scrollContent">
                <?php
                $sql = "SELECT project_ref, project_type, project_name, date_added 
                        FROM upline_app_project_info 
                        ORDER BY date_added DESC 
                        LIMIT 25";
                $result = $con->query($sql);

                if ($result && $result->num_rows > 0) {
                  while($row = $result->fetch_assoc()) {
                      $ref = htmlspecialchars($row['project_ref']);
                      $type = htmlspecialchars($row['project_type']);
                      $name = htmlspecialchars($row['project_name']);
                      $date = htmlspecialchars($row['date_added']);
                      
                      echo "<tr class='clickable-row' data-href=\"projectedit.php?project_ref={$ref}\">
                              <td class='project-number'>
                                <a href='#' onclick=\"openModal('projectedit.php?project_ref={$ref}'); return false;\" 
                                   style='color:#007bff;text-decoration:none;word-break:break-word;'>{$ref}</a>
                              </td>
                              <td>{$type}</td>
                              <td>{$name}</td>
                              <td>{$date}</td>
                              <td>
                                <a href='#' class='btn-action btn-dup' 
                                   onclick=\"event.stopPropagation(); if(confirm('Duplicate this project and all related records?')) runSilentAction('duplicate_project.php?project_ref={$ref}'); return false;\">Duplicate</a>
                              </td>
                              <td>
                                <a href='#' class='btn-action btn-del' 
                                   onclick=\"event.stopPropagation(); if(confirm('Are you sure you want to delete this project and all related records?')) runSilentAction('delete_project.php?project_ref={$ref}'); return false;\">Delete</a>
                              </td>
                            </tr>";
                  }
                } else {
                  echo '<tr><td colspan="6">No records found</td></tr>';
                }
                ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

<style>
.project-header {
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  text-align: center;
}

/* Scrollable container */
.projects-scroll-container {
  height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: #f4f6f9;
  scroll-behavior: smooth;
   width: 100%;
    box-sizing: border-box;
}

/* Light scrollbar styling */
.projects-scroll-container::-webkit-scrollbar {
  width: 10px;
}
.projects-scroll-container::-webkit-scrollbar-track {
  background: #e6e9ed;
  border-radius: 10px;
}
.projects-scroll-container::-webkit-scrollbar-thumb {
  background-color: #bbb;
  border-radius: 10px;
  border: 2px solid #e6e9ed;
}
.projects-scroll-container::-webkit-scrollbar-thumb:hover {
  background-color: #999;
}

/* Table styling */
.projects-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;   /* NEW: prevents overflow */
  font-size: 13px;
  color: #222;
}


/* Fixed header */
.projects-table thead {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* Table cells */
.projects-table th, .projects-table td {
  padding: 8px 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.projects-table th {
  background: #fff;
  color: #000;
  font-weight: 600;
}

.projects-table tbody tr:nth-child(even) {
  background: #f9fafb;
}
.projects-table tbody tr:nth-child(odd) {
  background: #fff;
}

/* Clickable rows */
.clickable-row {
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.clickable-row:hover {
  background: #e8f0fe !important;
  color: #003366;
}

.btn-action {
  padding: 6px 12px;
  border-radius: 6px;
  color: white;
  text-decoration: none;
  font-size: 13px;
  font-weight: 600;
}

.btn-dup {
  background-color: #10b981;
}
.btn-dup:hover {
  background-color: #059669;
}
.btn-del {
  background-color: #ef4444;
}
.btn-del:hover {
  background-color: #dc2626;
}

/* ===== Modal Styles ===== */
.modal-overlay {
  display: none;
  position: fixed;
  z-index: 1000;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: rgba(0, 0, 0, 0.6);
}
.modal-content {
  position: absolute;
  top: 50%; 
  left: 50%;
  transform: translate(-50%, -50%);

  /* Increased modal size */
  width: 98%;
  height: 98%;

  background: #fff;
  border-radius: 10px;

  /* prevent horizontal scroll */
  overflow-x: hidden;
  overflow-y: hidden;

  box-shadow: 0 0 12px rgba(0,0,0,0.45);
  display: flex;
  flex-direction: column;
}

.modal-header {
  background: #003366;
  color: white;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
}
.modal-header .modal-controls button {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  margin-left: 10px;
  cursor: pointer;
}
.modal-header .modal-controls button:hover {
  color: #ffcc00;
}
#projectFrame {
  flex: 1;
  width: 100%;
  height: 100%;

  /* prevents internal horizontal scroll */
  overflow-x: hidden;
  border: none;
}
</style>

<script>
// === CLICKABLE ROWS ===
document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll(".clickable-row").forEach(function (row) {
    row.addEventListener("click", function (e) {
      if (e.target.classList.contains("btn-action") || e.target.closest(".btn-action")) return;
      const projectRef = this.getAttribute("data-href");
      if (projectRef) openModal(projectRef);
    });
  });
});

// === MODAL FUNCTIONS ===
function openModal(url) {
  const modal = document.getElementById("projectModal");
  const frame = document.getElementById("projectFrame");
  frame.src = url;
  modal.style.display = "block";
}
function closeModal() {
  const modal = document.getElementById("projectModal");
  const frame = document.getElementById("projectFrame");
  frame.src = "";
  modal.style.display = "none";
}

function runSilentAction(url) {
  fetch(url)
    .then(response => {
      if (!response.ok) throw new Error("HTTP " + response.status);
      return response.text();
    })
    .then(text => {
      console.log("Raw server response:", text);

      try {
        const data = JSON.parse(text);
        if (data.status === "success") {
          showToast(`✅ Project duplicated successfully! New Ref: ${data.newPID}\nTotal Records Cloned: ${data.totalCloned}`, "success");
          setTimeout(() => window.location.href = "lander.php", 2500);
        } else {
          showToast("❌ Duplication failed: " + data.message, "error");
        }
      } catch (e) {
        showToast("⚠️ Unexpected server response.", "error");
      }
    })
    .catch(err => {
      showToast("Network or server error: " + err.message, "error");
      console.error(err);
    });
}


function showToast(message, type = "success") {
  const toast = document.getElementById("toast");
  const text = document.getElementById("toast-text");

  text.textContent = message;
  toast.className = `toast-message show toast-${type}`;

  setTimeout(() => {
    toast.className = "toast-message";
  }, 4000);
}

</script>

<!-- === MODAL STRUCTURE === -->
<div id="projectModal" class="modal-overlay">
  <div class="modal-content" id="draggableModal">
    <div class="modal-header">
      <span class="modal-title">Transparent Quantity v0.1</span>
      <div class="modal-controls">
        <button class="modal-minimize" onclick="closeModal()">✖</button>
      </div>
    </div>
    <iframe id="projectFrame" src="" frameborder="0"></iframe>
  </div>
</div>

<!-- === TOAST NOTIFICATION === -->
<div id="toast" class="toast-message hidden">
  <span id="toast-text"></span>
</div>

<style>
.toast-message {
  position: fixed;
  bottom: 30px;
  right: 30px;
  background-color: #003366;
  color: white;
  padding: 15px 25px;
  border-radius: 8px;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
  opacity: 0;
  transition: opacity 0.4s ease, transform 0.4s ease;
  transform: translateY(20px);
  z-index: 9999;
}
.toast-message.show {
  opacity: 1;
  transform: translateY(0);
}
.toast-success {
  background-color: #10b981;
}
.toast-error {
  background-color: #ef4444;
}
</style>

</body>
</html>
