<?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  | Journal Voucher</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='JV' ");
$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>

        .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 GetDetail1(str) {
            if (str.length == 0) {
                document.getElementById("ext").value = "";
                return;
            }
            else {
  
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function () {
                      if (this.readyState == 4 && 
                            this.status == 200) {
                          
                        var myObj = JSON.parse(this.responseText);
                          
                        document.getElementById
                            ("ext").value = myObj[0];
                          
                                            }
                };
  
                // xhttp.open("GET", "filename", true);
                xmlhttp.open("GET", "dupi1.php?strnoc=" + str, true);
                  
                // Sends the request to the server
                xmlhttp.send();
            }
        } 
function GetDetail2(str) {
            if (str.length == 0) {
                document.getElementById("searchBox1").value = "";
                return;
            }
            else {
  
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function () {
                      if (this.readyState == 4 && 
                            this.status == 200) {
                          
                        var myObj = JSON.parse(this.responseText);
                          
                        document.getElementById
                            ("searchBox1").value = myObj[0];
                          
                                            }
                };
  
                // xhttp.open("GET", "filename", true);
                xmlhttp.open("GET", "dupi2.php?strnoc=" + str, true);
                  
                // Sends the request to the server
                xmlhttp.send();
            }
        } 
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 = "cash.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('v_print_direct.php?usr=<?php echo $usr ?>', '_blank');
}
///////////////////////////////////////////


function validateForm()
	{
		


if((document.voucher.ext.value) == '')
                
        {
alert("Please Enter Accounts Code!");
document.voucher.ext.focus();

                        return false;
                }


	if((document.voucher.searchBox1.value) == '')
		
	{
			alert("Please Enter Accounts Head Name!");
document.voucher.searchBox1.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">JOURNAL VOUCHER</th>

  </tr>
 
<?
$result12 = mysqli_query($link, "select MAX(vch_number) as inv from ledgers" );
while($row12  = mysqli_fetch_object($result12))
{
$inv=$row12->inv+1;
}
?>
<td colspan="4" align="right"><b><font size=4 color="black">Voucher#</b>
<?

echo "<input type='text' id='strinv' name='strinv' size='5' style='color: black; font-family: Times-Roman; background-color: lightblue; font-size:25px;' value='$inv' readonly   />";



echo "</td>";
?>


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

<td>
  <b><font size="4" color="black">Account Code:</font></b>
</td>
<td>
  <input type="text" id="cid" name="cid" class="input-box" autocomplete="off" style="background-color: lightblue;">
</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 Head of Accounts</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("search7.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("search7.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 colspan=3><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)' onfocus='this.select()'  onkeyup='myFunction()'>";
?>

<tr>
<td align="left"><b><font size=4 color=black>Remarks (If any):</b></td>
                        <td align="left" colspan="3"><input type="text" name="strrem" class="input-box"  size="87" onkeydown="return tab(event)" /></td>
                        
                </tr>

                
                


      <td colspan="4" align="center">

<input type="submit" name="dr" value="Debit" style="background: none; color:#007BFF; border:2px solid #007BFF; padding:2px 20px; border-radius:5px;">
<input type="submit" name="cr" value="Credit" style="background: none; color:#007BFF; border:2px solid #007BFF; padding:2px 20px; border-radius:5px;">
</form>

<form method="post">
<tr>
    <td colspan="4">
<?
$strvoucher= Date("Y-m-d");
if(isset($_POST['strDate']) && !isset($_POST['reset']) )
{
$strvoucher=$_POST['strDate'];
AddDate1("<b><font size=4 color=black>Voucher Date: </b> &nbsp;", "strDate", $strvoucher, 10, 10, 0);         
}
else
{
AddDate1("<b><font size=4 color=black>Voucher Date: </b> &nbsp;", "strDate", $strvoucher, 10, 10, 0);         
}
?>
    
<input type="submit" name="save" value="Save Voucher" 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);
$tst1 = $t_cr;
$tst2 = $t_dr;
$sum = $t_dif;
$result1 = mysqli_query($link, "select sum(Debit-Credit) as bal from temp_vch where usr='$usr'");
while($row1 = mysqli_fetch_object($result1))
{
$tbal = $row1->bal;
}

if ($tbal != 0)
{
echo "<script language='javascript'>";
echo "alert('Debit and Credit Sides are not Equal.')";
echo "</script>";
goto donot;
}




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

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



                $result = mysqli_query($link, "select * from temp_vch where usr='$usr' order by Id");
                while($row = mysqli_fetch_object($result))
                {
                            if($row->Debit=='0.00')
                            {
           

  mysqli_query($link, "insert into ledgers (M_Head, vch_number, vch, A_Id, Code, Details, Credit, D_Date, usr, L_Type, V_Time, Chq, Pmode) values ('$row->M_Head','$v_no2','$jvVch','$row->A_Id','$row->Code','$row->Details','$row->Credit','$date','$row->usr','JV','$the_time','$row->Chq','$row->Pmode')");

  }
                            if($row->Credit=='0.00')
                            {



  mysqli_query($link, "insert into ledgers (M_Head, vch_number, vch, A_Id, Code, Details, Debit, D_Date, usr, L_Type, V_Time, Chq, Pmode) values ('$row->M_Head','$v_no2','$jvVch','$row->A_Id','$row->Code','$row->Details','$row->Debit','$date','$row->usr','JV','$the_time','$row->Chq','$row->Pmode')");
}
                     
                }


mysqli_query($link, "delete from temp_vch where usr='$usr'");
echo "<script language='javascript'>";
echo "alert('Successfully Done!')";
echo "</script>";

$link = "<script>window.open('voucher.php','_self')</script>";
echo $link;

donot:

        }



?>




</form>
<tr>
<td colspan="5" align="right">
<span class="icon text-white-50">
<i class="fas fa-book"></i>
</span>
<button class="btn btn-info btn-icon-split" onclick="openAndPrintPDF()"><span class="text">VIEW VOUCHER</span></button>



  <?
                                                 


if(isset($_POST['dr']))
        {
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'];
$rems = $_POST['strrem'];


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

 mysqli_query($link, "insert into temp_vch (M_Head, Code,  Details ,Debit , usr, A_Id, Chq, Pmode) values ('$mhead','$name','$rems','$gamt','$usr','$idd','$chq','$pmode')");

echo "<script language='javascript'>";
echo "alert('01 Record Saved Successfully.')";
echo "</script>";


}



if($_GET['action']=='delete'){
$lid=intval($_GET['tid']);
//$profilepic=$_GET['profilepic'];
//$ppicpath="teacherspic"."/".$profilepic;
$query=mysqli_query($link,"delete from temp_vch where Id='$lid'");
if($query){
//unlink($ppicpath);
//echo "<script type='text/javascript'> document.location = 'voucher.php'; </script>";
}
}









if(isset($_POST['cr']))
        {
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'];
$rems = $_POST['strrem'];


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

 mysqli_query($link, "insert into temp_vch (M_Head, Code, Details ,Credit , usr, A_Id, Chq, Pmode) values ('$mhead','$name','$rems','$gamt','$usr','$idd','$chq','$pmode')");

echo "<script language='javascript'>";
echo "alert('01 Record Saved Successfully.')";
echo "</script>";


}

?>
</form>
</table>


<form method="post">

<table align="center" id="customers">
<br>       
<tr>
    <th colspan="8"><font size="4">TRANSACTION DETAILS</th>

  </tr>


<?
$result = mysqli_query($link, "select * from temp_vch where usr='$usr' order by Id");
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>S.No.</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Accounts Category</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Accounts Code</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Accounts Head</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Remarks</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Dr. Amount</b>";
echo "        </td>";
echo "        <td align=center>";
        echo "                <b><font size=4 color=darkblue>Cr. Amount</b>";
        echo "        </td>";
        
      echo"  </td>";
  echo "        <td align=center>";
        echo "                <b><font size=4 color=darkblue>Action</b>";

      echo"  </td>";

        echo "</tr>";
                                         $count=0;
                                         $one=1;
                                         
                                        while($row = mysqli_fetch_object($result))
                                        {
$count=$one+$count;
$t_dr=$row->Debit+$t_dr;
$t_cr=$row->Credit+$t_cr;
$t_dif=$t_dr-$t_cr;
echo "<td align=center><font size=4 color=black>$count</td>";
echo "<td align=center><font size=4 color=black>$row->M_Head</td>";
echo "<td align=center><font size=4 color=black>$row->A_Id</td>";
echo "<td align=center><font size=4 color=black>$row->Code</td>";
echo "<td align=center><font size=4 color=black>$row->Details</td>";
echo "<td align=center><font size=4 color=black>$row->Debit</td>";
echo "<td align=center><font size=4 color=black>$row->Credit</td>";
echo "<td align=center>";

?>


<a href="voucher.php?action=delete&&tid=<?php echo $row->Id; ?>" style="color:red;" title="Delete Entry" onclick="return confirm('Do you really want to delete this entry?');"><i class="fa fa-trash" aria-hidden="true"></i> </a>

<?
echo "</tr>";
}
echo "<td align=center colspan=5>";
echo "<b><font size=3 color=darkblue>Grand Totals / Difference</b>";
echo "<td align=center><font size=4 color=black><b>$t_dr</b></td>";

echo "<td align=center><font size=4 color=black><b>$t_cr</b></td>";
echo "<td align=center><font size=4 color=black><b>$t_dif</b></td>";
                

?>

</form>
</table>             


<?
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  ?>