<?php
defined('BASEPATH') or exit('No direct script access allowed');

$aColumns = [
    'id',
    'property_id',
    'maintenance_title',
    'maintenance_description',
    'requested_by',
    'status',
    'created_at',
];

$sIndexColumn = 'id';
$sTable = db_prefix() . 'propertybase_properties_maintenance';
$join = [];
$where = [];

if (!empty($property_id)) {
    array_push($where, 'AND property_id=' . $property_id);
}

if (isset($postData['properties']) && $postData['properties']) {
    $property = $postData['properties'];
    $property = array_filter($property);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties_maintenance.property_id IN (' . implode(',', $property) . ')');
}

if (isset($postData['status']) && $postData['status']) {
    $propertyStatus = $postData['status'];
    $propertyStatus = array_filter($propertyStatus);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties_maintenance.status IN (' . implode(',', $propertyStatus) . ')');
}

$result = data_tables_init($aColumns, $sIndexColumn, $sTable, $join, $where, [
    db_prefix() . 'propertybase_properties_maintenance.id',
    db_prefix() . 'propertybase_properties_maintenance.property_id',
    db_prefix() . 'propertybase_properties_maintenance.user_id',
    db_prefix() . 'propertybase_properties_maintenance.requested_by_type',
]);

$output = $result['output'];
$rResult = $result['rResult'];


foreach ($rResult as $aRow) {
    $row = [];
    for ($i = 0; $i < count($aColumns); $i++) {

        $status = propertybase_get_request_status_data($aRow['status'])['badge'] ?? 'undefined';

        $requestedBy = propertybase_get_requested_by_maintenance_request_data($aRow['requested_by'], $aRow['requested_by_type'], $aRow['user_id']);

        $row[] = $aRow['id'];
        $row[] = propertybase_formatted_property_name($aRow['property_id'], true);
        $row[] = $aRow['maintenance_title'];
        $row[] = $aRow['maintenance_description'];
        $row[] = $status;
        $row[] = $requestedBy;
        $row[] = $aRow['created_at'];

        $options = '<div class="tw-flex tw-items-center tw-space-x-3">';

        if (staff_can('edit', 'propertybase_maintenance_requests')) {
            $options .= '<a href="' . admin_url(PROPERTYBASE_MODULE_NAME . '/maintenance_requests/view/' . $aRow['id']) . '" class="tw-text-neutral-500 hover:tw-text-neutral-700 focus:tw-text-neutral-700">
        <i class="fas fa-eye fa-lg"></i>
    </a>';
        }

        if (staff_can('delete', 'propertybase_maintenance_requests')) {
            $options .= '<a href="' . admin_url(PROPERTYBASE_MODULE_NAME . '/maintenance_requests/delete/' . $aRow['id']) . '"
    class="tw-mt-px tw-text-neutral-500 hover:tw-text-neutral-700 focus:tw-text-neutral-700 _delete">
        <i class="fa-regular fa-trash-can fa-lg"></i>
    </a>';
        }

        $options .= '</div>';

        $row[] = $options;
    }

    $output['aaData'][] = $row;
}
