<?php
include '../../connection.php';

if (isset($_POST['removed_organization_person'])) {
	$org_id = $_POST['id'];

	$query = "DELETE FROM tbl_organizational_structure WHERE organization_id = '$org_id' ";
	$query_result = $conn->query($query);
}

if (isset($_POST['load_organization_person'])) {

	echo 
	'
	<ul class="list-group">
	';
	$query = " SELECT 
			            tbl_organizational_structure.organization_id,
			            tbl_organizational_structure.user_id,
			            tbl_organizational_structure.position,
			            tbl_organizational_structure.status,
			            tbl_organizational_structure.date_created,
			            tbl_user.first_name,
			            tbl_user.middle_name,
			            tbl_user.last_name
			        FROM tbl_organizational_structure
			        LEFT JOIN tbl_user ON tbl_organizational_structure.user_id = tbl_user.user_id";
			        $result = $conn->query($query);

			        foreach ($result as $key => $row) {
			        	  $fullname = $row['last_name'].','.$row['first_name'].' '.$row['middle_name'];
			        	echo ' 
							  <li class="list-group-item"> <button class="btn btn-danger btn-sm remove-person" data-id="'.$row['organization_id'].'" align="end"><i class="fa fa-times-circle" aria-hidden="true"></i></button> '.$fullname.' - ('.$row['position'].')</li>
							  
							';
			        }

			        	echo 
						'
						</ul>
						';
}

if (isset($_POST['fetch_officials'])) {
    header("Content-Type: application/json");

    $query = "
        SELECT 
            tbl_organizational_structure.organization_id,
            tbl_organizational_structure.user_id,
            tbl_organizational_structure.position,
            tbl_organizational_structure.status,
            tbl_organizational_structure.date_created,
            tbl_user.first_name,
            tbl_user.middle_name,
            tbl_user.last_name
        FROM tbl_organizational_structure
        LEFT JOIN tbl_user ON tbl_organizational_structure.user_id = tbl_user.user_id
        ORDER BY FIELD(position, 'Barangay Captain', 'Barangay Secretary', 'Barangay Treasurer', 'Kagawad 1', 'Kagawad 2', 'Kagawad 3', 'Kagawad 4', 'Kagawad 5', 'Kagawad 6', 'Kagawad 7', 'SK Chairperson')
    ";

    $query_result = $conn->query($query);
    $officials = [];

    while ($row = $query_result->fetch_assoc()) {
        $fullname = $row['first_name'] . ' ' . $row['middle_name'] . ' ' . $row['last_name'];
        $officials[] = [
            'id' => $row['organization_id'],
            'name' => $fullname,
            'position' => $row['position']
        ];
    }

    echo json_encode($officials);
    exit();
}

if (isset($_POST['adding_organization'])) {
	$officials = $_POST['officials'];
	$position = strtoupper($_POST['position']);

	$query = "INSERT INTO tbl_organizational_structure (`user_id`, `position`) VALUES ('$officials', '$position')";
	$query_result =$conn->query($query);
}
 ?>