<?php
declare(strict_types=1);
ini_set('display_errors','0');
require_once __DIR__.'/../includes/console_shell.php';
require_login();
$pageLink='salary-config/pay-scales.php';
$pageAcl=require_acl('can_view',$pageLink);
if(empty($pageAcl['can_add'])){http_response_code(403);exit('Access denied.');}
require_once __DIR__.'/pay-scale-common.php';
require_once __DIR__.'/pay-scale-form.php';
$errors=[];$access=psm_access($con);$payrolls=psm_payrolls($con,$access);$opts=psm_options($con);$v=psm_defaults();$allEmployees=psm_employees($con,$access);
$showForm=isset($_GET['show_form'])||$_SERVER['REQUEST_METHOD']==='POST';$employeeName=trim((string)($_GET['employee_name']??''));
$v['orgid']=max(0,(int)($_GET['orgid']??0));$v['empid']=max(0,(int)($_GET['empid']??0));$v['configdata']=in_array((int)($_GET['configdata']??0),[0,1],true)?(int)($_GET['configdata']??0):0;
if(!$v['empid']&&$employeeName!==''){foreach($allEmployees as $employee)if(mb_strtolower(trim((string)$employee['name']))===mb_strtolower($employeeName)){$v['empid']=(int)$employee['id'];break;}}
if($v['empid']){foreach($allEmployees as $employee)if((int)$employee['id']===$v['empid']){$v['orgid']=(int)$employee['payroll_location'];break;}if(!psm_id_in($allEmployees,$v['empid'])){$errors[]='Invalid or unauthorized Employee Name.';$v['empid']=0;$v['orgid']=0;}}
if($v['orgid']&&!psm_id_in($payrolls,$v['orgid'])){$errors[]='Invalid or unauthorized Organisation Name.';$v['orgid']=0;}
$selectorRequested=isset($_GET['show_form']);
if($selectorRequested&&$v['orgid']<1&&$v['empid']<1){$errors[]='Select an Organisation Name or Employee Name before clicking Go.';$showForm=false;}
$employees=psm_employees($con,$access,$v['orgid']);$components=psm_components($con,$v['orgid']);$systemDefaults=psm_defaults_for_components($con,$v['orgid']);$previous=psm_latest_record($con,$v['orgid'],$v['empid']);$previousDetails=$previous?psm_detail_rows($con,(int)$previous['id']):[];
if($_SERVER['REQUEST_METHOD']==='POST'){
    $postedOrg=max(0,(int)($_POST['orgid']??0));$components=psm_components($con,$postedOrg);$systemDefaults=psm_defaults_for_components($con,$postedOrg);$employees=psm_employees($con,$access,$postedOrg);$v=psm_post($components);$previous=psm_latest_record($con,$postedOrg,$v['empid']);$previousDetails=$previous?psm_detail_rows($con,(int)$previous['id']):[];
    if(!verify_csrf($_POST['_csrf']??null))$errors[]='Security token expired. Please refresh and try again.';
    else{$errors=psm_validate($con,$v,0,$payrolls,$employees,$opts,$components);if(!$errors)try{$id=psm_save($con,$v,0);if(function_exists('audit_log'))audit_log('pay_scale.create','jos_app_payscale_nongrid',(string)$id);$_SESSION['flash_pay_scale']='Pay Scale added successfully.';redirect('/salary-config/pay-scales.php');}catch(Throwable $e){$errors[]='The Pay Scale could not be saved. No changes were committed.';}}
}
console_header('Add Pay Scale',$pageLink);?>
<div class="mb-6"><div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Salary Config</span><i class="fa-solid fa-chevron-right text-[9px]"></i><a href="/salary-config/pay-scales.php">Pay Scale Master</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Add</span></div><h1 class="text-2xl font-bold text-slate-900">Add Pay Scale</h1><p class="mt-1 text-sm text-slate-500">Create a Pay Scale using the established payroll component rules.</p></div>
<?php if($errors):?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><ul class="list-disc space-y-1 pl-5"><?php foreach($errors as $error):?><li><?=h($error)?></li><?php endforeach;?></ul></div><?php endif;?>
<section class="mb-6 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 Configuration</h2><p class="mt-1 text-sm text-slate-400">Select an organisation or an employee, choose the data source, then continue.</p></div><form method="get" id="payScaleSelector" class="grid items-end gap-5 p-6 md:grid-cols-[1fr_auto_1fr_1fr_auto]"><input type="hidden" name="show_form" value="1"><label class="text-sm font-bold text-slate-700">Organisation Name<select name="orgid" id="selectorOrg" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 font-semibold"><option value="">Select Organisation</option><?php foreach($payrolls as $o):?><option value="<?=(int)$o['id']?>" <?=$v['orgid']==(int)$o['id']&&!$v['empid']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><div class="pb-3 text-center text-sm font-extrabold text-red-500">OR</div><label class="text-sm font-bold text-slate-700">Employee Name<input name="employee_name" id="selectorEmployee" list="payScaleEmployees" value="<?=h($employeeName?:($v['empid']?((string)(array_values(array_filter($allEmployees,fn($e)=>(int)$e['id']===$v['empid']))[0]['name']??'')):''))?>" placeholder="Employee name" autocomplete="off" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 font-semibold"><datalist id="payScaleEmployees"><?php foreach($allEmployees as $o):?><option value="<?=h($o['name'])?>"></option><?php endforeach;?></datalist></label><label class="text-sm font-bold text-slate-700">Configure Data<select name="configdata" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 font-semibold"><option value="0" <?=$v['configdata']===0?'selected':''?>>System integrated</option><option value="1" <?=$v['configdata']===1?'selected':''?>>Manual Data</option></select></label><button type="submit" class="rounded-xl bg-brand-600 px-7 py-3 text-sm font-bold text-white">Go</button></form></section>
<script>const selectorOrg=document.getElementById('selectorOrg'),selectorEmployee=document.getElementById('selectorEmployee');selectorOrg?.addEventListener('change',()=>{if(selectorOrg.value)selectorEmployee.value=''});selectorEmployee?.addEventListener('input',()=>{if(selectorEmployee.value)selectorOrg.value=''})</script>
<?php if($showForm):?><?php $enabledComponents=array_filter($components,fn($c)=>(int)$c['payscale_enabled']===1&&in_array((int)$c['section_id'],[2,3,4,5],true));if($v['orgid']>0&&!$enabledComponents):?><div class="mb-5 rounded-xl border border-amber-100 bg-amber-50 px-5 py-4 text-sm font-semibold text-amber-700">No Pay Scale-enabled component rows are currently configured for the selected organisation.</div><?php endif;?><?php psm_render_form($v,$payrolls,$employees,$opts,$components,$previousDetails,$systemDefaults,'Submit');?><?php endif;?>
<?php console_footer();
