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

$year = (int)($this->input->get('year') ?: date('Y'));

$pTable = db_prefix().'integrity_pacts';
$sTable = $pTable;

$aColumns = [
    $pTable.'.id as id',
    $pTable.'.staff_name as staff_name',
    $pTable.'.staff_code as staff_code',
    $pTable.'.department as department',
    $pTable.'.year as year',
    $pTable.'.hod_status as hod_status',
    $pTable.'.status as status',
    $pTable.'.submitted_at as submitted_at',
    $pTable.'.created_at as created_at',
];

$sIndexColumn = 'id';

// ✅ Join staff table so we can filter by s.hod = logged_in_staff
$join = [
    'LEFT JOIN '.db_prefix().'staff s ON s.staffid = '.$pTable.'.staff_id',
];

$where = [];
$where[] = 'AND '.$pTable.'.year = '.$year;

$logged = (int) get_staff_user_id();

$canViewAll = staff_can('view', 'integrity_pact');
$canViewOwn = staff_can('view_own', 'integrity_pact');

// ✅ If user cannot view all, allow:
// - own records
// - OR records where staff.hod == logged (HOD scope)
if (!$canViewAll) {
    if ($canViewOwn) {
        // NOTE: if your HOD column is hod_id, change s.hod -> s.hod_id
        $where[] = 'AND ('.$pTable.'.staff_id = '.$logged.' OR s.hod = '.$logged.')';
    } else {
        // No permissions at all
        $where[] = 'AND 1=0';
    }
}

$additionalSelect = [
    $pTable.'.staff_id',
    $pTable.'.hod_id',
    's.hod as staff_hod', // optional, useful for UI logic
];

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

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

    $viewUrl = admin_url('integrity_pact/view/'.$id);

    // ID
    $row[] = '<span class="tw-font-medium">#'.$id.'</span>';

    // Name with row-options
    $nameCol = '<a href="'.$viewUrl.'" class="tw-font-medium">'.e($aRow['staff_name'] ?? '-').'</a>';
    $nameCol .= '<div class="row-options">';
    $nameCol .= '<a href="'.$viewUrl.'">'._l('view').'</a>';

    $isOwner = ((int)($aRow['staff_id'] ?? 0) === $logged);

    // ✅ HOD can "Witness/Approve" via view page (only link shown)
    // NOTE: if your HOD column is hod_id, use (int)$aRow['hod_id'] === $logged
    $isHodForThis = ((int)($aRow['staff_hod'] ?? 0) === $logged);

    if ($isHodForThis && ($aRow['hod_status'] ?? '') === 'pending') {
        $nameCol .= ' | <a href="'.$viewUrl.'#hod_action" class="text-success">Witness</a>';
    }

    // Edit/Delete rules (keep your logic)
    $canEdit   = staff_can('edit', 'integrity_pact') || ($isOwner && ($aRow['hod_status'] ?? '') === 'pending');
    $canDelete = staff_can('delete', 'integrity_pact');

    if ($canEdit) {
        $nameCol .= ' | <a href="'.admin_url('integrity_pact/edit/'.$id).'">'._l('edit').'</a>';
    }
    if ($canDelete) {
        $nameCol .= ' | <a href="'.admin_url('integrity_pact/delete/'.$id).'" class="_delete text-danger">'._l('delete').'</a>';
    }

    $nameCol .= '</div>';
    $row[] = $nameCol;

    $row[] = e($aRow['staff_code'] ?? '-');
    $row[] = e($aRow['department'] ?? '-');
    $row[] = e($aRow['year'] ?? '-');

    // HOD Status label
    $hodStatus = (string)($aRow['hod_status'] ?? 'pending');
    $label = 'label-warning';
    if ($hodStatus === 'witnessed') $label = 'label-success';
    if ($hodStatus === 'rejected')  $label = 'label-danger';
    $row[] = '<span class="label '.$label.'">'.ucfirst($hodStatus).'</span>';

    // Overall status label
    $status = (string)($aRow['status'] ?? '');
    $slabel = 'label-info';
    if ($status === 'completed') $slabel = 'label-success';
    if ($status === 'rejected')  $slabel = 'label-danger';
    $row[] = '<span class="label '.$slabel.'">'.ucfirst($status).'</span>';

    $row[] = !empty($aRow['submitted_at']) ? e(_dt($aRow['submitted_at'])) : '-';
    $row[] = !empty($aRow['created_at']) ? e(_dt($aRow['created_at'])) : '-';

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

echo json_encode($output);
die;
