<div class="container">
  <div class="alert fade in" id="notif_box" style="display:none;">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    <strong id="notif" style="font-size:30px;"></strong>
  </div>
</div>

<div class="container">
	<h3>Add New Agent</h3><hr>
    <div class="form-group">
    	<input type="text" class="form-control" id="group_name" name="group_name" placeholder="Enter Group Name" required>
  	</div>

    <div class="form-group">
    	<button type="button" class="btn btn-success" onclick="addNewUser()">Add Agent</button>
  	</div>
	<div class="row">
		<div class="col-md-6">
			<h3>List of currently allowed Agents</h3><hr>
			<ul class="list-group">
				<?php
                    if(count(glob(__DIR__."/users/*")) === 0) {
                        echo 'No users found.';
                    } else {
                        foreach (glob(__DIR__."/users/*") as $filename) {
                            $filename = explode('/', $filename);
                            $filename = end($filename);
                            echo '<li class="list-group-item d-flex justify-content-between align-items-center">'.$filename. '<span class="badge badge-warning badge-pill" onclick="deleteUser('."'$filename'".')">X</span></li>';
                        }
                    }
				?>
			</ul>
		</div>
	</div>
</div>

<style>
.badge-warning {
	background: red;
	cursor: pointer;
}
</style>

<script>
	function addNewUser() {
		var gname = document.getElementById("group_name").value,
			inFolder = 'users',
			path ='/api/add_user?filename='+gname+'&inFolder='+inFolder;
		fetch(path)
		.then(function(response) { return response.json(); })
		.then(function(json) {
			if(json.status=='success') {
				// console.log(json.status);
				// alert(json.msg);
				notification(json.status, json.msg);
				location.reload(true);
			} else notification(json.status, json.msg);
		});
		// console.log(gname);
	}

	function deleteUser(fname) {
		var inFolder = 'users',
			f='/api/delete_user?name='+fname+'&folder=/CONTENT/ROOT_URI/Admin/'+inFolder;
		fetch(f)
		.then(function(response) { return response.json(); })
		.then(function(json) {
			if(json.status=='success'){
				// removeModal(fname);
				// console.log(json.status);
				notification(json.status, json.msg);
				// location.reload(true);
			}
		});
	}

	function notification(res_status, res_txt) {
		var notif_box = document.getElementById('notif_box');
		var notif = document.getElementById('notif');

		notif_box.style.display = 'block';
		if (res_status == 'success') {
			notif_box.classList.add('alert-success');
		} else {
			notif_box.classList.add('alert-danger');
		}
		notif.innerHTML = res_txt;
	}
</script>







<center> <h2>Dedicate Agent to A/C </h2> </center>



<?php
// Update dedicated agent to A/C
if(isset($_POST['agentmail']) && isset($_POST['aaid']) && $_POST['agentmail']!="Select"){

  $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  $sql = "UPDATE `".$GLOBALS['arif_ac']."` SET `AA_AGENT` = '".$_POST['agentmail']."' WHERE `arif_ac`.`AA_ID` = '".$_POST['aaid']."'";
  // if( $result = $conn->query($sql) ) echo $_POST['agentmail'] , $_POST['aaid'], "Successfully Added!";
  $result = $conn->query($sql);
}

function view_list_ac($type) {
  $agentMails='<select name="agentmail"><option>Select</option>';
  if(count(glob(__DIR__."/users/*")) === 0) {
      $agentMails=$agentMails. 'No users found.';
  } else {
      foreach (glob(__DIR__."/users/*") as $filename) {
          $filename = explode('/', $filename);
          $filename = end($filename);
          $agentMails=$agentMails. '<option>'.$filename. '</option>';
      }
  }
  $agentMails=$agentMails."</select>"; //echo $agentMails;
echo '
<div class="container" style="margin-top: 70px;">
<h5>VIEW CUSTOMERS</h5><hr>
</div>
<div class="container">
<table class="table table-striped table-bordered table-hover table-responsive">
  <tr>
    <th>SL</th>
    <th>Type</th>
    <th>AC No</th>
    <th>Name</th>
    <th>Account Creation Date</th>
    <th>Loan Amount</th>
    <th>PHONE</th>
    <th>Balance</th>
    <th>Dedicated Agent</th>
    <th>Dedicate an Agent</th>

  </tr>';
  $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  $sql = "SELECT * FROM `".$GLOBALS['arif_ac']."` WHERE `AA_TYPE`='".$type."' ORDER BY `AA_ID` DESC";
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
      while($row = $result->fetch_assoc()) {
          //$ID=$row["GC_ID"];
          $tt=$row["AA_ID"]-10;
          $date1 = date_create($row["AA_DATE"]);
          $date2 = date_create(date("Y/m/d"));
          $diff = date_diff($date1, $date2);
          if($type === 'Loan'){
            $no_paid_inst = ($row["AA_MATURE_VALUE"] + $row["AA_BAL"]) / $row["AA_INSTALLMENT"];
          } else {
            $no_paid_inst = $row["AA_BAL"] / $row["AA_INSTALLMENT"];
          }
          if ($row["AA_ACTYPE"] == 'D'){$diff = $diff->format("%a"); $diff=(int)$diff;$due_i=$diff-$row["AA_NO_OF_PAYPAID"];} else {$diff=$diff->format("%m"); $diff=(int)$diff;$due_i=$diff-$row["AA_NO_OF_PAYPAID"];}
          echo "
          <tr>
            <td>".$tt."</td>
            <td>".$row["AA_ACTYPE"].",".$row["AA_TYPE"]."</td>
            <td>".$row["AA_ACNO"]."</td>
            <td>".$row["AA_NAME"]."</td>
            <td>".$row["AA_DATE"]."</td>
            <td>".$row["AA_MATURE_VALUE"]."</td>
            <td>".$row["AA_PHONE"]."</td>
            <td>".$row["AA_BAL"]. "</td>
            <td>".$row["AA_AGENT"].'</td>
            <td><form method="post"> <input type="hidden" name="aaid" value="'.$row["AA_ID"].'">'.$agentMails.' <input type="submit" value="Dedicete"></form></td>

          </tr>';
      }
  } else {
      echo "0 results";
  };
  $conn->close();

echo '
</table>
</div>
';
}

view_list_ac('Loan');
view_list_ac('Recurring');
//
// if(isset($_GET['Type']) && $_GET['Type']=="Loan") view_list_ac('Loan');
// if(isset($_GET['Type']) && $_GET['Type']=="Recurring") view_list_ac('Recurring');
// if(isset($_GET['Type']) && $_GET['Type']=="FD") view_list_ac('FD');
?>
