<?php
  if($_SESSION['type'] !== 'admin'){
    echo '<script>window.location.href="/Admin/View_AC?Type=Recurring"</script>';
  }
    $conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
    $conn->set_charset("utf8");
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      $user_id = $_POST['user_id'];
      $user_name = $_POST['user_name'] ?? '';
      $user_phone = $_POST['user_phone'] ?? '';
      $type = $_POST['type'] ?? 'agent';
      $comiRate = $_POST['comi_rate'] ?? null;
      $passwordPlain = $_POST['password'] ?? '';

      // Validation
      if (empty($user_name) || empty($user_phone) || empty($passwordPlain)) {
          $error = "All fields are required.";
      } elseif (!preg_match("/^[0-9]{10}$/", $user_phone)) {
          $error = "Invalid phone number format.";
      } else {
          $password = password_hash($passwordPlain, PASSWORD_DEFAULT);

          // Profile Picture Upload
          $profilePicPath = null;
          if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] === UPLOAD_ERR_OK) {
              $uploadDir = __DIR__ . "/picture/";
              if (!file_exists($uploadDir)) {
                  mkdir($uploadDir, 0777, true);
              }
              $fileTmp = $_FILES['profile_pic']['tmp_name'];
              $fileName = time() . "_" . basename($_FILES['profile_pic']['name']);
              $filePath = $uploadDir . $fileName;
              if (move_uploaded_file($fileTmp, $filePath)) {
                  $profilePicPath = "picture/" . $fileName;
              } else {
                  $error = "Failed to upload profile picture.";
              }
          }

          if (!isset($error)) {
              $table = $GLOBALS['arif_users'] ?? 'arif_users';
              $sql = "INSERT INTO `$table` 
                      (user_id, password, type, user_name, user_phone, comi_rate, profile_pic) 
                      VALUES (?, ?, ?, ?, ?, ?, ?)";
              $stmt = $conn->prepare($sql);
              $stmt->bind_param("sssssss", $user_id, $password, $type, $user_name, $user_phone, $comiRate, $profilePicPath);

              if ($stmt->execute()) {
                  $success = "User <strong>{$user_name}</strong> added successfully.";
              } else {
                  $error = "Failed to add user: " . $stmt->error;
              }
              $stmt->close();
          }
      }
    }
    
    $getAgentListsQuery = "SELECT * FROM " . $GLOBALS['arif_users'] . " ORDER BY type, user_id";
    $agentResult = $conn->query($getAgentListsQuery);
    $agentList = [];
    if ($agentResult && $agentResult->num_rows > 0) {
        while ($row = $agentResult->fetch_assoc()) {
            $agentList[] = $row;
        }
    }
?>

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

  <form method="post" enctype="multipart/form-data">
    <div class="row">
      <!-- Left Column -->
      <div class="col-md-6">
        <div class="form-group">
          <label for="user_name">Full Name</label>
          <input type="text" class="form-control" id="user_name" name="user_name" placeholder="Enter Full Name" required>
        </div>

        <div class="form-group">
          <label for="user_phone">Phone Number</label>
          <input type="tel" class="form-control" id="user_phone" name="user_phone" placeholder="Enter Phone Number" required>
        </div>
        <div class="form-group">
          <label for="user_id">User ID</label>
          <input class="form-control" type="text" name="user_id" id="user_id" placeholder="Enter unique User ID"/>
        </div>
        <div class="form-group">
          <label for="type">User Type</label>
          <select onchange="showCommissionField();" class="form-control" id="user-type" name="type" required>
            <option value="">-Select-</option>
            <option value="agent" >Agent</option>
            <option value="admin">Admin</option>
            <option value="bm">BRanch Manager</option>
          </select>
        </div>

        <div class="form-group" id="commission-field" style="display: none;">
          <label for="comi_rate">Commission Rate (%)</label>
          <input type="number" class="form-control" id="comi_rate" name="comi_rate" value="3" placeholder="" required>
        </div>

        <div class="form-group">
          <label for="password">Password</label>
          <input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" required>
        </div>
        <div class="form-group">
          <label for="profile_pic">Profile Picture</label>
          <input type="file" class="form-control" id="profile_pic" name="profile_pic" accept="image/*">
        </div>

        <div class="form-group">
          <button type="submit" class="btn btn-success w-100">Add Agent</button>
        </div>
      </div>

      <!-- Right Column (empty for now) -->
      <div class="col-md-6">
        <!-- You can add more form fields here -->
      </div>
    </div>
  </form>

<div class="container">
    <h3>User Management</h3>
    <hr>
    <table class="table table-striped table-bordered table-hover">
        <thead class="thead-dark">
            <tr>
                <th>ID</th>
                <th>Profile</th>
                <th>User ID</th>
                <th>User Type</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Comi Rate (%)</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($agentList)): ?>
                <?php foreach ($agentList as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['id']); ?></td>
                        <td>
                          <?php if(!empty($user['profile_pic'])):  ?>

                            <img src="/CONTENT/ROOT_URI/Admin/<?php echo $user['profile_pic']; ?>" width="40" height="40" style="border-radius:50%;">
                          <?php else: ?>
                            <span>No Photo</span>
                          <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($user['user_id']); ?></td>
                        <td class="badge-cell">
                            <span class="badge <?php echo $user['type'] === 'admin' ? 'badge-primary' : 'badge-secondary'; ?>">
                                <?php echo htmlspecialchars($user['type']); ?>
                            </span>
                        </td>
                        <td><?php echo htmlspecialchars($user['user_name']); ?></td>
                        <td><?php echo htmlspecialchars($user['user_phone']); ?></td>
                        <td><?php echo htmlspecialchars($user['comi_rate']); ?></td>
                        <td>
                            <a href="edit_user?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-warning">Edit</a>
                            <?php if($user['type'] !== 'admin') { ?>
                                <a href="delete_user?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                             <?php }else{ ?>
                                <a disabled class="btn btn-sm btn-danger">Delete</a>
                             <?php } ?>
                            
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="6" class="text-center">No users found</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php $conn->close(); ?>
	
</div>

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

.badge-cell {
  text-align: center;       /* horizontally center */
}

.badge {
  display: inline-block;
  padding: 0.35em 0.65em;
  font-weight: 600;
  line-height: 1;
  color: #fff;
  white-space: nowrap;
  border-radius: 0.25rem;
}

.badge-primary {
  background-color: #e95420 ; /* Blue */
}

.badge-secondary {
  background-color: #efb73e; /* Gray */
}

</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;
	}

  function showCommissionField(){
    const selectedUserType = document.getElementById('user-type').value;
    const commissionField = document.getElementById('commission-field');
    if(selectedUserType === 'agent'){
      commissionField.style.display = 'block';
    }else{
      commissionField.style.display = 'none';
    }
    

  }
</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');
?>
