<?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  | Edit Cash Recovery</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='Cash2' ");
$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>
#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;
        }


        .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;
}
</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 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_rec2.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_cash.php?usr=<?php echo $usr ?>', '_blank');
}
///////////////////////////////////////////


function validateForm()
	{
		


if((document.voucher.cash_type.value) == '')
                
{
alert("Please Select Cash Head!");
document.voucher.cash_type.focus();
return false;
}


if((document.voucher.itemBox.value) == '')

{
alert("Please Enter Accounts Head Name!");
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">EDIT CASH RECOVERY VOUCHER</th>

  </tr>
 
<?








$result12 = mysqli_query($link, "select * from edit_vch where c_usr='$usr'" );
while($row12  = mysqli_fetch_object($result12))
{
$inv=$row12->Vch_Number;
$idate=$row12->V_Date;

}
?>
<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:20px;' value='$inv' readonly   />";



echo "</td>";
?>


  
<tr>
                        <td align=left><b><font size=4 color=black>Recovery Received In:</b></td>
                        <td align=left >
                                <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 = "";
                                        
                                        
                                        $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>


<td colspan="2">
<tr>
   <td>
  <b><font size="4" color="black">Search Customer's Title:</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">Customer Code:</font></b>
</td>
<td>
  <input type="text" id="cid" name="cid" class="input-box" autocomplete="off" style="background-color: lightblue;">
</td>


<!-- 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 Account's Title</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>

<tr align="left">
<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)' onfocus= 'this.select()' >";
?>
<td colspan="2">
<tr>
<td align="left"><b><font size=4 color=black>Narration:</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="cr" value="Credit" style="background: lightblue; color:black; border:2px solid #007BFF; padding:2px 20px; border-radius:5px;">
</form>

<form method="post">
<tr>
<td colspan="4">
<?
if(isset($_POST['strDate']) && !isset($_POST['reset']) )
{
AddDate1("<b><font size=4 color=black>Voucher Date: </b> &nbsp;", "strDate", $idate, 10, 10, 0);         
}
else
{
AddDate1("<b><font size=4 color=black>Voucher Date: </b> &nbsp;", "strDate", $idate, 10, 10, 0);         
}
?>
    
<input type="submit" name="save" value="Update Voucher" style="background: lightblue; color:black; 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);


$sql1 = "SELECT * FROM tmp_vch where usr='$usr' ";
$q = $link->query($sql1);
if ($q->num_rows == 0) 
{
echo "<script language='javascript'>";
echo "alert('The Blacnk Voucher Can Not Be Saved!')";
echo "</script>";
goto donot;
}



$result1 = mysqli_query($link, "select * from edit_vch where c_usr='$usr'");
$row1 =  mysqli_fetch_object($result1);
$v_no2 = $row1->Vch_Number;
$vdate = $row1->V_Date;
$auser = $row1->usr;

mysqli_query($link, "delete from ledgers where vch_number='$v_no2'");


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


$result = mysqli_query($link, "select * from tmp_vch where usr='$usr' and Credit!='0.00' order by Id");
while($row = mysqli_fetch_object($result))
{

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


$result12 = mysqli_query($link, "select Pmode, Sum(Credit) as tdebs from tmp_vch where usr='$usr' group by Pmode");
while($row12 = mysqli_fetch_object($result12))
{
$pmode = $row12->Pmode;
$tdebs = $row12->tdebs;

$result13 = mysqli_query($link, "select M_Head, A_Id from acc_heads where Name='$pmode'" );
while($row13  = mysqli_fetch_object($result13))
{
$mhead = $row13->M_Head;
$cid = $row13->A_Id;
}
$dets = "Recovery Received from Customers.";
mysqli_query($link, "insert into ledgers (M_Head, vch_number, vch, A_Id, Code, Details, Debit, D_Date, usr, L_Type, V_Time) values ('$mhead','$v_no2','$cpVch','$cid','$pmode','$dets','$tdebs','$date','$auser','CR','$the_time')");
  }

 

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

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

donot:

        }



?>




</form>
<form method="post">


  <?
                                                 


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'];
$cash = $_POST['cash_type'];


//$result13 = mysqli_query($link, "select M_Head, A_Id from acc_heads where Name='$cash'");
//$row13 =  mysqli_fetch_object($result13);
//$mhead1 = $row13->M_Head;
//$cid1 = $row13->A_Id;



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

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

//$result14 = mysqli_query($link, "select MAX(Id) as ids from tmp_vch");
//$row14 =  mysqli_fetch_object($result14);
//$idd = $row14->ids;
//$rem2 = $rems ." (".$name.")";
//mysqli_query($link, "insert into tmp_vch (M_Head, Code,  Details, Debit, usr, A_Id, Chq) values ('$mhead1','$cash','$rem2','$gamt','$usr','$cid1','$idd')");

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 tmp_vch where Id='$lid'");
$query=mysqli_query($link,"delete from tmp_vch where Chq='$lid'");
if($query){
//unlink($ppicpath);
//echo "<script type='text/javascript'> document.location = 'voucher.php'; </script>";
}
}








?>
</form>
</table>


<form method="post">
<?
if (isset($_POST['update'])) {
$id  = $_POST['id'];
$qty = floatval($_POST['qty']);
mysqli_query($link, "UPDATE tmp_vch SET Credit='$qty' WHERE Id='$id'");
$link = "<script>window.open('cash_rec2.php','_self')</script>";
echo $link;
}


// --- Delete Record ---
if (isset($_POST['delete'])) {
    $id = $_POST['id'];
    mysqli_query($link, "DELETE FROM tmp_vch WHERE Id='$id'");
$link = "<script>window.open('cash_rec2.php','_self')</script>";
echo $link;
  
}


// --- Fetch Data ---
$result = mysqli_query($link, "select * from tmp_vch where usr='$usr' and Credit!='0.00' order by Id");
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
    .table-container {
        max-height: 600px;       /* adjust height limit here */
        overflow-y: auto;        /* adds vertical scrollbar */
        width: 60%;
        border: 1px solid #ccc;
    }

    table { border-collapse: collapse; width: 99%; background: #fff; }
    th, td { border: 1px solid #ccc; padding: 2px 4px; }
    th { background: #333; color: #fff; position: sticky; top: 0; z-index: 1; }
    
    button { padding: 3px 8px; }
    button[name="update"] { display: none; }
</style>

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

  </tr><tr>
<?
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>Category</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Customer Code</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Customer Head</b>";
echo "        </td>";
echo "        <td align=center>";
echo "                <b><font size=4 color=darkblue>Narration</b>";
echo "        </td>";

echo "        <td align=center>";
        echo "                <b><font size=4 color=darkblue>Cr. Amount</b>";
        echo "        </td>";
echo "        <td align=center>";
        echo "                <b><font size=4 color=darkblue>Salesman</b>";
        echo "        </td>";
        
      echo"  </td>";
  echo "        <td align=center>";
        echo "                <b><font size=4 color=darkblue>Action</b>";

      echo"  </td>";

        echo "</tr>";?>

<?php 

$g_total = 0;

                                         $count=0;
                                         $one=1;
while ($row = mysqli_fetch_assoc($result)):
  $count=$one+$count;
    $g_total += $row['Credit'];
    
$cree = floor($row['Credit']);
  ?>
<tr>
<form method="post">
   <input type="hidden" name="id" value="<?= $row['Id'] ?>">
      <td align="center"><?= $count ?></td>
  
     <td align="center"><?= $row['M_Head'] ?></td>
    <td align="center"><?= $row['A_Id'] ?></td>
    <td><?= $row['Code'] ?></td>
      <td><?= $row['Details'] ?></td>
     
     <td align="center">
      <input type="number" step="any" name="qty" value="<?= $cree ?>" 
       onfocus="this.select()" required 
       style="width:100px; 
              text-align:center; 
              background-color:lightblue; 
              color:black; 
              border:none; 
              font-size:20px;">

     <td align="center"><?= $row['Chq'] ?></td>
     
      
    </td>
 
    <td align="center">
        <button type="submit" name="update">Save</button>
        <button type="submit" name="delete" onclick="return confirm('Delete this record?')">Delete</button>
    </td>
</form>
</tr>
<?php endwhile;
 ?>
<tr style="font-weight:bold; background:#f0f0f0;">
    <td colspan="5" align="right"><b>Grand Total:</b></td>
        <td align="center"> <font size=5 ><?= number_format($g_total, 2) ?></td>
    <td colspan="2">
</tr>


</table>
</div>
</body>
</html>



</div>
      


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