<?php
// core configuration
include_once "../../TMS-FILES/config/core.php";
 
// set page title
$page_title="Client Search";
 
// include login checker
$require_login=true;
include_once "../../TMS-FILES/login_checker.php";

// include classes
include_once '../../TMS-FILES/config/database.php';
include_once '../../TMS-FILES/objects/client.php';

$total_rows = 0;
?>


    <!-- include the header  -->
    <?php include_once '../../TMS-FILES/layout_head.php'; ?>

    <!-- include the nav bar  -->
    <?php include_once '../../TMS-FILES/layout_nav.php'; ?>

    <!-- END Nav bar - START Content Code  -->
    
<script language="JavaScript" type="text/javascript">
		
	function valid_data(str) { 
		var pcnt="%" ;
		var fslsh = "/";
		var bslsh = "\\";
		var crt="^" ;
		var brkto="<" ;
		var brktc = ">";
		var equl = "=";
		var dollr  = "$";		

		if (str.indexOf(pcnt)>-1 ||  str.indexOf(fslsh)>-1 || str.indexOf(dollr)>-1 ){ return false ;}  
		if (str.indexOf(bslsh)>-1 ||   str.indexOf(crt)>-1 ){ 	return false ;		} 
		if (str.indexOf(brkto)>-1 ||  str.indexOf(brktc)>-1 ||  str.indexOf(equl)>-1 ){ 	return false ;		} 
		return true ;
	} 

	function fnValidateSearchForm() {
		searchfield = document.frmSearch.srchType.value.trim() ;
		searchterm = document.frmSearch.srchTxt.value.trim() ;
		if (searchfield.length == 0 || searchfield.length > 8) {alert("Please select a valid search type."); return false; }
		else if (searchterm.length == 0 || searchfield.length > 55) {alert("Search text is required and may not exceed 55 characters."); return false; }
		else if (!valid_data(searchterm)) {alert("Search text contains invalid  characters."); return false; }
		else if (!valid_data(searchfield) ){alert("Search Type contains invalid  characters."); return false; }
		else if (document.frmSearch.srchType.value =="dob" && (document.frmSearch.srchTxt.value.length !== 10 
		|| isNaN(document.frmSearch.srchTxt.value.substr(0,4)) 
		|| isNaN(document.frmSearch.srchTxt.value.substr(8,10)) 
		|| !valid_data(document.frmSearch.srchTxt.value))) {
		   alert("DOB must be a valid date, entered in YYYY-MM-DD format");
		   document.frmSearch.srchTxt.focus();
		   return false ;
	} 
		else {	return true;}
		
	}
	
</script>	
    
<?php
//  START POST code here....
//  START POST code here....

if($_POST){

	function test_input($data) {
	  $data = str_replace("%", "", trim($data));
	  $data = stripslashes($data);
	  $data = htmlspecialchars($data);
	  
	  return $data;
	}	 
	
	$search_term	= "";
	$search_field = "";

		$search_field = test_input($_POST["srchType"]);
		$search_term = test_input($_POST["srchTxt"]);
		$errmsg = "";
		if (strlen($search_term)<1 ) { $errmsg = "The search text is blank";
		}
		else{
			switch ($search_field) {
				case "lname":
					if (strlen($search_term) > 25) {$errmsg = "Last Name may not exceed 25 characters";}
					break;
				case "dob":
					if (strlen($search_term) > 10 ||  !DateTime::createFromFormat('Y-m-d', $search_term)) {$errmsg = "DOB must be in YYYY-MM-DD format";}
					break;
				case "phone1":
					if (strlen($search_term) > 25 ) {$errmsg = "Phone number may not exceed 25 characters";}
					break;			
				case "email":
					if (strlen($search_term) > 55 ) {$errmsg = "E-mail may not exceed 55 characters";}
					break;
				case "pc":
					if (strlen($search_term) > 11 ) {$errmsg = "Postal Code may not exceed 11 characters";}
					break;	
				case "business":
					if (strlen($search_term) > 125 ) {$errmsg = "Business Name may not exceed 125 characters";}
					break;						
			}
		}

		if($errmsg !=="") {
			echo "<div class='alert alert-danger text-center'><h4>" . $errmsg . ".  Please try again.</h4></div>";
		} else {
			if(strlen($search_term)>0 && strlen($search_field) >0) {
				// instantiate database and client object
				$database = new Database();
				$db = $database->getConnection();
 
				$client = new Client($db);
				$stmt = $client->search($search_term, $search_field);
				// get row count from search results
				$total_rows=$stmt->rowCount();
			}
		}
}
//  END POST code here....
//  END POST code here....
?>


<div class="my-3 my-md-5">
<div class="container-flex">

<!--   START client Search  Section  -->
<!--   START client Search  Section  -->

<div class="row  mb-5 my-md-5 ml-5 pl-5 pr-5 mr-5" >
<div class="col-md-12 ml-5 pr-5 mr-5" >

<form action="clientSearch.php#results" method="post" id="frmSearch" name="frmSearch" class="form-horizontal"  onsubmit="return fnValidateSearchForm()" >
	<div class="row ">
             <div class="col-sm-12 mt-0 pt-0 ">
				
			<fieldset class="form-fieldset pl-5 pb-5 mb-5 pt-2">
					<legend  >  Search for Client </legend>
				
                    <div class="form-group ml-3 ">
			  
			  
                        <div class="row  pt-0 pb-3">
				
				<div class="col-sm-3 "><label class="form-label" >Select Search Type:</label>
                              <select class="form-control " name="srchType"  width="100px">
					<option value="lname" selected="selected">Last Name</option>
					<option value="dob" >DOB</option>
					<option value="email" >E-mail</option>
					<option value="phone1" >Phone Number</option>
					<option value="pc" >Postal Code</option>
					<option value="business" >Business Name</option>
					</select>
				</div>
				<div class="col-sm-5">
					<label class="form-label" >Enter Search Text:</label><input type="text" class="form-control pt-1 pb-1" name="srchTxt"  id="srchTxt">
                         </div>
				 
			</div>
				<div class="row  pt-0 pb-3"> 
				<div class="col-sm-8 mt-5 mb-0 pt-5 text-center">
					<INPUT  TYPE="submit" class="btn btn-primary btn-sm " VALUE=" Find  Client " name="srchclient" id="srchclient" />
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					<input name="Reset" type="reset" class="btn btn-primary btn-sm " value=" Reset Search Criteria " />
				</div>
			</div>	
     
			</fieldset>
			</div>
	</div>

</form>

</div>   		<!--  END  search form left col   -->

</div>   		<!--  END  search form right col   -->

 		<!--  END  search form row   -->

            <div class="row  text-right pr-5 mr-5">
			<div class="col-12 text-right">
				<div class=' pull-right mb-2 pb-0 pr-5 mr-5 '>
					<i class="fe fe-plus"></i> <a href="clientAdd.php">Add Client</a>
				</div> 
			</div>
		</div>
 <div class="row mb-5 my-md-5 ml-5 pl-5 pr-5 mr-5">
			<div class="col-12  ">
<a name="results"></a> 

                <div class="card pb-3 ml-5  mr-5">
                  <div class="card-header ">
                    <h3 class="card-title  text-light">Client Search Results</h3>
                  </div><div class='alert' ><br><font style='color:red;' >**Note:  Clients in Red</font> indicate client data has been flagged or has flagged transactions.  Please Validate the Client record before adding a transaction.</div>
                  <div class="table-responsive">



 <?php
// display the clients if there are any

if($total_rows>0){

    echo "<table class='table card-table table-vcenter '>";
        echo "<tr>";
            echo "<th scope='col'>Id</th>";
            echo "<th scope='col'>Name</th>";
			echo "<th scope='col'>DOB</th>"; 
			echo "<th scope='col'>E-mail Address</th>";
            echo "<th scope='col'>Address</th>";
			echo "<th scope='col' nowrap>Postal Code</th>";
            echo "<th scope='col'>Phone No.</th>";
			echo "<th scope='col'>Business Name</th>";
            echo "<th scope='col'>&nbsp;</th>";

        echo "</tr>";

       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
 
            extract($row);
			
            echo "<tr scope='row'>";
                echo "<td " .  ($row["blnFlag"]  ? "style='color:red;'" : "") . " >{$id}</td>";
                echo "<td " .  ($row["blnFlag"]  ? "style='color:red;'" : "") . " nowrap>{$lname}" . ", " . "{$fname}</td>";
                echo "<td nowrap>{$dob}</td>";		
                echo "<td >" . substr($row['email'], 0, 30) . (strlen($row['email'])>30 ? "..." : "") . "</td>";				
                echo "<td>{$addr1}</td>";
				echo "<td nowrap>{$pc}</td>";
                echo "<td nowrap>{$phone1}</td>";
				echo "<td nowrap>" . substr($row['business'], 0, 20) . "...</td>";
                echo "<td  nowrap>";
                     // edit client button
         
                    echo "<a href='clientUpdate.php?name={$id}' class='icon' alt='Update this Client' title='Update this Client'>";
                        echo "<i class='fe fe-edit'></i>  ";
                    echo "</a> &nbsp;  &nbsp; ";

                    echo "<a href='txnSearch.php?name={$id}' class='icon' alt='Update/Add Transaction' title='Update/Add Transaction' >";
                        echo "<i class='fe fe-dollar-sign'></i>";
                    echo "</a> &nbsp;  &nbsp; ";					
 
                    // delete client button (not visible if type is admin)
					if ($_SESSION['usertype'] == "Admin" ) {
			?>			
						
<a href='#' class='icon' runat='server' onclick="myFunction(<?=$row['id'] ?> , '<?=str_replace("'","\'",$row['lname'] )?>')"  alt='Remove this Client' title='Remove this Client' >
			       <?php    
		echo "<i class='fe fe-trash' ></i>";
						echo "</a>";
					}
           echo "</td>";
           echo "</tr>";
        }
    echo "</table>";
 
}
 
// or else, tell the client there are no clients to display
else{
    echo "<div class='alert '>No clients found.</div>";
}
?>

                  </div>
                </div>
                      </div>
            </div>		<!--  END  row-col12  -->
          </div>		<!--  END  container  -->
        </div>		<!--  END  md5-3 page section  -->


<!--   END  Display Table   Section  -->
<!--   END  Display Table  Section   -->

      </div>  <!--  END  page-main  -->

    <!-- include the footer  bar -->
    <?php include_once '../../TMS-FILES/layout_foot.php'; ?>

    </div>  <!--  END Page   -->

<script>
function myFunction(id, name) {
 
		var pcnt="%" ;
		var fslsh = "\/";
		var bslsh = "\\";
		var crt="^" ;
		var brkto="<" ;
		var brktc = ">";
		var equl = "=";
		var dollr  = "$";		
		var validname = 1;
		if (name.indexOf(pcnt)>-1 ||  name.indexOf(fslsh)>-1 || name.indexOf(dollr)>-1 ){ validname= 0 ;}  
		if (name.indexOf(bslsh)>-1 ||   name.indexOf(crt)>-1 ){ 	validname=  0 ;		} 
		if (name.indexOf(brkto)>-1 ||  name.indexOf(brktc)>-1 ||  name.indexOf(equl)>-1 ){ 	validname=  0 ;		} 
	
	if(validname==1 )  {	
		var r = confirm("You are about to ARCHIVE all details, Notes, ID History, and Transactions for client " + name + ".  Okay to continue?");
		if (r == true) {
			//  alert("You pressed OK!");
			if(isNaN(id)) {
				alert("Invalid id.  Archive has been cancelled");
			} else {
					window.location.href = "clientDelete.php?id=" + id;
			}
		} else {
			alert("Okay.  Archive cancelled!");
		}
	}else {
		alert("Unexpected characters in client name detected. Archive has been cancelled.");
	}		
}
</script>


  </body>
</html>