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

$aColumns = [
  'id',
  'staff_name',
  'department',
  'signed_date',
  'created_at',
];

$sIndexColumn = 'id';
$sTable       = db_prefix() . 'gift_policy_statements';
$additionalSelect = ['staff_id'];

$where = [];

if (staff_cant('view', 'gift_policy_statement') && staff_can('view_own', 'gift_policy_statement')) {
  $where[] = 'AND staff_id=' . (int)get_staff_user_id();
}

$result  = data_tables_init($aColumns, $sIndexColumn, $sTable, [], $where, $additionalSelect);
$output  = $result['output'];
$rResult = $result['rResult'];

foreach ($rResult as $aRow) {
  $row = [];

  $canViewAll = staff_can('view', 'gift_policy_statement');
  $canOwn     = staff_can('view_own', 'gift_policy_statement') && ((int)$aRow['staff_id'] === (int)get_staff_user_id());
  $canEdit    = staff_can('edit', 'gift_policy_statement') && ($canViewAll || $canOwn);
  $canDelete  = staff_can('delete', 'gift_policy_statement') && ($canViewAll || $canOwn);

  foreach ($aColumns as $col) {
    $_data = $aRow[$col];

    if ($col === 'staff_name') {
      $viewUrl = admin_url('gift_policy_statement/view/' . $aRow['id']);
      $_data = '<a href="' . $viewUrl . '" class="tw-font-medium">' . e($_data) . '</a>';
      $_data .= '<div class="row-options">';
      $_data .= '<a href="' . $viewUrl . '">' . _l('view') . '</a>';
      if ($canEdit)   $_data .= ' | <a href="' . admin_url('gift_policy_statement/edit/' . $aRow['id']) . '">' . _l('edit') . '</a>';
      if ($canDelete) $_data .= ' | <a href="' . admin_url('gift_policy_statement/delete/' . $aRow['id']) . '" class="_delete text-danger">' . _l('delete') . '</a>';
      $_data .= '</div>';
    }elseif ($col === 'signed_date') {
            $_data = e(_d($_data) ?: '-');
        }
         elseif ($col === 'created_at') {
      $_data = !empty($_data) ? e(_dt($_data)) : '-';
    } else {
      $_data = e($_data);
    }

    $row[] = $_data;
    $row['DT_RowClass'] = 'has-row-options';
  }

  // options column
  $opts  = '<a class="btn btn-xs btn-default" href="' . admin_url('gift_policy_statement/view/' . $aRow['id']) . '">' . _l('view') . '</a> ';
  if ($canEdit)   $opts .= '<a class="btn btn-xs btn-info" href="' . admin_url('gift_policy_statement/edit/' . $aRow['id']) . '">' . _l('edit') . '</a> ';
  if ($canDelete) $opts .= '<a class="btn btn-xs btn-danger _delete" href="' . admin_url('gift_policy_statement/delete/' . $aRow['id']) . '">' . _l('delete') . '</a>';

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