<?php
/** @var array<string,mixed> $investigationData */
$d = is_array($investigationData ?? null) ? $investigationData : [];
$summary = is_array($d['summary'] ?? null) ? $d['summary'] : [];
$queue = is_array($d['queue'] ?? null) ? $d['queue'] : ['rows'=>[],'total'=>0,'page'=>1,'per_page'=>50];
$rows = is_array($queue['rows'] ?? null) ? $queue['rows'] : [];
$filters = is_array($d['filters'] ?? null) ? $d['filters'] : [];
$investigators = is_array($d['investigators'] ?? null) ? $d['investigators'] : [];
$allowedSites = is_array($d['allowed_sites'] ?? null) ? $d['allowed_sites'] : [];
$isAr = current_lang() === 'ar';
$tr = static function (string $en, string $ar) use ($isAr): string { return $isAr ? $ar : $en; };
$severityLabel = ['CRITICAL'=>$tr('Critical','حرجة'),'HIGH'=>$tr('High','عالية'),'MEDIUM'=>$tr('Medium','متوسطة'),'LOW'=>$tr('Low','منخفضة'),'INFO'=>$tr('Information','معلوماتية')];
$stageLabel = [
    'NEW'=>$tr('New','جديدة'),'ASSIGNED'=>$tr('Assigned','معيّنة'),'UNDER_REVIEW'=>$tr('Under review','قيد المراجعة'),
    'INFORMATION_REQUIRED'=>$tr('Information required','معلومات مطلوبة'),'FINDING_PROPOSED'=>$tr('Finding proposed','نتيجة مقترحة'),
    'SUPERVISOR_REVIEW'=>$tr('Supervisor review','مراجعة المشرف'),'MANAGEMENT_APPROVAL'=>$tr('Management approval','اعتماد الإدارة'),
    'CORRECTIVE_ACTION'=>$tr('Corrective action','إجراء تصحيحي'),'CLOSED'=>$tr('Closed','مغلقة'),
];
$slaLabel = ['OVERDUE'=>$tr('Overdue','متأخرة'),'DUE_SOON'=>$tr('Due soon','تستحق قريبًا'),'ON_TRACK'=>$tr('On track','ضمن الوقت'),'NO_DUE_DATE'=>$tr('No due date','دون موعد'),'COMPLETED'=>$tr('Completed','مكتملة')];
$total = (int)($queue['total'] ?? 0);
$page = max(1,(int)($queue['page'] ?? 1));
$perPage = max(20,(int)($queue['per_page'] ?? 50));
$totalPages = max(1,(int)ceil($total / $perPage));
$returnQuery = $filters;
$returnQuery['p']=$page;$returnQuery['per_page']=$perPage;$returnQuery['lang']=current_lang();
$returnToQueue=url_to('diar-investigations',$returnQuery);
$schemaReady=(int)($summary['workflow_schema_ready']??0)===1;
?>
<section class="diar-investigations-page diar-functional-page diar-workflow-v4" data-diar-route="diar-investigations">
    <header class="diar-investigation-hero clarity-hero">
        <div><span class="eyebrow"><?= e($tr('CONTROLLED INVESTIGATION WORKFLOW','دورة تحقيق محكومة')) ?></span><h1><?= e($tr('Investigation cases','قضايا التحقيق')) ?></h1><p><?= e($tr('Assign, investigate, request information, propose findings, approve decisions and follow corrective actions without changing frozen evidence.','تعيين القضايا والتحقق وطلب المعلومات واقتراح النتائج واعتمادها ومتابعة الإجراءات التصحيحية دون تعديل الأدلة المجمدة.')) ?></p></div>
        <div class="hero-safety"><strong><?= e($tr('Separation of duties','فصل المسؤوليات')) ?></strong><span><?= e($tr('Investigators propose findings, supervisors review them, and management approval remains separate from technical administration.','يقترح المحققون النتائج ويراجعها المشرفون، بينما يظل الاعتماد الإداري منفصلًا عن الإدارة التقنية.')) ?></span></div>
    </header>

    <?php if (!$schemaReady): ?><div class="diar-alert error"><?= e($tr('The DIAR-6B.4 Oracle workflow migration is required before workflow actions are enabled.','يلزم تطبيق ترقية Oracle الخاصة بـ DIAR-6B.4 قبل تفعيل إجراءات دورة التحقيق.')) ?></div><?php endif; ?>
    <?php if (!empty($successMessage)): ?><div class="diar-alert success"><?= e($successMessage) ?></div><?php endif; ?>
    <?php if (!empty($errorMessage)): ?><div class="diar-alert error"><?= e($errorMessage) ?></div><?php endif; ?>
    <?php if (!empty($loadError)): ?><div class="diar-alert error"><?= e($loadError) ?></div><?php endif; ?>

    <ol class="workflow-stage-strip" aria-label="<?= e($tr('Investigation stages','مراحل التحقيق')) ?>">
        <?php $n=0; foreach($stageLabel as $code=>$label): $n++; ?><li><b><?= $n ?></b><span><?= e($label) ?></span></li><?php endforeach; ?>
    </ol>

    <div class="diar-kpis workflow-kpis">
        <article><span><?= e($tr('Total cases','إجمالي القضايا')) ?></span><strong><?= number_format((int)($summary['total_cases']??0)) ?></strong></article>
        <article><span><?= e($tr('Active review','مراجعة نشطة')) ?></span><strong><?= number_format((int)($summary['active_cases']??0)) ?></strong></article>
        <article><span><?= e($tr('Supervisor review','مراجعة المشرف')) ?></span><strong><?= number_format((int)($summary['supervisor_review_cases']??0)) ?></strong></article>
        <article><span><?= e($tr('Management approval','اعتماد الإدارة')) ?></span><strong><?= number_format((int)($summary['management_approval_cases']??0)) ?></strong></article>
        <article class="risk-critical"><span><?= e($tr('Overdue','متأخرة')) ?></span><strong><?= number_format((int)($summary['overdue_cases']??0)) ?></strong></article>
        <article><span><?= e($tr('Unassigned open','مفتوحة دون تعيين')) ?></span><strong><?= number_format((int)($summary['unassigned_open']??0)) ?></strong></article>
    </div>

    <form class="diar-filter-panel workflow-filter-panel" method="get" action="index.php">
        <input type="hidden" name="page" value="diar-investigations"><input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
        <div class="field search-field"><label for="diar-q"><?= e($tr('Search','بحث')) ?></label><input id="diar-q" name="q" value="<?= e($filters['q']??'') ?>" placeholder="<?= e($tr('Case, item or store','القضية أو الصنف أو المخزن')) ?>"></div>
        <div class="field"><label for="diar-site"><?= e($tr('Hospital','المستشفى')) ?></label><select id="diar-site" name="site"><option value=""><?= e($tr('All allowed hospitals','كل المستشفيات المسموحة')) ?></option><?php foreach($allowedSites as $site): ?><option value="<?= e($site) ?>" <?= strtoupper((string)($filters['site']??''))===$site?'selected':'' ?>><?= e($site) ?></option><?php endforeach; ?></select></div>
        <div class="field"><label for="diar-stage"><?= e($tr('Workflow stage','مرحلة التحقيق')) ?></label><select id="diar-stage" name="stage"><option value=""><?= e($tr('All stages','كل المراحل')) ?></option><?php foreach($stageLabel as $code=>$label): ?><option value="<?= e($code) ?>" <?= strtoupper((string)($filters['stage']??''))===$code?'selected':'' ?>><?= e($label) ?></option><?php endforeach; ?></select></div>
        <div class="field"><label for="diar-sla"><?= e($tr('SLA status','حالة المهلة')) ?></label><select id="diar-sla" name="sla"><option value=""><?= e($tr('All SLA states','كل حالات المهلة')) ?></option><?php foreach(['OVERDUE','DUE_SOON','ON_TRACK'] as $code): ?><option value="<?= e($code) ?>" <?= strtoupper((string)($filters['sla']??''))===$code?'selected':'' ?>><?= e($slaLabel[$code]) ?></option><?php endforeach; ?></select></div>
        <div class="field"><label for="diar-severity"><?= e($tr('Priority','الأولوية')) ?></label><select id="diar-severity" name="severity"><option value=""><?= e($tr('All priorities','كل الأولويات')) ?></option><?php foreach($severityLabel as $code=>$label): ?><option value="<?= e($code) ?>" <?= strtoupper((string)($filters['severity']??''))===$code?'selected':'' ?>><?= e($label) ?></option><?php endforeach; ?></select></div>
        <div class="field"><label for="diar-assignee"><?= e($tr('Assigned to','المعيّن إليه')) ?></label><select id="diar-assignee" name="assignee"><option value=""><?= e($tr('All assignments','كل التعيينات')) ?></option><option value="__UNASSIGNED__" <?= (string)($filters['assignee']??'')==='__UNASSIGNED__'?'selected':'' ?>><?= e($tr('Unassigned','غير معيّنة')) ?></option><?php foreach($investigators as $investigator): $username=(string)($investigator['username']??''); ?><option value="<?= e($username) ?>" <?= strcasecmp((string)($filters['assignee']??''),$username)===0?'selected':'' ?>><?= e($username) ?></option><?php endforeach; ?></select></div>
        <div class="filter-actions"><button class="primary-button" type="submit"><?= e($tr('Apply filters','تطبيق الفلاتر')) ?></button><a class="secondary-button" href="<?= e(url_to('diar-investigations')) ?>"><?= e($tr('Reset','إعادة ضبط')) ?></a></div>
    </form>

    <section class="diar-queue-card workflow-queue-card">
        <div class="section-heading"><div><h2><?= e($tr('Controlled case queue','قائمة القضايا المحكومة')) ?></h2><p><?= e(sprintf($tr('%s records match the selected scope.','يوجد %s سجل يطابق النطاق المحدد.'),number_format($total))) ?></p></div><strong><?= number_format($total) ?></strong></div>
        <?php if($rows===[]): ?><div class="panel-empty-state investigation-empty"><span>◎</span><strong><?= e($tr('No cases match the selected filters','لا توجد قضايا تطابق الفلاتر المحددة')) ?></strong></div>
        <?php else: ?><div class="queue-table-wrap"><table class="diar-queue-table workflow-table"><thead><tr><th><?= e($tr('Priority','الأولوية')) ?></th><th><?= e($tr('Case','القضية')) ?></th><th><?= e($tr('Hospital / store','المستشفى / المخزن')) ?></th><th><?= e($tr('Item / scope','الصنف / النطاق')) ?></th><th><?= e($tr('Workflow','الدورة')) ?></th><th><?= e($tr('SLA','المهلة')) ?></th><th><?= e($tr('Assignment','التعيين')) ?></th><th><?= e($tr('Actions','الإجراءات')) ?></th></tr></thead><tbody>
        <?php foreach($rows as $row): $sev=(string)($row['severity_code']??'INFO');$entity=(string)($row['entity_type']??'CASE');$stage=strtoupper((string)($row['workflow_stage_code']??'NEW'));$sla=strtoupper((string)($row['sla_status_code']??'NO_DUE_DATE')); ?>
            <tr><td><span class="severity-badge severity-<?= e(strtolower($sev)) ?>"><?= e($severityLabel[$sev]??$sev) ?></span><strong class="risk-score"><?= number_format((float)($row['risk_score']??0),0) ?></strong></td>
            <td><span class="entity-tag"><?= e($entity==='EVENT'?$tr('EVENT','حدث'):$tr('CASE','قضية')) ?></span><a class="investigation-case-link" href="<?= e(url_to('diar-case-evidence',['case'=>(string)$row['case_code'],'return'=>$returnToQueue])) ?>"><?= e($row['case_code']??'') ?></a><small><?= e((string)($row['calendar_day']??'')) ?></small></td>
            <td><strong><?= e($row['site_code']??'') ?></strong><span><?= e($isAr?($row['store_name_ar']??$row['store_name_en']??''):($row['store_name_en']??$row['store_name_ar']??'')) ?></span></td>
            <td><?php if($entity==='EVENT'): ?><strong><?= e($tr('Correlated members','أعضاء مترابطون')) ?>: <?= number_format((int)($row['member_count']??0)) ?></strong><?php else: ?><strong><?= e($row['item_code']??'') ?></strong><span><?= e($isAr?($row['item_name_ar']??$row['item_name_en']??''):($row['item_name_en']??$row['item_name_ar']??'')) ?></span><?php endif; ?></td>
            <td><span class="workflow-stage-badge stage-<?= e(strtolower($stage)) ?>"><?= e($stageLabel[$stage]??$stage) ?></span></td>
            <td><span class="sla-badge sla-<?= e(strtolower($sla)) ?>"><?= e($slaLabel[$sla]??$sla) ?></span><small><?= e((string)($row['due_at']??'')) ?></small></td>
            <td><?php if(!empty($row['assigned_to'])): ?><strong><?= e($row['assigned_to']) ?></strong><small><?= e((string)($row['assigned_at']??'')) ?></small><?php else: ?><span class="unassigned"><?= e($tr('Unassigned','غير معيّنة')) ?></span><?php endif; ?></td>
            <td><div class="investigation-row-actions"><a class="review-link evidence-link" href="<?= e(url_to('diar-case-evidence',['case'=>(string)$row['case_code'],'return'=>$returnToQueue])) ?>"><?= e($tr('Frozen evidence','الأدلة المجمدة')) ?></a><a class="review-link workflow-link" href="<?= e(url_to('diar-investigation',['case'=>(string)$row['case_code'],'return'=>$returnToQueue])) ?>"><?= e($tr('Open workflow','فتح الدورة')) ?></a></div></td></tr>
        <?php endforeach; ?></tbody></table></div><?php endif; ?>
        <?php if($totalPages>1): ?><nav class="pagination"><?php $base=$filters;$base['per_page']=$perPage;if($page>1):$q=$base;$q['p']=$page-1;?><a href="<?= e(url_to('diar-investigations',$q)) ?>"><?= e($tr('Previous','السابق')) ?></a><?php endif; ?><span><?= e($tr('Page','صفحة')) ?> <?= $page ?> / <?= $totalPages ?></span><?php if($page<$totalPages):$q=$base;$q['p']=$page+1;?><a href="<?= e(url_to('diar-investigations',$q)) ?>"><?= e($tr('Next','التالي')) ?></a><?php endif; ?></nav><?php endif; ?>
    </section>
</section>
