<?php
declare(strict_types=1);

function psm_selected(array $values, int $id): string { return in_array($id,$values,true)?'selected':''; }

function psm_render_form(array $v,array $payrolls,array $employees,array $opts,array $components,array $stored,array $systemDefaults,string $button): void
{
    $sections=[2=>'Earning',3=>'Deduction',4=>'CTC',5=>'Primary'];
    $bySection=[];foreach($components as $c)if((int)$c['payscale_enabled']===1&&in_array((int)$c['section_id'],[2,3,4,5],true))$bySection[(int)$c['section_id']][]=$c;
    $employeeLabel='';foreach($employees as $employee)if((int)$employee['id']===(int)$v['empid']){$employeeLabel=(string)$employee['name'];break;}
    ?>
    <form method="post" id="payScaleForm" class="space-y-6" novalidate>
      <input type="hidden" name="_csrf" value="<?=h(csrf_token())?>">
      <input type="hidden" name="orgid" value="<?=(int)$v['orgid']?>">
      <input type="hidden" name="empid" value="<?=(int)$v['empid']?>">
      <input type="hidden" name="configdata" value="<?=(int)$v['configdata']?>">
      <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
        <div class="border-b border-slate-100 px-6 py-5"><h2 class="text-lg font-bold text-slate-800">Pay Scale Details</h2><p class="mt-1 text-sm text-slate-400">Fields and sequence follow the legacy Pay Scale Master.</p></div>
        <div class="grid gap-5 p-6 md:grid-cols-2 <?=(int)$v['empid']>0?'xl:grid-cols-6':'xl:grid-cols-5'?>">
          <?php if((int)$v['empid']>0):?><label class="text-sm font-bold text-slate-700">Employee Name<input value="<?=h($employeeLabel)?>" readonly class="mt-2 w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 font-semibold text-slate-600"></label><?php endif;?>
          <label class="text-sm font-bold text-slate-700">Gross Type <span class="text-red-500">*</span><select name="s_type" required class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 font-semibold"><option value="">Select Gross Type</option><?php foreach($opts['salary_types'] as $o):?><option value="<?=(int)$o['id']?>" <?=(int)$v['s_type']===(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
          <label class="text-sm font-bold text-slate-700">Month <span class="text-red-500">*</span><select name="month" required class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 font-semibold"><option value="">Select Month</option><?php foreach($opts['months'] as $o):?><option value="<?=(int)$o['id']?>" <?=(int)$v['month']===(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
          <label class="text-sm font-bold text-slate-700">Year <span class="text-red-500">*</span><select name="year" required class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 font-semibold"><option value="">Select Year</option><?php foreach($opts['years'] as $o):?><option value="<?=(int)$o['id']?>" <?=(int)$v['year']===(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
          <label class="text-sm font-bold text-slate-700">Pay Scale Name <span class="text-red-500">*</span><input name="payscalename" maxlength="255" required value="<?=h($v['payscalename'])?>" class="mt-2 w-full rounded-xl border border-slate-200 px-4 py-3 font-semibold"></label>
          <label class="text-sm font-bold text-slate-700">Gross Pay <span class="text-red-500">*</span><input name="total_salary" type="number" min="0" step="0.01" required value="<?=h((string)$v['total_salary'])?>" class="mt-2 w-full rounded-xl border border-slate-200 px-4 py-3 font-semibold"></label>
        </div>
      </section>
      <?php foreach($sections as $sectionId=>$title):$rows=$bySection[$sectionId]??[];?>
      <section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
        <div class="border-b border-slate-100 px-6 py-5"><h2 class="text-lg font-bold text-slate-800"><?=h($title)?></h2><p class="mt-1 text-sm text-slate-400">Configure the current value and calculation mapping for each component.</p></div>
        <div class="overflow-x-auto"><table class="w-full min-w-[1450px] text-left text-sm"><thead class="bg-slate-50 text-xs font-extrabold uppercase text-slate-700"><tr><th colspan="5" class="border-b border-slate-200 px-5 py-3 text-center">New</th><th colspan="3" class="border-b border-l border-slate-200 px-5 py-3 text-center text-red-600">Old Pay Scale</th></tr><tr><th class="px-5 py-4">Sr No</th><th class="px-5 py-4">Component Name</th><th class="px-5 py-4">Calculation Type</th><th class="px-5 py-4">X Percentage of</th><th class="px-5 py-4">Value</th><th class="border-l border-slate-200 px-5 py-4 text-red-600">Calculation Type</th><th class="px-5 py-4 text-red-600">X Percentage of</th><th class="px-5 py-4 text-red-600">Value</th></tr></thead><tbody class="divide-y divide-slate-100">
        <?php $sr=1;foreach($rows as $c):$cid=(int)$c['component_id'];$saved=$v['details'][$sectionId][$cid]??[];$def=(int)$v['configdata']===0?($systemDefaults[$cid]??[]):[];$calc=(int)($saved['calculation']??($def[1]['value']??0));$pctRaw=$saved['percentageof']??($def[2]['value']??'');$pct=is_array($pctRaw)?array_map('intval',$pctRaw):array_values(array_filter(array_map('intval',explode(',',(string)$pctRaw))));$amount=(string)($saved['value_amt']??($def[3]['value']??''));$calcReadonly=(int)($def[1]['readonly']??0)===1;$pctReadonly=(int)($def[2]['readonly']??0)===1;$amountReadonly=(int)($def[3]['readonly']??0)===1;$previous=$stored[$sectionId][$cid]??[];$previousCalc=(int)($previous['calculation']??0);$previousPct=array_values(array_filter(array_map('intval',explode(',',(string)($previous['percentageof']??'')))));?>
          <tr><td class="px-5 py-4 font-semibold text-slate-500"><?=$sr++?></td><td class="px-5 py-4 font-bold text-slate-800"><?=h($c['componentname'])?></td>
          <td class="px-5 py-4"><select name="details[<?=$cid?>][calculation]" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold" <?=$calcReadonly?'disabled':''?>><option value="0">Select Calculation Type</option><?php foreach($opts['calculations'] as $o):?><option value="<?=(int)$o['id']?>" <?=$calc===(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select><?php if($calcReadonly):?><input type="hidden" name="details[<?=$cid?>][calculation]" value="<?=$calc?>"><?php endif;?></td>
          <td class="px-5 py-4"><select name="details[<?=$cid?>][percentageof][]" multiple size="3" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 font-semibold" <?=$pctReadonly?'disabled':''?>><?php foreach(psm_percentage_options($components,$sectionId) as $o):$oid=(int)$o['component_id'];if($oid===$cid)continue;?><option value="<?=$oid?>" <?=in_array($oid,array_map('intval',(array)$pct),true)?'selected':''?>><?=h($o['componentname'])?></option><?php endforeach;?></select><?php if($pctReadonly)foreach((array)$pct as $p):?><input type="hidden" name="details[<?=$cid?>][percentageof][]" value="<?=(int)$p?>"><?php endforeach;?></td>
          <td class="px-5 py-4"><input name="details[<?=$cid?>][value_amt]" type="number" step="0.01" value="<?=h($amount)?>" class="w-full rounded-xl border border-slate-200 px-3 py-3 font-semibold" <?=$amountReadonly?'readonly':''?>></td>
          <td class="border-l border-slate-200 px-5 py-4 text-red-600"><?php $oldCalcName='';foreach($opts['calculations'] as $o)if((int)$o['id']===$previousCalc){$oldCalcName=(string)$o['name'];break;}?><?=h($oldCalcName?:'-')?></td>
          <td class="px-5 py-4 text-red-600"><?php $oldNames=[];foreach($components as $o)if(in_array((int)$o['component_id'],$previousPct,true))$oldNames[]=(string)$o['componentname'];?><?=h($oldNames?implode(', ',$oldNames):'-')?></td>
          <td class="px-5 py-4 text-red-600"><?=isset($previous['value_amt'])?h((string)$previous['value_amt']):'-'?></td></tr>
        <?php endforeach;?><?php if(!$rows):?><tr><td colspan="8" class="px-6 py-10 text-center font-semibold text-slate-400">No configured <?=h($title)?> components.</td></tr><?php endif;?></tbody></table></div>
      </section><?php endforeach;?>
      <div class="flex flex-wrap gap-3"><button class="rounded-xl bg-brand-600 px-7 py-3 text-sm font-bold text-white"><i class="fa-solid fa-floppy-disk mr-2"></i><?=h($button)?></button><a href="/salary-config/pay-scales.php" class="rounded-xl border border-slate-200 bg-white px-7 py-3 text-sm font-bold text-slate-600">Cancel</a></div>
    </form>
    <?php
}
