<?php include('session.php'); include_once('complaint_hierarchy.php');

if(isset($_POST['action']) && $_POST['action'] == 'get_admin_node_children') {
  $parent_id = (int)$_POST['parent_id'];
  $level = (int)($_POST['level'] ?? 2);
  $children = complaint_child_nodes($conn, $parent_id);
  $html = '';

  if($children && $children->num_rows > 0) {
    $html .= '<div class="form-group complaint-node-group" data-level="'.$level.'">';
    $html .= '<label>'.complaint_html(complaint_admin_level_label($level)).'</label>';
    $html .= '<select class="form-control complaint-node-select" data-level="'.$level.'">';
    $html .= '<option value="">Select</option>';
    while($child = $children->fetch_assoc()) {
      $html .= '<option value="'.$child['id'].'">'.complaint_html($child['name']).'</option>';
    }
    $html .= '</select></div>';
  }

  echo json_encode([
    'html' => $html,
    'has_children' => ($children && $children->num_rows > 0)
  ]);
  exit;
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
	<title>ECIMS ADMIN | UPDATE COMPLAINT LIST</title>
    <?php include('includes/head.php'); ?>
    <style>
      .selected-path {
        background: #f8f9fa;
        border: 1px solid #ddd;
        border-radius: 6px;
        padding: 10px 12px;
        margin-bottom: 16px;
        font-weight: 600;
      }
    </style>
  </head>
  <body>
    <div class="container-scroller">
      <div class="horizontal-menu">
        <?php include('includes/header.php'); ?>
      </div>
      <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
          <div class="content-wrapper">
            <div class="page-header">
              <h3 class="page-title"> Update Complaint List </h3>
            </div>
            <div class="row">
              <div class="col-12 grid-margin stretch-card">
                <div class="card">
                  <div class="card-body">
                      <?php $err = $msg = '';
							if(isset($_POST['submit'])) {
								$details = mysqli_real_escape_string($conn, $_POST['details']);
								$priority = mysqli_real_escape_string($conn, $_POST['priority'] ?? '3');
								$code = mysqli_real_escape_string($conn, $_POST['code']);
								$node_id = (int)$_POST['node_id'];
								$path = complaint_node_path($conn, $node_id);
								$id = mysqli_real_escape_string($conn, $_POST['id']);
                if($path == '') {
                  $err = 'Please select complete complaint path.';
                  $insert = false;
                } else {
								  $complaint_type = (strpos($path, 'E/M') === 0) ? 'EM' : 'BR';
								  if($complaint_type == 'EM') {
									  $priority = complaint_node_priority($conn, $node_id, $priority);
								  }
								  $subdivision = complaint_node_subdivision($conn, $node_id);
								  list($cc_id, $cs_id) = complaint_compat_category_ids($conn, $node_id);
							    $insert = $conn->query("UPDATE complaint_list SET complaint_type='".$complaint_type."',node_id='".$node_id."',cc_id='".$cc_id."',cs_id='".$cs_id."',details='".$details."',priority='".$priority."',code='".$code."',subdivision='".$subdivision."' WHERE cid='".$id."'");
                }
							if($insert){
								$msg = 'Data Updated Successfully.';
							} else if(empty($err)) {
								$err = $conn->error;
							}
						}
						if(!empty($err)){
						  echo "
							<div class='alert alert-danger alert-dismissible'>
							  <h4><i class='fa fa-warning'></i> Error!</h4>
							  ".$err."
							</div>
						  ";
						}
						if(!empty($msg)){
						  echo "
							<div class='alert alert-success alert-dismissible'>
							  <h4><i class='fa fa-check'></i> Success!</h4>
							  ".$msg."
							</div>
						  ";
						}
                        $department = $conn->query("SELECT * FROM complaint_list WHERE cid='".$_GET['id']."'")->fetch_assoc();
                        $selectedChain = complaint_node_chain($conn, $department['node_id'] ?? 0);
                        $selectedPath = complaint_node_path($conn, $department['node_id'] ?? 0);
						?>
                    <form class="forms-sample" method="POST">
                        <input type="hidden" name="id" value="<?php echo $department['cid']; ?>"/>
                      <div class="form-group">
                        <label>Complaint Type</label>
                        <select class="form-control complaint-node-select" data-level="1" required>
                          <option value="">Select</option>
                          <?php
                          $rootSelected = $selectedChain[0]['id'] ?? '';
                          $nodes = complaint_root_nodes($conn);
                          while($node = $nodes->fetch_assoc()) {
                          ?>
                          <option value="<?php echo $node['id']; ?>" <?php if($rootSelected == $node['id']) {echo 'selected';} ?>><?php echo complaint_html($node['name']); ?></option>
                          <?php } ?>
                        </select>
                      </div>
                      <div id="nodeSelects">
                        <?php
                        for($i = 1; $i < count($selectedChain); $i++) {
                          $parentId = (int)$selectedChain[$i - 1]['id'];
                          $level = $i + 1;
                          $children = complaint_child_nodes($conn, $parentId);
                        ?>
                          <div class="form-group complaint-node-group" data-level="<?php echo $level; ?>">
                            <label><?php echo complaint_html(complaint_admin_level_label($level)); ?></label>
                            <select class="form-control complaint-node-select" data-level="<?php echo $level; ?>">
                              <option value="">Select</option>
                              <?php while($child = $children->fetch_assoc()) { ?>
                                <option value="<?php echo $child['id']; ?>" <?php if($selectedChain[$i]['id'] == $child['id']) {echo 'selected';} ?>><?php echo complaint_html($child['name']); ?></option>
                              <?php } ?>
                            </select>
                          </div>
                        <?php } ?>
                      </div>
                      <input type="hidden" name="node_id" id="node_id" required value="<?php echo (int)($department['node_id'] ?? 0); ?>">
                      <div class="selected-path" id="selectedPath"><?php echo complaint_html($selectedPath != '' ? $selectedPath : 'No complaint path selected'); ?></div>
                      <div class="form-group">
                        <label for="details">Complaint Detail</label>
                        <input type="text" class="form-control" required name="details" value="<?php echo $department['details']; ?>" id="details" placeholder="Complaint Detail">
                      </div>
                      <div class="form-group">
                        <label for="code">Code</label>
                        <input type="text" class="form-control" required name="code" id="code" value="<?php echo $department['code']; ?>" placeholder="Code">
                      </div>
                      <div class="form-group">
                        <label for="priority">Priority</label>
                        <select class="form-control" name="priority" id="priority">
                          <option value="1" <?php if($department['priority'] == '1') {echo 'selected';} ?>>1</option>
                          <option value="2" <?php if($department['priority'] == '2') {echo 'selected';} ?>>2</option>
                          <option value="3" <?php if($department['priority'] == '3') {echo 'selected';} ?>>3</option>
                        </select>
                      </div>
                      <button type="submit" name="submit" class="btn btn-primary me-2">Submit</button>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>
		  <?php include('includes/footer.php'); ?>
        </div>
      </div>
    </div>
    <?php include('includes/foot.php'); ?>
    <script>
      $(document).ready(function(){
        function rebuildPath() {
          var parts = [];
          $('.complaint-node-select').each(function(){
            var text = $(this).find('option:selected').text();
            if($(this).val() !== '') {
              parts.push(text);
            }
          });
          $('#selectedPath').text(parts.length ? parts.join(' / ') : 'No complaint path selected');
        }

        $(document).on('change', '.complaint-node-select', function(){
          var current = $(this);
          var nodeId = current.val();
          var nextLevel = parseInt(current.data('level'), 10) + 1;

          $('.complaint-node-group').filter(function(){
            return parseInt($(this).data('level'), 10) >= nextLevel;
          }).remove();

          $('#node_id').val('');
          rebuildPath();

          if(nodeId === '') {
            return;
          }

          $.ajax({
            url: '',
            type: 'POST',
            dataType: 'json',
            data: {
              action: 'get_admin_node_children',
              parent_id: nodeId,
              level: nextLevel
            },
            success: function(response){
              if(response.has_children) {
                $('#nodeSelects').append(response.html);
              } else {
                $('#node_id').val(nodeId);
              }
              rebuildPath();
            }
          });
        });

        $('.forms-sample').on('submit', function(e){
          if($('#node_id').val() === '') {
            e.preventDefault();
            alert('Please select complete complaint path.');
          }
        });

        rebuildPath();
      });
    </script>
  </body>
</html>
