<?php
session_start();
include('includes/config.php');
include('defs.php');

if(strlen($_SESSION['aid'])==0)
  { header('location:index.php');
}

$usr=$_SESSION['uname'];



 ?>

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>GLAKB  | Opening Balance Form</title>

  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="../plugins/fontawesome-free/css/all.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="../dist/css/adminlte.min.css">
  <!--Function Email Availabilty---->

</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
  <!-- Navbar -->
<?php include_once("includes/navbar.php");?>
  <!-- /.navbar -->

  <!-- Main Sidebar Container -->
 <?php include_once("includes/sidebar.php");?>

 
  <div class="content-wrapper">

<?
$result12 = mysqli_query($link, "select Role from user_details where Name='$usr' ");
$row12=  mysqli_fetch_object($result12);
$role = $row12->Role;
if($role=='Operator')
{
$result = mysqli_query($link, "select Role from user_priv where Name='$usr' and Form='Ob' ");
$row=  mysqli_fetch_object($result);
$role = $row->Role;
if($role=='0')
{
{
echo"<center>";
echo"<br><br><br><br><br>";
echo"<img src='users.png' width='160' height='160'><br>";
echo "<font size=6 color=red><b>ACCESS DENIED!</b><br>";
echo "<font size=4 color=darkblue><b>You Do Not Have Permission to View This Page.</b><br>";
goto a;
}
}
}
?> 



<style>
#suggestions {
            border: 2px solid #ccc;
            display: none;
            position: absolute;
            background-color: white;
            width: 300px;
            max-height: 250px;
            overflow-y: auto;
            z-index: 1000;
        }
        #suggestions div {
            padding: 3px;
            cursor: pointer;
        }
        #suggestions div:hover,
        #suggestions .selected {
            background-color: #f0f0f0;
        }



#suggestions1 {
            border: 2px solid #ccc;
            display: none;
            position: absolute;
            background-color: white;
            width: 300px;
            max-height: 250px;
            overflow-y: auto;
            z-index: 1000;
        }
        #suggestions1 div {
            padding: 3px;
            cursor: pointer;
        }
        #suggestions1 div:hover,
        #suggestions1 .selected {
            background-color: #f0f0f0;
        }

        .input-box {
            width: 100%;
            padding: 2px;
            margin-top: 2px;
            margin-bottom: 2px;
            border: 2px solid gainsboro;
            border-radius: 4px;
            font-size: 16px;

        }
#customers {
  font-family: Times-Roman;
  border-collapse: collapse;
  width: 80%;
}

#customers td, #customers th {
  border: 1px solid #4444;
  padding: 4px;
}

#customers tr:nth-child(even){background-color:gainsboro ;}


#customers th {
  padding-top: 8px;
  padding-bottom: 8px;
  text-align: center;
background-color:dodgerblue;
    color: white;
}

#results {
    max-height: 600px;   /* adjust as needed */
    overflow-y: auto;    /* vertical scrollbar */
    border: 1px solid #ccc;
}

 #recordModal {
            display: none;
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }
        #modalContent {
            background: #fff;
            margin: 5% auto;
            padding: 20px;
            width: 1000px;
            border-radius: 8px;
        }
        #searchBox {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            font-size: 25px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }
        
        tr:hover {
            background: #f5f5f5;
            cursor: pointer;
        }
   


</style>   
<link rel="stylesheet" href="css/style.css">
<script language="javascript">

 window.onload= function show()
                        {
                                if(document.voucher.ext.value =="")
                                        {

                                                document.voucher.ext.focus()
                                        }
                                        }
function myFunction() 
{
$x = document.getElementById("gamt").value;
document.getElementById("namt").value=$x;

}

function myFunction1() 
{
$x = document.getElementById("gamt").value;
$y = document.getElementById("itax").value;
$a = document.getElementById("stax").value;
$z=$x-$y-$a;
document.getElementById("namt").value=$z;
}

function myFunction2() 
{
$x = document.getElementById("gamt").value;
$y = document.getElementById("itax").value;
$z = document.getElementById("stax").value;
$a=$x-$y-$z;
document.getElementById("namt").value=$a;
}

function myFunction3() 
{
$x = document.getElementById("gamt").value;
$y = document.getElementById("itax").value;
$z = document.getElementById("stax").value;
$b = document.getElementById("bsts").value;
$c = document.getElementById("otax").value;
$a=$x-$y-$z-$b-$c;
document.getElementById("namt").value=$a;
}


function setValue()
{
        var val = document.getElementById("dt").value;
        document.getElementById("date").value=val;
}
 function formconfirm() {
return confirm("You Clicked the Button. Continue?<? echo "$coursename";?>");
}

function show_cbo11()
                {
                        var val2 = document.getElementById('cash_type').value;
                       
                        location.href = "ob.php?M_Headc="+val2;
                        
                }


                
            
                
                  function processkey(e)
                {
                        var kc = (window.Event?e.which:e.keyCode)
                        if (kc >=48 && kc<= 57 || kc ==8 || kc == 46)
                                return true
                        else
                                return false

     
           }

function openAndPrintPDF() 
{
var pdfWindow = window.open('rep_payments.php?usr=<?php echo $usr ?>', '_blank');
}
///////////////////////////////////////////


function validateForm()
{
if((document.voucher.itemBox.value) == '')
{
alert("Please Enter Head of Accounts!");
document.voucher.itemBox.focus();
return false;
}
if((document.voucher.gamt.value) == '' || (document.voucher.gamt.value) == 0 )
{
alert("Please Enter Amount.");
document.voucher.gamt.focus();
return false;
}


	

return true;
}




//////////////////////////////////////////////////////











                
</script>





<form name="voucher" action="" method="POST" onSubmit = "return  validateForm();">



        <table align="center" id="customers">
       
<tr>
    <th colspan="4"><font size="5">OPENING BALANCE FORM</th>

  </tr>
 


<tr>
    <td>
<b><font size="4" color="black">Press Enter to Search Head:</font></b>
</td>
<td>
  <input type="text" id="itemBox" name="itemBox" id="itemBox" class="input-box" placeholder="Press Enter to search" autocomplete="off" autofocus>
</td>

<td>
  <b><font size="4" color="black">Head Code:</font></b>
</td>
<td>
  <input type="text" id="cid" name="cid" class="input-box" autocomplete="off">
</td>
<tr>





<!-- Modal -->
<div id="recordModal" style="display:none;">
  <div id="modalContent" style="background:#fff;padding:10px;border-radius:10px;width:60%;margin:auto;max-height:400px;overflow:auto;">
    <h3>Search Expense Head</h3>
    <input type="text" id="searchBox" placeholder="Type or press Enter..." autocomplete="off" style="width:100%;padding:8px;margin-bottom:8px;">
    <div id="results" style="max-height:300px;overflow-y:auto;border:1px solid #ccc;"></div>
    <br>
    <button onclick="closeModal()">Close</button>
  </div>
</div>

<script>
  const itemBox = document.getElementById("itemBox");
  const codeBox = document.getElementById("cid");
  const billBox = document.getElementById("bill");
  const modal = document.getElementById("recordModal");
  const searchBox = document.getElementById("searchBox");
  const results = document.getElementById("results");
  let selectedIndex = -1;

  // === Open modal on Enter ===
  itemBox.addEventListener("keydown", e => {
    if (e.key === "Enter") {
      e.preventDefault();
      openModal();
    }
  });

  function openModal() {
    modal.style.display = "block";
    searchBox.value = "";
    results.innerHTML = "<p style='text-align:center;'>Loading all records...</p>";
    selectedIndex = -1;
    searchBox.focus();

    // ✅ Load all records initially
    fetch("search5.php?q=ALL")
      .then(res => res.text())
      .then(data => results.innerHTML = data);
  }

  function closeModal() {
    modal.style.display = "none";
    itemBox.focus();
  }

  // === Live search (Enter or typing) ===
  searchBox.addEventListener("keyup", e => {
    if (["ArrowUp", "ArrowDown", "Enter", "Escape"].includes(e.key)) return;

    let q = searchBox.value.trim();
    if (q.length === 0) q = "ALL"; // ✅ show all when empty

    fetch("search5.php?q=" + encodeURIComponent(q))
      .then(res => res.text())
      .then(data => results.innerHTML = data);
  });

  // === Arrow key navigation ===
  searchBox.addEventListener("keydown", e => {
    const rows = results.querySelectorAll("tr");
    if (!rows.length) return;

    if (e.key === "ArrowDown" || e.key === "ArrowUp") {
      e.preventDefault();
      selectedIndex = (selectedIndex + (e.key === "ArrowDown" ? 1 : -1) + rows.length) % rows.length;
      rows.forEach((r, i) => r.style.backgroundColor = i === selectedIndex ? "#d0ebff" : "");
      rows[selectedIndex].scrollIntoView({ block: "nearest" });
    } else if (e.key === "Enter" && selectedIndex >= 0) {
      e.preventDefault();
      selectRow(rows[selectedIndex]);
    } else if (e.key === "Escape") closeModal();
  });

  // === Select row ===
  function selectRow(row) {
    const code = row.getAttribute("data-code");
    if (!code) return;
    codeBox.value = code;
    closeModal();

    fetch("get_customer.php?id=" + encodeURIComponent(code))
      .then(res => res.json())
      .then(data => {
        itemBox.value = data.name || "";
        codeBox.value = data.code || code;
        gamt.focus();
      });
  }

  results.addEventListener("click", e => {
    const row = e.target.closest("tr");
    if (row) selectRow(row);
  });
</script>

<td><b><font size=4 color=black>Amount:</b></td>
        <?
echo "<td ><b><input type='text' name='gamt' class='input-box' size='16' style='color: black; font-family: Times-Roman; font-size:2' id='gamt' value='0' onkeypress='return processkey(event)' onkeyup='myFunction()' onfocus='this.select()'>";
?>
<td colspan="3">
<tr>    
<td><b><font size=4 color=black>Debit / Credit:</b></td>
<td>
<select name=pmode class='input-box'>
<option value='Debit'>Debit</option>
<option value='Credit'>Credit</option>
</td>
</select>
<td colspan="3">
 <tr>


  <?


$strvoucher= Date("Y-m-d");
if(isset($_POST['strDate']) && !isset($_POST['reset']) )
{
$strvoucher=$_POST['strDate'];
AddDate("<b><font size=4 color=black>Op. Balance Date: </b> &nbsp;", "strDate", $strvoucher, 10, 10, 0);         
}
else
{
AddDate("<b><font size=4 color=black>Op. Balance Date: </b> &nbsp;", "strDate", $strvoucher, 10, 10, 0);         
}
echo "</td>";
  ?>      
<td colspan="3">
<tr>
      <td colspan="4" align="center">

<input type="submit" name="save" value="Save Balance" style="background: none; color:#007BFF; border:2px solid #007BFF; padding:2px 20px; border-radius:5px;">




  <?
                                                 


if(isset($_POST['save']))
{
date_default_timezone_set ("Asia/Karachi");
$the_time = date('d-m-Y (h:i:s a)', time());

$date = strtotime($_POST['strDate']);
$date = date("Y-m-d",$date);

$name = $_POST['itemBox'];
$idd = $_POST['cid'];
$gamt = $_POST['gamt'];
$pmode = $_POST['pmode'];


$result12 = mysqli_query($link, "select Salesman, M_Head from acc_heads where Name='$name' and A_Id='$idd' ");
$row12 =  mysqli_fetch_object($result12);
$mhead = $row12->M_Head;
$sman = $row12->Salesman;




$result = mysqli_query($link, "select max(vch_number) as v_no2 from ledgers ");
$row =  mysqli_fetch_object($result);
$v_no2 = $row->v_no2 + 1;

$cpVch = str_pad($v_no2, 6, "0", STR_PAD_LEFT);
$cpVch = "JV".$cpVch;


$sql1 = "select * from ledgers where A_Id='$idd' and Code='$name' and Details='Opening Balance of the Customer..' ";
$q = $link->query($sql1);
if ($q->num_rows > 0) 
{
echo "<script language='javascript'>";
echo "alert('Customer Op.Balance already exists. Kindly Update it from Customer Edit Menu for Changes.')";
echo "</script>";
goto donothing;
}


if($pmode=='Debit')
{
mysqli_query($link, "insert into ledgers (D_Date, Code, M_Head, Details, Debit, usr, A_Id, Salesman, vch_number, vch, L_Type) values ('$date','$name','$mhead','Opening Balance of the Customer..','$gamt','$usr','$idd','$sman','$v_no2','$cpVch','JV')");

}

elseif($pmode=='Credit')
{
    
mysqli_query($link, "insert into ledgers (D_Date, Code, M_Head, Details, Credit, usr, A_Id, Salesman, vch_number, vch, L_Type) values ('$date','$name','$mhead','Opening Balance of the Customer..','$gamt','$usr','$idd','$sman','$v_no2','$cpVch','JV')");

}





echo "<script language='javascript'>";
echo "alert('Successfully Added!')";
echo "</script>";

$link = "<script>window.open('ob.php','_self')</script>";
echo $link;
donothing:
}
a:
        include "footer.php";
?>
</div>
<!-- ./wrapper -->

<!-- jQuery -->
<script src="../plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- bs-custom-file-input -->
<script src="../plugins/bs-custom-file-input/bs-custom-file-input.min.js"></script>
<!-- AdminLTE App -->
<script src="../dist/js/adminlte.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="../dist/js/demo.js"></script>
<!-- Page specific script -->
<script>
$(function () {
  bsCustomFileInput.init();
});
</script>
</body>
</html>
<?php  ?>