<?php 
include '../../connection.php';
 ?>
<div class="card">
	<div class="card-header">
		<button class="btn btn-primary btn-md" data-toggle="modal" data-target="#add-official-position"><i class="fa fa-plus-circle"></i> Add Record</button>
	</div>
	<div class="body">
		<div class="row">
			<div class="col-lg-4">
				<h4 class="text-center">OFFICIALS</h4>
			<div id="person"></div>
			</div>
				<div class="col-lg-8">
					<h4 class="text-center">ORGANIZATIONAL STRUCTURE</h4>
				<div id="chart_div"></div>
			</div>
		</div>
		
	</div>
</div>


<!-- Modal -->
<div class="modal fade" id="add-official-position" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add officials <i class="fa fa-users"></i></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
        	<label>Choose Person</label>
        	<select class="js-example-basic-single form-control" name="state" id="officials" style="width: 100%;">
			  <option value="" selected>--select--</option>
		
			<?php 
        	$query = "SELECT * FROM tbl_user";
        	$query_result = $conn->query($query);

        	foreach ($query_result as $key => $row) {
        		echo '<option value="'.$row['user_id'].'">'.$row['last_name'].', '.$row['first_name'].' '.$row['middle_name'].'</option>';
        	}
        	?>
			</select>
        	
        </div>

        <div class="mb-3">
        	<label>Position</label>
        	<select class="js-example-basic-single" name="state" id="position" style="width: 100%;">
        		 <option value="" selected>--select--</option>
				  <option value="Captain">Barangay Captain</option>
				  <option value="Kagawads">Barangay Kagawads</option>
				  <option value="Secretary">Barangay Secretary</option>
				  <option value="Treasurer">Barangay Treasurer</option>
                  <option value="Keeper">Barangay Record Keeper</option>
				  <option value="Chairperson">SK  Chairperson</option>
		</select>
        </div>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" onclick="add_person()">Save <i class="fa fa-save"></i></button>
      </div>
    </div>
  </div>
</div>

<script>

	$(document).on('click', '.remove-person',function(){
		let id = $(this).data("id");
		swal({
  title: "Are you sure?",
  text: "Once deleted, you will not be able to recover this data file!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  if (willDelete) {
  	$.ajax({
		method: 'post',
		url: 'query/organization_query.php',
		data:{
			"removed_organization_person": 1,
			"id": id
		},
		success: function(res){
			$('#person').html(res);
			load_person();
			drawChart();
		}
	});
    swal("Poof! Your data file has been deleted!", {
      icon: "success",
    });
  } else {
    swal("Your data file is safe!");
  }
});
		
	});
	load_person();
function load_person(){
	$.ajax({
		method: 'post',
		url: 'query/organization_query.php',
		data:{
			"load_organization_person": 1
		},
		success: function(res){
			$('#person').html(res);
            $('#add-official-position').modal('hide');
		}
	})
}
function add_person(){
	let officials = $('#officials').val();
	let position = $('#position').val();

	if (officials === "" || position === "") {
		swal({
		  title: "Oops!",
		  text: "You missed some input field!",
		  icon: "warning",
		});
		return;
	}
	$.ajax({
		method: 'post',
		url: 'query/organization_query.php',
		data:{
			"adding_organization": 1,
			"officials": officials,
			"position": position
		},
		success: function(res){
            swal({
              title: "Success!",
              text: "You added a person!",
              icon: "success",
            });
			drawChart();
			load_person();
		}
	});

}

$(document).ready(function() {
    $('.js-example-basic-multiple').select2();
});
$(document).ready(function() {
    $('.js-example-basic-single').select2({
    	dropdownParent: $('#add-official-position'),
    	theme: 'classic',
    });
});

google.charts.load('current', { packages: ["orgchart"] });
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    $.ajax({
        method: 'POST',
        url: 'query/organization_query.php',
        data: { fetch_officials: 1 },
        dataType: 'json',
        success: function (res) {
            if (!res || res.length === 0) {
                $("#chart_div").html("<div class='alert alert-warning'>No officials found.</div>");
                return;
            }

            // Create the DataTable
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Name');
            data.addColumn('string', 'Manager');
            data.addColumn('string', 'ToolTip');

            let rows = [];

            // 🔍 Find officials
            let captain   = res.find(o => o.position === "CAPTAIN");
            let secretary = res.find(o => o.position === "SECRETARY");
            let treasurer = res.find(o => o.position === "TREASURER");
            let keeper    = res.find(o => o.position === "KEEPER");
            let sk        = res.find(o => o.position === "CHAIRPERSON");
            let kagawads  = res.filter(o => o.position.includes("KAGAWAD"));

            // ✅ Captain (Root)
            if (captain) {
                rows.push([
                    { v: captain.name, f: `${captain.name}<div style='color:green;font-style:italic'>${captain.position}</div>` },
                    '',
                    captain.position
                ]);
            }

            // ✅ Secretary
            if (secretary) {
                rows.push([
                    { v: secretary.name, f: `${secretary.name}<div style='color:red;font-style:italic'>${secretary.position}</div>` },
                    captain ? captain.name : '',
                    secretary.position
                ]);
            }

            // ✅ Treasurer
            if (treasurer) {
                rows.push([
                    { v: treasurer.name, f: `${treasurer.name}<div style='color:red;font-style:italic'>${treasurer.position}</div>` },
                    captain ? captain.name : '',
                    treasurer.position
                ]);
            }

            // ✅ Record Keeper
            if (keeper) {
                rows.push([
                    { v: keeper.name, f: `${keeper.name}<div style='color:orange;font-style:italic'>${keeper.position}</div>` },
                    captain ? captain.name : '',
                    keeper.position
                ]);
            }

            // ✅ Kagawads (attach under Secretary if exists, else under Captain)
            kagawads.forEach(k => {
                rows.push([
                    { v: k.name, f: `${k.name}<div style='color:blue;font-style:italic'>${k.position}</div>` },
                    secretary ? secretary.name : (captain ? captain.name : ''),
                    k.position
                ]);
            });

            // ✅ SK Chairperson (attach under Treasurer if exists, else under Captain)
            if (sk) {
                rows.push([
                    { v: sk.name, f: `${sk.name}<div style='color:purple;font-style:italic'>${sk.position}</div>` },
                    treasurer ? treasurer.name : (captain ? captain.name : ''),
                    sk.position
                ]);
            }

            // 📊 Draw Chart
            data.addRows(rows);
            var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
            chart.draw(data, { allowHtml: true });
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error:", error);
            $("#chart_div").html("<div class='alert alert-danger'>Failed to load chart.</div>");
        }
    });
}


</script>