<?php
session_start();
$block_redirect = true;

// Check if user is logged in
if (isset($_COOKIE['techwire'])) {
    include 'includes/database.inc.php';
    include 'includes/config.inc.php';
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="<?= $_MODE ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $_TITLE ?></title>

    <!-- Styles -->
    <link href="../assets/bootstrap/css/bootstrap.<?= $_THEME ?>.css" rel="stylesheet">
    <!--<link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.arcpunk.css">-->
    <link href="../assets/autocomplete.css" rel="stylesheet">
    <link href="../assets/css/fontawesome.css" rel="stylesheet">
    <link href="../assets/css/brands.css" rel="stylesheet">
    <link href="../assets/css/solid.css" rel="stylesheet">
    <link href="../assets/custom.css" rel="stylesheet">
    <link href="../assets/customcss.css" rel="stylesheet">
    <link href="../assets/bs-stepper.min.css" rel="stylesheet">

    <!-- Favicon -->
    <link rel="apple-touch-icon" sizes="180x180" href="../assets/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../assets/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../assets/favicon-16x16.png">
    <link rel="manifest" href="assets/manifest.json">

    <!-- Scripts -->
    <script src="../assets/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/guided.tour.js"></script>
    <script src="../assets/autocomplete.js"></script>

</head>
<style>
a.disabled {
    pointer-events: none;
    cursor: default;
}
.well { height: 100vh; }
#filedrag {
    display: block;
    font-weight: bold;
    text-align: center;
    padding: 1em 0;
    margin: 1em 0;
    color: #555;
    border: 2px dashed #555;
    border-radius: 7px;
    cursor: default;
}
#filedrag.hover {
    color: #44697c;
    border-color: #44697c;
    border-style: solid;
}
/* Remove number input spinners */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
input[type=number] { -moz-appearance: textfield; }
</style>
<script>
function loadContent(page,query,locale,extra)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5 
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(locale).innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET",page+".php?"+query+extra,true);
xmlhttp.send();
}


// ?
var option= {
	animation: true,
	delay: 2000
}


// Deprecated?
function toasted(toaster) {
	var myAlert = document.getElementById('toastframe');
	var toastAlert = new bootstrap.Toast(myAlert, option);
	toastAlert.show();
}

// Sidebar Tooltip
function tooltip(tipped) {
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
  })
	tooltipList.show();
}

// Delete Confirm
function confirmDelete() {
	if (document.getElementById('delete').value != "DELETE") {
		document.getElementById('deletebtn').disabled = true;
	} else {
		document.getElementById('deletebtn').disabled = false;
	}
}

// Toggle Popover
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})

// AutoLoad Onboarding
<?php if($_ONBOARD == 'OTHER'){ ?>
function onboard(){
const myModal = new bootstrap.Modal(document.getElementById('Onboard'))
myModal.show()
}
<?php } ?>

// AutoLoad Whats New
<?php if($_WHATSNEW == 'OTHER'){ ?>
function onboard(){
const myModal = new bootstrap.Modal(document.getElementById('WhatNew'))
myModal.show()
}
<?php } ?>

// Call to Toast
function toast() {
  var toastElList = [].slice.call(document.querySelectorAll('.toast'))
  var toastList = toastElList.map(function(toastEl) {
    return new bootstrap.Toast(toastEl)
  })
  toastList.forEach(toast => toast.show()) 
}

// Filter Functions
function filter() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("filterInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("filterTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

// Check if INPUT is empty
function nullInput(input,button) {
	 if(document.getElementById(input).value==="") { 
            document.getElementById(button).disabled = true; 
        } else { 
            document.getElementById(button).disabled = false;
        }
    }


// Open Help Window
function HelpDoc(page) {
  window.open("https://docs.techwire.cc/"+page,"_blank","height=1000,width=1000,left=150,top=250");
}

// Open Service Orders in their own window
function ServiceOrder(project, id) {
	var ht = 400;
	var wd = 580;
	var features = "top=150,left=150,width=" + (screen.width - wd) * .5 + ",height=" + (screen.height - ht) * .5;
  window.open("https://beta.techwire.cc/forms/service.order.php?project="+project+"&case="+id,"_blank", features);
}


// Check Online
function isOnline() {
  var x = "<div class='toast-header'><strong class='me-auto text-danger'>Offline</strong><button type='button' class='btn-close' data-bs-dismiss='toast' aria-label='Close'></button></div><div class='toast-body' id='toast'>You are not connected to the the database!</div>";
  if(navigator.onLine == false) {
	  document.getElementById("toast").innerHTML = x;
  var toastElList = [].slice.call(document.querySelectorAll('.toast'))
  var toastList = toastElList.map(function(toastEl) {
    return new bootstrap.Toast(toastEl)
  })
  toastList.forEach(toast => toast.show()) 
	}
}


// Autocomplete
function autoComplete(users, email, id) {
var user_list = users.split(",");
var email_list = email.split(",");
var id_list = id.split(",");
autocomplete(document.getElementById("myAuto"), document.getElementById("autoid"), user_list, email_list, id_list); 
}


// Search Autofocus
function searchFocus(page,query,locale,extra,tag)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5 
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(locale).innerHTML=xmlhttp.responseText;
    }
    const el = document.getElementById(tag);
      if (el) {
        el.focus();
      }
  }
xmlhttp.open("GET",page+".php?"+query+extra,true);
xmlhttp.send();

}

// Drag and Drop Kanban
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
    const handle = ev.target;
    if (!handle.classList.contains('drag-handle')) return;

    const card = handle.closest('.kanban-card');
    if (!card) return;

    ev.dataTransfer.setData("text/plain", card.id);
    ev.dataTransfer.effectAllowed = "move";

    // 👇 Use the full card as the drag image
    const rect = card.getBoundingClientRect();
    ev.dataTransfer.setDragImage(
        card,
        rect.width / 2,
        rect.height / 2
    );
}

function drop(ev, page, query, locale) {
    ev.preventDefault();

    // Get dragged element
    const draggedId = ev.dataTransfer.getData("text");
    const draggedEl = document.getElementById(draggedId);
    if (!draggedEl) return;

    // Find the dropzone (closest parent with class)
    const dropzone = ev.target.closest('.kanban-dropzone');
    if (!dropzone) return;

    // Prevent dropping on itself
    if (draggedEl.contains(dropzone)) return;

    // Append the dragged card
    dropzone.appendChild(draggedEl);

    // AJAX call to update status
    const url = `${page}.php?${query}${encodeURIComponent(draggedId)}`;
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            if (document.getElementById(locale)) {
                document.getElementById(locale).innerHTML = xhr.responseText;
            }
        }
    };
    xhr.open("GET", url, true);
    xhr.send();
}

function dragOverBorder(ev, id) {
  ev.preventDefault(); // MUST allow drop
  const zone = document.getElementById(id);
  if (zone) {
	zone.style.background = 'rgba(10,180,205,.25)';
    zone.style.border = '2px dashed #41DFF4';
    zone.style.color = '#41DFF4';
    console.log('drag over', id); // test
  }
}

function dragLeaveBorder(ev, id) {
  const zone = document.getElementById(id);
  if (zone) {
	zone.style.background = 'none';
    zone.style.border = '2px dashed #10363B';
    zone.style.color = '#10363B';
    console.log('drag leave', id); // test
  }
}

function initKanbanDragHandles() {
    document.querySelectorAll('.kanban-card').forEach(card => {
        card.addEventListener('dragstart', e => {
            if (!e.target.classList.contains('drag-handle')) {
                e.preventDefault();
            }
        });
    });
}

</script>
<body onload="onboard()" onclick="isOnline()">

<iframe class="border-0 shadow-none h-100" style="position:absolute; bottom:0; right:20; display:none;" src="" name="toastframe" id="toastframe"></iframe>

<!-- Sidebar -->
<div id="sidebar"><?php include 'includes/sidebar.inc.php'; ?></div>


<!-- Body -->
<div class="container-fluid" id="body">
  <div class="row ms-5">
    <div id="projects" class="col-sm-12" style="padding:0em 2em 0em 6em;">
      <?php if ($_STATUS !== 'Disabled') include 'forms/projects.current.php'; ?>
    </div>
  </div>
</div>

<!-- Shared Modals -->
<?php include 'includes/modals.inc.php'; ?>

<!-- Toast -->
<div class="toast-container position-fixed bottom-0 end-0 p-3 m-4">
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true" id="toast"></div>
</div>

<!-- Agents -->
<div class="d-none" id="tasker"></div>
<div class="d-none" id="mailer"></div>
<div id="debugger"></div>

<?php 
if ($_STATUS === 'Pending') include 'includes/status.pending.php'; 
if ($_STATUS === 'Disabled') include 'includes/status.disabled.php'; 
if ($_ROLE === 'Demo' && $_STATUS !== 'Pending' && $_STATUS !== 'Disabled') include 'includes/status.demo.php'; 
?>

<!-- Scripts -->
<script src="../assets/bootstrap/js/tooltip.js"></script>
<script src="../assets/js/main.js"></script> <!-- (👉 Move your inline JS here for cleaner code) -->

</body>
</html>

<?php 
} else { // Not logged in
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Techwire</title>

    <!-- Styles -->
    <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/fontawesome.css" rel="stylesheet">
    <link href="assets/css/brands.css" rel="stylesheet">
    <link href="assets/css/solid.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@3">
    <link rel="manifest" href="assets/manifest.json">

    <!-- Scripts -->
    <script src="assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</head>
<script>
function loadContent(page,query,locale,extra)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5 
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(locale).innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET",page+".php?"+query+extra,true);
xmlhttp.send();
}

</script>
<body>
    <video src="assets/background.webm" class="position-fixed w-100 h-100" style="object-fit:cover;top:0;left:0;" autoplay loop muted></video>
    <div id="content"><?php include 'login.php'; ?></div>
</body>
</html>
<?php } ?>
