<?
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  | Customer Details</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='Add-Cust' ");
$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;
}
}
}


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


              ?>
              <html>
<head>
<style>
#customers {
  font-family: Times-Roman;
  border-collapse: collapse;
  width: 80%;
}

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

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


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



 #suggestions {
            border: 1px solid #ccc;
            display: none;
            position: absolute;
            background-color: white;
            width: 250px;
            max-height: 150px;
            overflow-y: auto;
            z-index: 1000;
        }
        #suggestions div {
            padding: 1px;
            cursor: pointer;
        }
        #suggestions div:hover,
        #suggestions .selected {
            background-color: #f0f0f0;
        }
</style>   
<link rel="stylesheet" href="css/style.css">
<script language="javascript" type="text/javascript">

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

                                                document.voucher.name.focus()
                                        }
                                        }
                                        
function formconfirm() {
return confirm("Do You want to Continue?<? echo "$coursename";?>");
}
function openAndPrintPDF() 
{
var pdfWindow = window.open('rep_custs.php?usr=<?php echo $usr ?>', '_blank');
}

function processkey(e) {
    var kc = (window.Event ? e.which : e.keyCode);

    // Allow digits (48–57), backspace (8), dot (46), and minus (-) (45)
    if ((kc >= 48 && kc <= 57) || kc == 8 || kc == 46 || kc == 45)
        return true;
    else
        return false;
}


function validateForm()
{

if((document.voucher.name.value) == '')
{
alert("Please Enter Title First!");
document.voucher.name.focus();
return false;
}


if((document.voucher.cname.value) == '')
{
alert("Please Enter Contact Person!");
document.voucher.cname.focus();
return false;
}



if((document.voucher.ctype.value) == '')
{
alert("Please Select Customer Type!");
document.voucher.ctype.focus();
return false;
}

if((document.voucher.searchBox.value) == '')
{
alert("Please Select City Information!");
document.voucher.searchBox.focus();
return false;
}

if((document.voucher.dued.value) == '' || (document.voucher.dued.value) == 0 )
{
alert("Please Enter Due Days!");
document.voucher.dued.focus();
return false;
}

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

return true;
}




  </script>


 <table align="center" id="customers">
       
<tr>
    <th colspan="4"><font size="5">ADD CUSTOMER INFORMATION</th>

  </tr>               
 
<?
$result = mysqli_query($link, "SELECT MAX(SNO) as fno FROM acc_heads WHERE M_Head='Customer' ");
while($row = mysqli_fetch_object($result))
{
$fno = $row->fno;
}
$fno1 = $fno+1;

$result420 = mysqli_query($link, "select M_Id from mheads where Name='Customer'");
$row420 =  mysqli_fetch_object($result420);
$cde1 = $row420->M_Id;

$ac_code = str_pad($fno1, 4, "0", STR_PAD_LEFT);
$fcode=$cde1."-".$ac_code;
 ?>

<td colspan="4">
<b><font size=3 color="black">Accounts-ID:</b>
<input type='text' size='6' name="strid" id='strid' style='color: black; font-family: Times-Roman; background-color: lightblue; font-size:20px;' value="<?php echo $fcode ?>" readonly >


<tr>
<td width="200"><b><font size=3 color="black">Customer Title:</b></td>
<td><input type="text" name="name" size="30" onkeydown="return tab(event)"  /></td>

<td width="200"><b><font size=3 color="black">Contact Person:</b></td>
<td><input type="text" name="cname" size="30" onkeydown="return tab(event)"  /></td>
<tr>
<td width="200"><b><font size=3 color="black">Contact Number:</b></td>
<td><input type="text" name="cont" size="30" onkeydown="return tab(event)"  /></td>


 <td align=left><b><font size=3 color=black>Customer Type:</b></td>
                        <td align=left>
                                <select class="form-control" name="ctype" id="ctype" style=font-size="16" >
                                <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 Distinct Title from customer_type order by Title");
                                        while($row  = mysqli_fetch_object($result))
                                        {
                                                        if($M_Headc == $row->Title)
                                                        {
                                                                echo "<option value=\"$row->Title\" selected=\"selected\">$row->Title</option>";
                                                        }        
                                                        else
                                                        {
                                                                echo "<option value=\"$row->Title\">$row->Title</option>";
                                                        }
                                        }
                                ?>
                                </select>
                                <tr>
<td><b><font size=3 color="black">Target Warehouse:</font></b></td>
<td>
<select class="form-control" name=waree>
<option value='QUETTA'>QUETTA</option>
<option value='LAHORE'>LAHORE</option>
<option value='KARACHI'>KARACHI</option>
</select>


<td><b><font size=3 color="black">Province:</font></b></td>
<td>
<select class="form-control" name=prov>
<option value='BALOCHISTAN'>BALOCHISTAN</option>
<option value='PUNJAB'>PUNJAB</option>
<option value='SINDH'>SINDH</option>
<option value='KPK'>KPK</option>

</select>
<tr>
<td width="240"><b><font size=3 color="black">Search City:</b></td>
<td colspan="1">

    <input type="text" id="searchBox" name="searchBox" placeholder="Click to search..." autocomplete="off" onkeyup="GetDetail1(this.value)" onkeydown="return event.key !== 'Enter';" >
    <div id="suggestions"></div>

    <script>
        const searchBox = document.getElementById("searchBox");
        const suggestions = document.getElementById("suggestions");
        let selectedIndex = -1;

        searchBox.addEventListener("click", fetchSuggestions);
        searchBox.addEventListener("keyup", function(e) {
            const items = suggestions.querySelectorAll("div");

            if (e.key === "ArrowDown") {
                selectedIndex = (selectedIndex + 1) % items.length;
                updateSelection(items);
            } else if (e.key === "ArrowUp") {
                selectedIndex = (selectedIndex - 1 + items.length) % items.length;
                updateSelection(items);
            } else if (e.key === "Enter" && selectedIndex > -1) {
                searchBox.value = items[selectedIndex].innerText;
                suggestions.style.display = "none";
            } else {
                fetchSuggestions();
            }
        });

        function updateSelection(items) {
            items.forEach((item, i) => {
                item.classList.toggle("selected", i === selectedIndex);
            });
        }

        function fetchSuggestions() {
            const query = searchBox.value;
            fetch(`s_town.php?q=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    suggestions.innerHTML = "";
                    data.forEach(name => {
                        const div = document.createElement("div");
                        div.textContent = name;
                        div.onclick = () => {
                            searchBox.value = name;
                            suggestions.style.display = "none";
                        };
                        suggestions.appendChild(div);
                    });
                    suggestions.style.display = data.length ? "block" : "none";
                    selectedIndex = -1;
                });
        }
    </script>




<td width="200"><b><font size=3 color="black">Address:</b></td>
<td colspan="3"><input type="text" name="adr" size="30" onkeydown="return tab(event)"  /></td>
<tr>

<td width="200"><b><font size=3 color="black">NTN No.:</b></td>
<td><input type="text" name="ntn" size="30" onkeydown="return tab(event)"  /></td>


<td width="200"><b><font size=3 color="black">STRN:</b></td>
<td><input type="text" name="strn" size="30" onkeydown="return tab(event)"  /></td>
<tr>


<td>
<b><font size=3 color="black">Due Days:</b>

<?
echo "<td align=left><b><input type='text' name='dued' size='15' style='color: black; font-family: Times-Roman; background-color: lightblue; font-size:2' id='dued' value='0' onkeypress='return processkey(event)'>";

?>

<td>
<b><font size=3 color="black">Invoice Credit Limit:</b>

<?
echo "<td align=left><b><input type='text' name='clmt' size='15' style='color: black; font-family: Times-Roman; background-color: lightblue; font-size:2' id='clmt' value='0' onkeypress='return processkey(event)'>";

?>
<tr>

<td align=left><b><font size=3 color=black>Salesman:</b></td>
                        <td align=left>
                                <select class="form-control" name="salesman" id="salesman" style=font-size="16" >
                                <option value="">select</option>
                                <?php 
                                if(isset($_GET['Sman']))
                                        {
                                                $Sman = $_GET['Sman'];
                                                
                                                
                
                                        }
                                else                        
                                        $Sman = "";
                                        
                                        //include('config.php');
                                        $result = mysqli_query($link, "select Distinct Name from acc_heads where M_Head='Salesman' order by Name");
                                        while($row  = mysqli_fetch_object($result))
                                        {
                                                        if($Sman == $row->Name)
                                                        {
                                                                echo "<option value=\"$row->Name\" selected=\"selected\">$row->Name</option>";
                                                        }        
                                                        else
                                                        {
                                                                echo "<option value=\"$row->Name\">$row->Name</option>";
                                                        }
                                        }
                                ?>
                                </select>      

<td><b><font size=3 color="black">Opening Balance:</b></td>
<?
echo "<td align=left><b><input type='text' name='opbal' size='15' style='color: black; font-family: Times-Roman; background-color: lightblue; font-size:2' id='opbal' value='0' onkeypress='return processkey(event)'>";

?>


<tr>
    <td colspan="4" align="center">
<input type="submit" name="save" value="Save Entry" style="background: none; color:#007BFF; border:2px solid #007BFF; padding:2px 20px; border-radius:5px;">
</table>
</form>

<form method="post">

 <table align="center" id="customers">
       

  <td colspan="2" align="right">
<input type="submit" name="search" value="Search" style="background: none; color:#007BFF; border:2px solid #007BFF; padding:2px 20px; border-radius:5px;">


<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">Open Customer List</span></button>

 <?

       

if(isset($_POST['search']))
{
$link1 = "<script>window.open('editview.php','_self')</script>";
echo $link1;
}




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

$name = $_POST['name'];
$cname = $_POST['cname'];
$cont = $_POST['cont'];
$waree = $_POST['waree'];
$ctype = $_POST['ctype'];
$prov = $_POST['prov'];
$city = $_POST['searchBox'];
$ntn = $_POST['ntn'];
$strn = $_POST['strn'];

$adr = $_POST['adr'];

$sman = $_POST['salesman'];
$dued = $_POST['dued'];
$clmt = $_POST['clmt'];
$opbal = $_POST['opbal'];


$sql1 = "SELECT * FROM acc_heads where Name='$name' ";
$q = $link->query($sql1);
if ($q->num_rows == 1) 
{
echo "<script language='javascript'>";
echo "alert('Customer Name already exists!')";
echo "</script>";
goto donothing;
}


 
mysqli_query($link, "insert into acc_heads (Name, M_Head, Contact_No, C_Person, Adress, NTN1, City, Ctype, addby, addon, Active, SNO, M_Id, A_Id, Warehouse, Province, STRN, Dued, Salesman, C_Limit) values ('$name','Customer','$cont','$cname','$adr','$ntn','$city','$ctype','$usr','$the_time','Y','$fno1','$cde1','$fcode','$waree','$prov','$strn','$dued','$sman','$clmt')");

if($opbal>=0)
{
mysqli_query($link, "insert into ledgers (D_Date, Code, M_Head, Details, Debit, usr, A_Id, Salesman) values ('$edate','$name','Customer','Opening Balance of the Customer..','$opbal','$usr','$fcode','$sman')");

}

if($opbal<0)
{
    $nopbal = $opbal * -1;
mysqli_query($link, "insert into ledgers (D_Date, Code, M_Head, Details, Credit, usr, A_Id, Salesman) values ('$edate','$name','Customer','Opening Balance of the Customer..','$nopbal','$usr','$fcode','$sman')");

}


echo "<script language='javascript'>";
echo "alert('Information added Successfully!')";
echo "</script>";
$link1 = "<script>window.open('add_cust.php','_self')</script>";
echo $link1; 
donothing:
}
           
                 



 echo "</center>";
  echo "
                                </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  ?>