<?php
require_once dirname(__DIR__) . '/components/executive/components.php';
require_once dirname(__DIR__, 2) . '/Executive/Language/ExecutiveLanguage.php';
$isAr=current_lang()==='ar';
$tr=static function(string $en,string $ar)use($isAr):string{return $isAr?$ar:$en;};
$data=is_array($financeData??null)?$financeData:null;$cards=is_array($data['cards']??null)?$data['cards']:[];
$matrix=is_array($data['matrix']??null)?$data['matrix']:[];$years=is_array($data['availableYears']??null)?$data['availableYears']:[$year,$compareYear];
$movement=is_array($data['primaryMovement']??null)?$data['primaryMovement']:null;$topNet=is_array($data['topNetSpecialty']??null)?$data['topNetSpecialty']:null;
$topTotalRevenue=is_array($data['topTotalRevenueSpecialty']??null)?$data['topTotalRevenueSpecialty']:null;
$money=static function(float $v):string{return number_format($v,0);};$compact=static function(float $v):string{$a=abs($v);return $a>=1000000?number_format($v/1000000,2).'M':($a>=1000?number_format($v/1000,1).'K':number_format($v,0));};
$pct=static function($v):string{return $v===null?'—':number_format((float)$v,1).'%';};
$icons=['moh'=>'▤','drug'=>'▣','net'=>'⌁'];
$tones=['moh'=>'moh','drug'=>'drug','net'=>'net'];
?>
<div class="exec-page" data-exec-foundation="H10.15.2">
<?php if($dataError||!$data): ?>
<section class="exec-surface" style="padding:28px"><h2><?=e($tr('Specialty finance data is temporarily unavailable','بيانات المالية حسب التخصص غير متاحة مؤقتًا'))?></h2><p><?=e($tr('Try another year or branch.','جرّب سنة أو فرعًا آخر.'))?></p></section>
<?php else: ?>
<section class="exec-kpi-grid">
<?php foreach(['moh','drug','net'] as $key):$c=$cards[$key]??[];exec_ui_kpi_card([
'tone'=>$tones[$key],'icon'=>$icons[$key],
'label'=>$tr((string)($c['title']??''),$key==='moh'?'إيراد وزارة الصحة':($key==='drug'?'إيراد الأدوية':'الصافي بعد الأدوية ووزارة الصحة')),
'value'=>$money((float)($c['current_total']??0)),
'comparison'=>$tr('vs ','مقابل ').$compareYear.' · '.$pct($c['percent']??null)
]);endforeach;
exec_ui_kpi_card(['tone'=>$movement&&((float)$movement['percent']<0)?'negative':'positive','icon'=>'↗','label'=>$tr('Largest movement','أكبر تحرك'),'value'=>$movement?$pct($movement['percent']):'—','comparison'=>$movement?(string)$movement['title']:$tr('No comparable movement','لا يوجد تحرك قابل للمقارنة'),'metric'=>$movement&&((float)$movement['percent']>=0)?'↑':'']);
?>
</section>

<form method="get" action="index.php" class="exec-filter-card">
<input type="hidden" name="page" value="specialty-finance"><input type="hidden" name="lang" value="<?=e(current_lang())?>">
<div class="exec-filter-title"><span><?=e(exec_lang('report_settings'))?></span><h2><?=e($tr('Compare the financial contribution','قارن المساهمة المالية'))?></h2></div>
<label class="exec-field"><span><?=e($tr('Current year','السنة الحالية'))?></span><select name="year"><?php foreach($years as $y):?><option value="<?=e((string)$y)?>" <?=(int)$y===(int)$year?'selected':''?>><?=e((string)$y)?></option><?php endforeach?></select></label>
<label class="exec-field"><span><?=e($tr('Comparison year','سنة المقارنة'))?></span><select name="compare_year"><?php foreach($years as $y):?><option value="<?=e((string)$y)?>" <?=(int)$y===(int)$compareYear?'selected':''?>><?=e((string)$y)?></option><?php endforeach?></select></label>
<button class="exec-primary" type="submit">↻ <?=e($tr('Update view','تحديث العرض'))?></button>
</form>

<div class="exec-section-bar">
<?php exec_ui_section_heading(exec_lang('performance_overview'),exec_lang('top_contributors'),$tr('Top 10 ranked by each financial measure','أعلى 10 تخصصات مرتبة حسب كل مؤشر مالي'));?>
<div class="exec-segmented" aria-label="View scope"><button class="active" type="button"><?=e($tr('Top 10','أعلى 10'))?></button><button type="button"><?=e(exec_lang('all_specialties'))?></button></div>
</div>

<section class="exec-chart-grid" data-legacy-aliases="special_net_rev net_rev" data-legacy-function="get_net_rev" data-source-boundary="FULL_HISTORICAL_FUNCTION_BODY_AND_DISPATCHER_ALIAS_MAPPING_RECOVERED">
<?php
$chartMeta=[
'moh'=>[$tr('MOH contribution by specialty','مساهمة وزارة الصحة حسب التخصص'),'MOH','moh'],
'drug'=>[$tr('Drug revenue by specialty','إيراد الأدوية حسب التخصص'),'Drug','drug'],
'net'=>[$tr('Net revenue by specialty','صافي الإيراد حسب التخصص'),'Net','net']
];
foreach(['moh','drug','net'] as $key):
$chart=$data['charts'][$key]??[];$payload=$chart['payload']??[];$values=(array)(($payload['series'][0]['values']??[]));$labels=(array)($payload['labels']??[]);
$rows=[];foreach($labels as $i=>$label){$rows[]=['label'=>(string)$label,'value'=>(float)($values[$i]??0)];}
exec_ui_chart_card(['key'=>$key,'eyebrow'=>$tr('SPECIALTY VIEW','عرض التخصصات'),'title'=>$chartMeta[$key][0],'subtitle'=>$tr('Top 10','أعلى 10'),'unit'=>$tr('Millions SAR','مليون ريال'),'empty'=>$tr('No activity for this year','لا توجد بيانات لهذه السنة'),'error'=>$tr('Chart temporarily unavailable','الرسم غير متاح مؤقتًا'),'total_label'=>$tr('Total','الإجمالي'),'total_value'=>$compact((float)($cards[$key]['current_total']??0))]);
?>
<script type="application/json" id="exec_chart_data_<?=e($key)?>"><?=json_encode(['tone'=>$chartMeta[$key][2],'rows'=>$rows,'limit'=>10,'locale'=>$isAr?'ar-SA':'en-US'],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP)?></script>
<?php endforeach?>
</section>

<section class="exec-lower-grid" data-legacy-function="special_prof" data-source-boundary="FULL_HISTORICAL_FUNCTION_BODY_RECOVERED">
<article class="exec-surface exec-table-card">
<?php exec_ui_section_heading(exec_lang('detailed_analysis'),exec_lang('all_specialties'));?>
<div class="exec-table-wrap"><table class="exec-table" data-exec-table><thead><tr><th>#</th><th><?=e($tr('Specialty','التخصص'))?></th><th><?=e(exec_lang('total_revenue'))?></th><th><?=e($tr('MOH revenue','إيراد وزارة الصحة'))?></th><th><?=e($tr('Drug revenue','إيراد الأدوية'))?></th><th><?=e($tr('Net after drug / MOH','الصافي بعد الأدوية ووزارة الصحة'))?></th></tr></thead><tbody>
<?php foreach($matrix as $i=>$row):?><tr><td><span class="exec-rank"><?=e((string)($i+1))?></span></td><td><strong><?=e((string)$row['label'])?></strong></td><td><?=array_key_exists('total_revenue_value',$row)&&$row['total_revenue_value']!==null?e($money((float)$row['total_revenue_value'])):'—'?></td><td><?=e($money((float)$row['moh_value']))?></td><td><?=e($money((float)$row['drug_value']))?></td><td><?=array_key_exists('net_value',$row)&&$row['net_value']!==null?e($money((float)$row['net_value'])):'—'?></td></tr><?php endforeach?>
</tbody></table></div>
</article>
<aside class="exec-surface exec-insight-card">
<?php exec_ui_section_heading(exec_lang('key_findings'),exec_lang('executive_summary'));?>
<div class="exec-insight-list">
<?php if($topTotalRevenue):?><div class="exec-insight-item"><i>1</i><div><?=e(exec_lang('leading_total_revenue_specialty'))?>: <strong><?=e((string)$topTotalRevenue['label'])?></strong> — <?=e($money((float)$topTotalRevenue['value']))?></div></div><?php endif?>
<?php if($topNet):?><div class="exec-insight-item"><i>2</i><div><?=e($tr('Leading net-revenue specialty: ','أعلى تخصص في صافي الإيراد: '))?><strong><?=e((string)$topNet['label'])?></strong> — <?=e($money((float)$topNet['value']))?></div></div><?php endif?>
<?php if($movement):?><div class="exec-insight-item"><i>3</i><div><?=e($tr('Largest year-over-year movement: ','أكبر تحرك سنوي: '))?><strong><?=e((string)$movement['title'])?></strong> — <?=e($pct($movement['percent']))?></div></div><?php endif?>
<div class="exec-insight-item"><i>4</i><div><?=e($tr('Protect the strongest contribution and validate sustainability by specialty.','حافظ على أقوى مساهمة وتحقق من استدامتها حسب التخصص.'))?></div></div>
</div>
</aside>
</section>

<script>
(function(){'use strict';var gate={expected:3,rendered:0,empty:0,failed:0,status:'PENDING',runtime:'H10.15.2'};
function publish(){gate.status=gate.failed===0&&(gate.rendered+gate.empty)===gate.expected?'PASS':'FAIL';window.__DDB_SPECIALTY_FINANCE_CHART_GATE__=gate;document.documentElement.dataset.specialtyFinanceChartGate=gate.status;document.documentElement.dataset.specialtyFinanceChartRuntime='H10.15.2';}
function run(){if(!window.ExecutiveUI||!window.ExecutiveUI.Charts){gate.failed=3;publish();return;}['moh','drug','net'].forEach(function(key){var card=document.querySelector('[data-exec-chart-card="'+key+'"]'),node=document.getElementById('exec_chart_data_'+key);try{var cfg=JSON.parse(node.textContent||'{}'),result=window.ExecutiveUI.Charts.renderHorizontalBar('exec_chart_'+key,cfg);if(result.empty){gate.empty++;card.dataset.chartState='empty';}else if(result.rendered){gate.rendered++;card.dataset.chartState='rendered';}else{gate.failed++;card.dataset.chartState='error';}}catch(e){gate.failed++;if(card)card.dataset.chartState='error';}});publish();}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',run,{once:true});else run();
})();</script>
<?php endif?>
</div>
