<?php 
session_start();

include '../../connection.php';

if (isset($_POST['updating_complaints'])) {
    $UniqueID = $_POST['UniqueID'];
    $u_respondent = $_POST['u_respondent'];
    $u_incident_address = $_POST['u_incident_address'];
    $u_complaint_types = $_POST['u_complaint_types'];
    $u_description = $_POST['u_description'];
    $u_incident_date = $_POST['u_incident_date'];

    $query = "UPDATE `tbl_transaction` SET `respondent` = '$u_respondent', `incident_address`='$u_incident_address',`complaint_type_id`='$u_complaint_types',`description`='$u_description', `incident_date`='$u_incident_date' WHERE `UniqueID`= '$UniqueID'";
   $query_result = $conn->query($query);
}

if (isset($_POST['deleting_complaints'])) {
   $UniqueID = $_POST['UniqueID'];

   $query = "delete from tbl_transaction where UniqueID = '$UniqueID'";
   $query_result = $conn->query($query);
}
if (isset($_POST['adding_complaints'])) {

    $respondent = $_POST['respondent'];
    $incident_address = trim($_POST['incident_address']);
    $complaint_type = $_POST['complaint_type'];
    $description = strtoupper(trim($_POST['description']));
    $incident_date = $_POST['incident_date'];
    $id = $_SESSION['resident_id'];

    $targetDir = "../../uploads/evidence/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $evidence_path = null;

    if (!empty($_FILES['evidence']['name'])) {
        $fileName = time() . "_" . basename($_FILES['evidence']['name']);
        $targetFile = $targetDir . $fileName;
        $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

        $allowed = ['jpg', 'jpeg', 'png', 'mp4', 'mov', 'avi', 'mkv'];

        if (in_array($fileType, $allowed)) {
            if ($_FILES['evidence']['size'] > 100 * 1024 * 1024) {
                echo "File too large. Max 100MB allowed.";
                exit;
            }

            if (move_uploaded_file($_FILES['evidence']['tmp_name'], $targetFile)) {
                $evidence_path = $fileName;
            } else {
                echo "Error uploading file.";
                exit;
            }
        } else {
            echo "Invalid file type.";
            exit;
        }
    }

    $stmt = $conn->prepare("
        INSERT INTO tbl_transaction 
        (resident_id, respondent, incident_address, complaint_type_id, description, incident_date, supported_evidence) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("ississs", $id, $respondent, $incident_address, $complaint_type, $description, $incident_date, $evidence_path);

    if ($stmt->execute()) {
        echo "success";
    } else {
        echo "Database error: " . $conn->error;
    }

    $stmt->close();
}



if (isset($_POST['loading_complaints'])) {
	$id = $_SESSION['resident_id'];
	echo 
	'
	<table id="mytable" class="table table-sm table-striped">
  <thead>
    <tr>
      <th scope="col">NO.</th>
      <th scope="col">COMPLAINER</th>
      <th scope="col">RESPONDENT</th>
      <th scope="col">INCIDENT ADDRESS</th>
      <th scope="col">COMPLAIN TYPE</th>
      <th scope="col">DESCRIPTION</th>
      <th scope="col">STATUS</th>
      <th scope="col">INCIDENT DATE</th>
      <th scope="col">DATE</th>
      <th scope="col">ACTION</th>
    </tr>
  </thead>
  <tbody>
	';

	$query  = "SELECT 
tbl_transaction.UniqueID,
tbl_transaction.resident_id,
tbl_transaction.respondent,
tbl_transaction.incident_address,
tbl_transaction.complaint_type_id,
tbl_transaction.description,
tbl_transaction.description,
tbl_transaction.status,
tbl_transaction.incident_date,
tbl_transaction.date_created,
tbl_resident.first_name,
tbl_resident.middle_name,
tbl_resident.last_name,
tbl_complaint_types.complain_name
FROM `tbl_transaction` 
LEFT JOIN tbl_resident ON tbl_transaction.resident_id = tbl_resident.resident_id
LEFT JOIN tbl_complaint_types ON tbl_transaction.complaint_type_id  = tbl_complaint_types.complaint_type_id where tbl_transaction.resident_id = '$id' ORDER BY tbl_transaction.UniqueID DESC";
	$query_result = $conn->query($query);
	$counter = 0;
	foreach ($query_result as $key => $row) {
		$fullname = $row['last_name'].', '.$row['first_name'].''. $row['middle_name'];

        switch ($row['status']) {
            case 'Accept':
                $status = "<span class='badge badge-info'>Accepted</span>";
                break;
            case 'Pending':
                $status = "<span class='badge badge-primary'>Pending</span>";
                break;
            case 'Declined':
                $status = "<span class='badge badge-danger'>Declined</span>";
                break;
            case 'Settled':
                $status = "<span class='badge badge-success'>Settled</span>";
                break;
            case 'Unsettled':
                $status = "<span class='badge badge-warning'>Unsettled</span>";
                break;
         
        }
		echo 
		'
		    <tr>
      <th scope="row">'.++$counter.'</th>
      <td>'.$fullname.'</td>
      <td>'.$row['respondent'].'</td>
      <td>'.$row['incident_address'].'</td>
      <td>'.$row['complain_name'].'</td>
      <td>'.$row['description'].'</td>
      <td>'.$status.'</td>
      <td>'.date("F-d-Y", strtotime($row['incident_date'])).'</td>
      <td>'.date("F-d-Y", strtotime($row['date_created'])).'</td>
      <td width="1%" style="white-space: nowrap;">
         <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#update-complaint" onclick="edit_complaints(\''.$row['UniqueID'].'\',\''.$row['respondent'].'\', \''.$row['incident_address'].'\',\''.$row['complaint_type_id'].'\',\''.$row['description'].'\',\''.$row['incident_date'].'\')"><i class="fa fa-edit"></i></button>
      <button class="btn btn-danger btn-sm" onclick="delete_complaints(\''.$row['UniqueID'].'\')"><i class="fa fa-trash"></i></button>
      
   <button class="btn btn-primary btn-sm click_page" data-page="complaint_info.php?page='.$row['UniqueID'].'">View Info</button>
      </td>
    </tr>
		';
	}

	echo 
		'
		  </tbody>
</table>
		';
}
 ?>