<?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  | Cash Payment</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='Cash' ");
$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 = "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('rep_payments.php?usr=<?php echo $usr ?>', '_blank');
}
///////////////////////////////////////////


function validateForm()
	{
		




if((document.voucher.cash_type.value) == '')
		
	{
			alert("Please Select Cash Type First!");
document.voucher.cash_type.focus();

			return false;
		}

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">AMOUNT PAYMENT 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   />";



$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);         
}
echo "</td>";
?>


  
<tr>
                        <td align=left><b><font size=4 color=black>Payment Given From:</b></td>
                        <td align=left colspan="2">
                                <select class="form-control" name="cash_type" id="cash_type" style=font-size="16" onchange="show_cbo11()">
                                <option value="">select</option>
                                <?php 
                                if(isset($_GET['M_Headc']))
                                        {
                                                $M_Headc = $_GET['M_Headc'];
                                                
                                                
                
                                        }
                                else                        
                                        $M_Headc = "";
                                        
                                        //include('config.php');
                                        $result = mysqli_query($link, "select Name from acc_heads where M_Head='Assets' order by Name");
                                        while($row  = mysqli_fetch_object($result))
                                        {
                                                        if($M_Headc == $row->Name)
                                                        {
                                                                echo "<option value=\"$row->Name\" selected=\"selected\">$row->Name</option>";
                                                        }        
                                                        else
                                                        {
                                                                echo "<option value=\"$row->Name\">$row->Name</option>";
                                                        }
                                        }
                                ?>
                                </select>


<?
$rst = MySQLi_Query($link, "Select Details from acc_heads where Name='$M_Headc'");

while($rt = mysqli_fetch_array($rst))
{
$det=$rt['Details'];
}
echo "<td align=right colspan=1><b><input type='text' class='input-box' name='desc' size='10' style='color: black; font-family: Times-Roman; background-color: lightblue; font-size:2' id='desc' value='$det' >";

?>


<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()'>";
?>
<tr>    
<td><b><font size=3 color=black>Mode of Payment:</b></td>
<td>
<select name=pmode class='input-box'>
<option value='NIL'>NIL</option>
<option value='By Cheque'>By Cheque</option>
<option value='By Cash'>By Cash</option>
<option value='Online'>Online</option>
<option value='Others'>Others</option>

</select>
<td><b><font size=4 color=black>Cheque No. (If any):</b></td>
<td colspan="1"><input type="text" name="chq" class="input-box" size="25" /></td>
</tr>

<tr>                
<td><b><font size=4 color=black>Remarks:</b></td>
<td colspan="3"><input type="text" name="rem" class="input-box" size="25" /></td>
<tr>                


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

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

<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['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'];

$fhead = $_POST['cash_type'];
$gamt = $_POST['gamt'];
$chq = $_POST['chq'];
$pmode = $_POST['pmode'];
$rems = $_POST['rem'];

$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 = "CP".$cpVch;



                        
$result13 = mysqli_query($link, "select A_Id from acc_heads where Name='$fhead'");
$row13 =  mysqli_fetch_object($result13);
$aid = $row13->A_Id;
                        
$result11 = mysqli_query($link, "select A_Id, M_Head from acc_heads where Name='$party'");
$row11 =  mysqli_fetch_object($result11);
$party_id = $row11->A_Id;
$party_mh = $row11->M_Head;

//$rems="Payment for Expense Code-".$idd;                            
  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 ('Assets','$v_no2','$cpVch','$aid','$fhead','$rems','$gamt','$date','$usr','CP','$the_time','$chq','$pmode')");


$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 ledgers (M_Head, vch_number, vch, A_Id, Code, Details ,Debit ,D_Date, usr, L_Type, V_Time, Chq, Pmode) values ('$mhead','$v_no2','$cpVch','$idd','$name','$rems','$gamt','$date','$usr','CP','$the_time','$chq','$pmode')");




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

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

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