<?php 
session_start();
include '../../connection.php';

if (isset($_POST['adding_schedule'])) {
    $sched_trans_id = $_POST['sched_trans_id'];
    $date_settle = $_POST['date_settle'];

    $check = "SELECT * FROM tbl_transaction_schedule WHERE UniqueID = '$sched_trans_id'";
    $check_result = $conn->query($check);

    if ($check_result->num_rows > 0) {
        echo "Transaction Already Scheduled!";
    }else{
        $query = "INSERT INTO tbl_transaction_schedule (`UniqueID`,`settle_date`,`date_created`) VALUES ('$sched_trans_id','$date_settle',CURDATE())";
        $query_result = $conn->query($query);
         echo "Transaction Schedule successfully!";
    }

    
}

if (isset($_POST['submitting_reports'])) {
    $transaction = $_POST['transaction'];
    $description = $_POST['description'];
    $id = $_SESSION['user_id'];
    $check_exist = "SELECT * FROM tbl_reports WHERE UniqueID = '$transaction'";
    $check_result = $conn->query($check_exist);

    if ($check_result->num_rows > 0) {
       echo "Transaction already exist!";
    }else{
          $query = "INSERT INTO tbl_reports (user_id, UniqueID, notes) VALUES ('$id', '$transaction', '$description')";
          $query_result = $conn->query($query);

          if ($query_result) {
            $update_transaction = "UPDATE SET status = 'Settled' WHERE UniqueID = '$transaction'";
            $update_result = $conn->query($update_transaction);
              echo "Reports submitted successfully!";
          }
    }

   
}

if (isset($_POST['updating_complaints_assigned'])) {
  $id = $_POST['id'];
  $status = $_POST['status'];

  $query = "UPDATE tbl_assignment SET status = '$status' WHERE assignment_id = '$id'";
  $query_result = $conn->query($query);
}

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

    $id = $_SESSION['user_id'];
    $status = $_POST['status'] ?? 'all';
    $date = $_POST['date'] ?? '';
    $search = $_POST['search'] ?? '';

    $query = "
        SELECT 
            t.UniqueID,
            t.resident_id,
            t.respondent,
            t.incident_address,
            t.complaint_type_id,
            t.description,
            t.status AS transaction_status,
            t.incident_date,
            t.date_created,
            t.supported_evidence,

            r.first_name AS res_fname,
            r.middle_name AS res_mname,
            r.last_name AS res_lname,
            r.email,
            r.address,
            r.contact,

            c.complain_name,

            a.assignment_id,
            a.assigned_person,
            a.department_id,
            a.status AS assigned_status,
            a.deadline,
            a.date_created AS date_assigned,

            u.first_name AS assigned_fname,
            u.middle_name AS assigned_mname,
            u.last_name AS assigned_lname

        FROM tbl_transaction t
        LEFT JOIN tbl_resident r ON t.resident_id = r.resident_id
        LEFT JOIN tbl_complaint_types c ON t.complaint_type_id = c.complaint_type_id
        LEFT JOIN tbl_assignment a ON a.UniqueID = t.UniqueID
        LEFT JOIN tbl_user u ON a.assigned_person = u.user_id
        WHERE a.assigned_person = '$id'
    ";

    // Apply filters
    if ($status !== 'all' && !empty($status)) {
        $query .= " AND a.status = '$status'";
    }

    if (!empty($date)) {
        $query .= " AND DATE(t.date_created) = '$date'";
    }

    if (!empty($search)) {
        $search = $conn->real_escape_string($search);
        $query .= " AND (
            t.description LIKE '%$search%' OR
            r.first_name LIKE '%$search%' OR
            r.last_name LIKE '%$search%' OR
            c.complain_name LIKE '%$search%'
        )";
    }

    $query .= " ORDER BY a.assignment_id DESC";
    $query_result = $conn->query($query);

    if ($query_result->num_rows == 0) {
        echo '<div class="text-center text-muted py-4"><i class="fa fa-info-circle"></i> No complaints found.</div>';
        exit;
    }

    foreach ($query_result as $row) {
        $resident = $row['res_lname'] . ', ' . $row['res_fname'] . ' ' . $row['res_mname'];
        $date_summited = date('F d, Y', strtotime($row['date_created']));

        switch ($row['assigned_status']) {
            case 'Pending':
                $status_badge = '<span class="status-badge status-pending">Pending</span>';
                break;
            case 'Ongoing':
                $status_badge = '<span class="status-badge status-ongoing">In Progress</span>';
                break;
            case 'Completed':
                $status_badge = '<span class="status-badge status-completed">Resolved</span>';
                break;
            default:
                $status_badge = '<span class="status-badge status-unknown">Unknown</span>';
                break;
        }

        echo '
        <div class="complaint-item mb-3 p-3 border rounded">
            <div class="row">
                <div class="col-md-1 text-center">
                    <img src="https://ui-avatars.com/api/?name=' . urlencode($resident) . '&background=3498db&color=fff" class="resident-avatar rounded-circle" width="50" height="50" alt="Resident Avatar">
                </div>
                <div class="col-md-7">
                    <h6 class="mb-1">' . $row['complain_name'] . '</h6>
                    <p class="mb-1 text-muted">Submitted by: ' . $resident . ' • ' . $row['incident_address'] . '</p>
                    <p class="mb-1">' . $row['description'] . '</p>
                    <small class="text-muted">
                        <i class="far fa-clock mr-1"></i> Submitted on: ' . $date_summited . '
                    </small>
                </div>
                <div class="col-md-4 text-end">
                    <div class="mb-2">' . $status_badge . '</div>
                    <div class="dropdown">
                        <button class="btn btn-primary btn-sm dropdown-toggle" type="button" data-toggle="dropdown">
                            Action
                        </button>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a class="dropdown-item update-assignment" data-id="' . $row['assignment_id'] . '" data-status="Pending"><i class="fa fa-key"></i> Pending</a>
                            <a class="dropdown-item update-assignment" data-id="' . $row['assignment_id'] . '" data-status="Ongoing"><i class="fa fa-spinner"></i> In Progress</a>
                            <a class="dropdown-item update-assignment" data-id="' . $row['assignment_id'] . '" data-status="Completed"><i class="fa fa-check"></i> Resolved</a>
                            <a class="dropdown-item click_page" data-page="transaction_info.php?page=' . $row['UniqueID'] . '"><i class="fa fa-eye"></i> View Details</a>
                            <a class="dropdown-item" data-toggle="modal" data-target="#add-remarks" onclick="edit_reports_info(\''.$row['UniqueID'].'\')"><i class="fa fa-book"></i> Submit repord</a>
                             <a class="dropdown-item" data-toggle="modal" data-target="#add-hearing-schedule" onclick="edit_reports_info(\''.$row['UniqueID'].'\')"><i class="fa fa-calendar"></i> Schedule Hearing</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>';
    }
}



if (isset($_POST['deleting_assignment'])) {
 $id = $_POST['id'];
 $query = "DELETE FROM tbl_assignment WHERE assignment_id = '$id'";
 $query_result = $conn->query($query);
}

if (isset($_POST['updating_assignment'])) {
  $assign_id = $_POST['assign_id'];
  $u_status = $_POST['u_status'];

  $query = "UPDATE tbl_assignment SET status = '$u_status' WHERE assignment_id = '$assign_id'";
  $query_result = $conn->query($query);
}


if (isset($_POST['adding_assignements'])) {
	$transactions = $_POST['transactions'];
	$person_assigned = $_POST['person_assigned'];
	$department_assigned = $_POST['department_assigned'];
	$date_deadline = $_POST['date_deadline'];

	$query = "INSERT INTO tbl_assignment (`UniqueID`,`assigned_person`,`department_id`,`deadline`) VALUES ('$transactions', '$person_assigned', '$department_assigned', '$date_deadline')";
	$query_result = $conn->query($query);
}

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

  $id = $_SESSION['user_id'];
  $role = $_SESSION['role'];
	echo 
'
<table id="mytable" class="table table-striped table-sm">
  <thead>
    <tr>
      <th scope="col">NO.</th>
      <th scope="col">ASSIGNED PERSON</th>
      <th scope="col">DEPARTMENT</th>
      <th scope="col">STATUS</th>
      <th scope="col">DATE</th>
      <th scope="col">ACTION</th>
    </tr>
  </thead>
  <tbody>
';

if (isset($_SESSION['role']) && $_SESSION['role'] === "admin") {
    $query = "SELECT 

tbl_assignment.assignment_id,
tbl_assignment.assigned_person,
tbl_assignment.department_id,
tbl_assignment.status,
tbl_assignment.deadline,
tbl_assignment.date_created,
tbl_user.first_name,
tbl_user.middle_name,
tbl_user.last_name,
tbl_department.department_name,
tbl_transaction.resident_id,
tbl_resident.first_name AS res_fname,
tbl_resident.middle_name AS res_mname,
tbl_resident.last_name AS res_lname
FROM `tbl_assignment` 

LEFT JOIN tbl_user ON tbl_assignment.assigned_person = tbl_user.user_id
LEFT JOIN tbl_department ON tbl_assignment.department_id = tbl_department.department_id
LEFT JOIN tbl_transaction ON tbl_assignment.UniqueID = tbl_transaction.UniqueID
LEFT JOIN tbl_resident ON tbl_transaction.resident_id = tbl_resident.resident_id";
}else{
  $query = "SELECT 

tbl_assignment.assignment_id,
tbl_assignment.assigned_person,
tbl_assignment.department_id,
tbl_assignment.status,
tbl_assignment.deadline,
tbl_assignment.date_created,
tbl_user.first_name,
tbl_user.middle_name,
tbl_user.last_name,
tbl_department.department_name,
tbl_transaction.resident_id,
tbl_resident.first_name AS res_fname,
tbl_resident.middle_name AS res_mname,
tbl_resident.last_name AS res_lname
FROM `tbl_assignment` 

LEFT JOIN tbl_user ON tbl_assignment.assigned_person = tbl_user.user_id
LEFT JOIN tbl_department ON tbl_assignment.department_id = tbl_department.department_id
LEFT JOIN tbl_transaction ON tbl_assignment.UniqueID = tbl_transaction.UniqueID
LEFT JOIN tbl_resident ON tbl_transaction.resident_id = tbl_resident.resident_id WHERE tbl_assignment.assigned_person = '$id'";
}

$query_result = $conn->query($query);

$count = 0;


foreach ($query_result as $key => $row) {
	$fullname = $row['last_name'].', '.$row['first_name'].' '.$row['middle_name'];
	$date = date("F-d-Y", strtotime($row['date_created']));

  switch ($row['status']) {
    case 'Pending':
      $badge = "badge badge-primary";
      break;
       case 'Ongoing':
       $badge = "badge badge-warning";
      break;
       case 'Completed':
       $badge = "badge badge-success";
     
      break;
  }


echo 
'
 <tr>
      <th scope="row">'.++$count.'</th>
      <td>'.$fullname.'</td>
      <td>'.$row['department_name'].'</td>
      <td><span class="'.$badge.'">'.$row['status'].'</span></td>
      <td>'.$date.'</td>
      <td>
     <div class="btn-group">
  <button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
    Action
  </button>
  <div class="dropdown-menu">
    <a class="dropdown-item" onclick="edit_assignment(\''.$row['assignment_id'].'\', \''.$row['status'].'\')"><i class="fa fa-edit text-success"></i> Update</a>
    <a class="dropdown-item delete-btn" data-id="'.$row['assignment_id'].'"><i class="fa fa-trash text-danger"></i> Remove</a>

  </div>
</div>
      </td>
    </tr>
';
}
echo 
'
</tbody>
</table>
';
}


?>