<?php
session_start();
require_once '../utils/errorhandler.php';
require_once '../utils/response.php';
require_once '../model/dbclass.php';
require_once '../model/model.php';
require_once '../model/Property.php';

if ($_SESSION['wuseremail'] === null || !isset($_SESSION['wuseremail'])) {
     exit(badRequest(204,'Invalid session data. Proceed to login'));
}

$property = new Property();
$searchtext = (isset($_POST["searchtext"]) && $_POST["searchtext"] !== "") ? $_POST["searchtext"] : "%";
$status = (isset($_POST["status"]) && $_POST["status"] !== "") ? $_POST["status"] : "%";
$id = (isset($_POST["id"]) && intval($_POST["id"]) > 0) ? $_POST["id"] : 0;

if($id == 0){
    $results = $property->executeByQuerySelector("SELECT tenants.*,tenancydocs.tenantid,tenancydocs.document FROM tenants LEFT JOIN tenancydocs ON tenants.id = tenancydocs.tenantid WHERE tenants.lastname LIKE '$searchtext' OR tenants.firstname LIKE '$searchtext' OR tenants.othernames LIKE '$searchtext'");
}else{
    $results = $property->executeByQuerySelector("SELECT tenants.*,tenancydocs.tenantid,tenancydocs.document FROM tenants LEFT JOIN tenancydocs ON tenants.id = tenancydocs.tenantid AND tenants.id = $id");
}
if($results){
    $tenantarray = array();
    foreach($results as $result){
        $resultdependents = $property->executeByQuerySelector("SELECT * FROM dependents WHERE dependents.tenantid = " . $result["id"]);
        $tenantarray[] = array(
            "tenantdata" => $result,
            "dependentdata" => $resultdependents
            );
    }
	echo success($tenantarray,200, "Successful","Successful");
}else{
	exit(badRequest(204,'There may be no record to match this search filters'));
}
?>