<?php
declare(strict_types=1);
ini_set('display_errors','0');require_once __DIR__.'/../includes/console_shell.php';require_login();$pageLink=defined('PSM_LIST_PAGE_LINK')?PSM_LIST_PAGE_LINK:'salary-config/pay-scales.php';$pageTitle=defined('PSM_LIST_PAGE_TITLE')?PSM_LIST_PAGE_TITLE:'Pay Scale Master';$pageDescription=defined('PSM_LIST_PAGE_DESCRIPTION')?PSM_LIST_PAGE_DESCRIPTION:'Maintain organisation and employee Pay Scale component configurations.';$nestedList=defined('PSM_LIST_NESTED')&&PSM_LIST_NESTED;$reportMode=defined('PSM_LIST_REPORT_MODE')&&PSM_LIST_REPORT_MODE;$filterOnly=defined('PSM_LIST_FILTER_ONLY')&&PSM_LIST_FILTER_ONLY;$resultsOnly=defined('PSM_LIST_RESULTS_ONLY')&&PSM_LIST_RESULTS_ONLY;$showBack=!defined('PSM_LIST_SHOW_BACK')||PSM_LIST_SHOW_BACK;$showAdd=!defined('PSM_LIST_SHOW_ADD')||PSM_LIST_SHOW_ADD;$forceAdd=defined('PSM_LIST_FORCE_ADD')&&PSM_LIST_FORCE_ADD;$addUrl=defined('PSM_LIST_ADD_URL')?PSM_LIST_ADD_URL:'/salary-config/pay-scale-add.php';$filterAction=defined('PSM_LIST_FILTER_ACTION')?PSM_LIST_FILTER_ACTION:'/salary-config/pay-scale-list-results.php';$listUrl='/'.ltrim($pageLink,'/');$acl=require_acl('can_view',$pageLink);$addAcl=$acl;if(defined('PSM_LIST_ADD_ACL_LINK'))$addAcl=require_acl('can_view',PSM_LIST_ADD_ACL_LINK);require_once __DIR__.'/pay-scale-common.php';
$canAdd=$forceAdd||!empty($addAcl['can_add']);$canEdit=!empty($acl['can_edit']);$canDelete=!empty($acl['can_delete']);$errors=[];$access=psm_access($con);$payrolls=psm_payrolls($con,$access);$opts=psm_options($con);$catEnabled=gsr_category_enabled($con);$categories=$catEnabled?psm_rows($con,'SELECT id,designation_name name FROM jos_app_emp_category ORDER BY designation_name,id'):[];$poWhere=[];$poTypes='';$poParams=[];gsr_add_in('orgid',$access['payroll'],$poWhere,$poTypes,$poParams);$payScaleOptions=psm_rows($con,'SELECT id,payscalename name,orgid FROM jos_app_payscale_nongrid WHERE '.($poWhere?implode(' AND ',$poWhere):'1=1').' ORDER BY payscalename,id',$poTypes,$poParams);
if($_SERVER['REQUEST_METHOD']==='POST'&&$reportMode){http_response_code(405);$errors[]='This report page is read-only.';}
elseif($_SERVER['REQUEST_METHOD']==='POST'){
    $action=(string)($_POST['action']??'');$id=max(0,(int)($_POST['id']??0));$record=psm_record($con,$id,$payrolls);
    if(!verify_csrf($_POST['_csrf']??null))$errors[]='Security token expired. Please refresh and try again.';
    elseif(!$record)$errors[]='The requested Pay Scale does not exist or is outside your authorized scope.';
    elseif(($action==='unlock'&&!$canDelete)||($action!=='unlock'&&!$canEdit)){$errors[]='You do not have permission for this Pay Scale action.';http_response_code(403);}
    else try{psm_status_action($con,$id,$action);if(function_exists('audit_log'))audit_log('pay_scale.'.$action,'jos_app_payscale_nongrid',(string)$id);$_SESSION['flash_pay_scale']='Pay Scale status updated successfully.';redirect($listUrl);}catch(Throwable $e){$errors[]='The Pay Scale status could not be changed.';}
}
$f=['month'=>max(0,(int)($_GET['month']??0)),'year'=>max(0,(int)($_GET['year']??0)),'orgid'=>max(0,(int)($_GET['orgid']??0)),'category'=>max(0,(int)($_GET['category']??0)),'payscale'=>max(0,(int)($_GET['payscale']??0))];
foreach([['month',$opts['months'],'month'],['year',$opts['years'],'year'],['orgid',$payrolls,'organisation'],['category',$categories,'category'],['payscale',$payScaleOptions,'Pay Scale']] as [$key,$rows,$label])if($f[$key]&&!psm_id_in($rows,$f[$key])){$errors[]='Invalid or unauthorized '.$label.' filter.';$f[$key]=0;}
$where=[];$types='';$params=[];if($access['payroll']!==null)gsr_add_in('p.orgid',$access['payroll'],$where,$types,$params);foreach([['month','p.month'],['year','p.year'],['orgid','p.orgid'],['payscale','p.id']] as [$key,$col])if($f[$key]){$where[]=$col.'=?';$types.='i';$params[]=$f[$key];}if($f['category']){$where[]='EXISTS(SELECT 1 FROM jos_app_employee ec WHERE ec.payscale=p.id AND ec.category=?)';$types.='i';$params[]=$f['category'];}
$base=' FROM jos_app_payscale_nongrid p LEFT JOIN jos_app_payrolllocation o ON o.id=p.orgid LEFT JOIN jos_app_mmonth m ON m.id=p.month LEFT JOIN jos_app_year y ON y.id=p.year WHERE '.($where?implode(' AND ',$where):'1=1');$page=max(1,(int)($_GET['page']??1));$limit=25;$offset=($page-1)*$limit;$count=psm_rows($con,'SELECT COUNT(*) total'.$base,$types,$params);$total=(int)($count[0]['total']??0);$rows=psm_rows($con,'SELECT p.*,o.name organisation_name,m.month month_name,y.year year_name,(SELECT COUNT(*) FROM jos_app_employee e WHERE e.payscale=p.id) assigned_count,(SELECT GROUP_CONCAT(e.name ORDER BY e.name SEPARATOR ", ") FROM jos_app_employee e WHERE e.payscale=p.id LIMIT 3) assigned_names'.$base.' ORDER BY p.id DESC LIMIT ? OFFSET ?',$types.'ii',array_merge($params,[$limit,$offset]));$flash=$_SESSION['flash_pay_scale']??null;unset($_SESSION['flash_pay_scale']);$pages=max(1,(int)ceil($total/$limit));$selectedOrgName='';foreach($payrolls as $payroll)if($f['orgid']===(int)$payroll['id']){$selectedOrgName=(string)$payroll['name'];break;}$resultHeadings=$reportMode?['Sr No','Organisation Name','Month','Year','Pay Scale Name','Assigned Pay Scale']:['Sr No','Pay Scale ID','Date','Organisation Name','Month','Year','Pay Scale Name','Assigned Pay Scale','Status','Actions'];
console_header($pageTitle,$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><?php if($nestedList):?><a href="/salary-config/pay-scales.php">Pay Scale Master</a><i class="fa-solid fa-chevron-right text-[9px]"></i><?php endif;?><span class="text-brand-600"><?=h($pageTitle)?></span></div><h1 class="text-2xl font-bold text-slate-900"><?=h($pageTitle)?></h1><p class="mt-1 text-sm text-slate-500"><?=h($pageDescription)?></p></div>
<?php if($flash):?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><?=h($flash)?></div><?php endif;?><?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"><?=h(implode(' ',$errors))?></div><?php endif;?>
<?php if($reportMode):?><style>section>.bg-slate-900{background:linear-gradient(135deg,#eff6ff,#eef2ff)!important;color:#1e3a8a!important}section table thead{border-top:1px solid #e2e8f0}section table tbody tr{transition:background-color .15s ease}</style><?php endif;?>
<?php if($resultsOnly&&!$showBack):?><style>section>.flex.justify-end{display:none!important}</style><?php endif;?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm"><div class="flex flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-6 py-5"><div><h2 class="text-lg font-bold text-slate-800"><?=$filterOnly?'Pay Scale Filters':($resultsOnly?'Pay Scale Report':'Pay Scale List')?></h2><p class="mt-1 text-sm text-slate-400"><?=$filterOnly?'Select the required filters to open the report on a separate page.':($resultsOnly?'Review the filtered Pay Scale records.':($reportMode?'Select the payroll filters and click Go to view the report.':'Pay Scales follow the original verification and approval workflow.'))?></p></div><?php if($showAdd&&$canAdd):?><a href="<?=h($addUrl)?>" class="rounded-xl bg-brand-600 px-6 py-3 text-sm font-bold text-white shadow-sm transition hover:bg-brand-700"><i class="fa-solid fa-plus mr-2"></i>Add Pay Scale</a><?php endif;?></div>
<?php if(!$resultsOnly):?><form method="get" action="<?=$filterOnly?'/salary-config/pay-scale-list-results.php':''?>" class="grid gap-3 border-b border-slate-100 bg-slate-50/60 px-6 py-5 md:grid-cols-3 xl:grid-cols-6"><label class="text-xs font-bold uppercase text-slate-600">Month<select name="month" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm font-semibold normal-case"><option value="">All Months</option><?php foreach($opts['months'] as $o):?><option value="<?=(int)$o['id']?>" <?=$f['month']==(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><label class="text-xs font-bold uppercase text-slate-600">Year<select name="year" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm font-semibold normal-case"><option value="">All Years</option><?php foreach($opts['years'] as $o):?><option value="<?=(int)$o['id']?>" <?=$f['year']==(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><label class="text-xs font-bold uppercase text-slate-600">Organisation<select name="orgid" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm font-semibold normal-case"><option value="">All Organisations</option><?php foreach($payrolls as $o):?><option value="<?=(int)$o['id']?>" <?=$f['orgid']==(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><?php if($catEnabled):?><label class="text-xs font-bold uppercase text-slate-600">Category<select name="category" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm font-semibold normal-case"><option value="">All Categories</option><?php foreach($categories as $o):?><option value="<?=(int)$o['id']?>" <?=$f['category']==(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><?php endif;?><label class="text-xs font-bold uppercase text-slate-600">Payscale Name<select name="payscale" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm font-semibold normal-case"><option value="">All Pay Scales</option><?php foreach($payScaleOptions as $o):?><option value="<?=(int)$o['id']?>" <?=$f['payscale']==(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><div class="flex items-end gap-2"><button class="rounded-xl bg-brand-600 px-5 py-3 text-sm font-bold text-white">Go</button><a href="<?=h($listUrl)?>" class="rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-600">Reset</a></div></form><?php endif;?>
<?php if(!$filterOnly):?><?php if($resultsOnly):?><div class="flex justify-end border-b border-slate-100 px-6 py-4"><a href="/salary-config/pay-scale-list.php" class="rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-600"><i class="fa-solid fa-arrow-left mr-2"></i>Back to Filters</a></div><?php endif;?><?php if($reportMode):?><div class="border-b border-slate-100 bg-slate-900 px-6 py-5 text-center text-white"><div class="text-base font-extrabold"><?=h($selectedOrgName?:'All Organisations')?></div><div class="mt-1 text-sm font-semibold">Pay Scale List - Dated on <?=h(date('d-m-Y'))?></div></div><?php endif;?><div class="overflow-x-auto"><table class="w-full <?=$reportMode?'min-w-[900px]':'min-w-[1350px]'?> text-left text-sm"><thead class="bg-slate-50 text-xs font-extrabold uppercase tracking-wide text-slate-700"><tr><?php foreach($resultHeadings as $heading):?><th class="px-5 py-4"><?=h($heading)?></th><?php endforeach;?></tr></thead><tbody class="divide-y divide-slate-100"><?php foreach($rows as $i=>$row):[$label,$class]=psm_status_label((int)$row['status'],(int)$row['scalelock']);?><tr class="hover:bg-slate-50"><td class="px-5 py-4"><?=$offset+$i+1?></td><?php if(!$reportMode):?><td class="px-5 py-4 font-semibold"><?=(int)$row['id']?></td><td class="px-5 py-4"><?=h((string)$row['date'])?></td><?php endif;?><td class="px-5 py-4 font-bold"><?=h($row['organisation_name']??'-')?></td><td class="px-5 py-4"><?=h($row['month_name']??(string)$row['month'])?></td><td class="px-5 py-4"><?=h($row['year_name']??(string)$row['year'])?></td><td class="px-5 py-4 font-bold text-brand-700"><?=h($row['payscalename'])?></td><td class="px-5 py-4"><?=(int)$row['assigned_count']?'<span class="font-bold">'.(int)$row['assigned_count'].'</span><div class="max-w-64 truncate text-xs text-slate-400">'.h((string)$row['assigned_names']).'</div>':'<span class="text-slate-400">Not Assigned</span>'?></td><?php if(!$reportMode):?><td class="px-5 py-4"><span class="rounded-full px-3 py-1 text-xs font-bold <?=$class?>"><?=h($label)?></span></td><td class="px-5 py-4"><div class="flex gap-2"><?php if($canEdit&&!(int)$row['scalelock']):?><a title="Edit" href="/salary-config/pay-scale-edit.php?id=<?=(int)$row['id']?>" class="grid h-9 w-9 place-items-center rounded-lg border border-slate-200 text-brand-600"><i class="fa-solid fa-pen"></i></a><?php endif;?><?php if($canEdit&&!(int)$row['scalelock']&&(int)$row['status']<2):?><form method="post"><input type="hidden" name="_csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><input type="hidden" name="action" value="<?=(int)$row['status']===0?'verify':'approve'?>"><button title="<?=(int)$row['status']===0?'Verify':'Approve'?>" class="grid h-9 w-9 place-items-center rounded-lg border border-slate-200 text-emerald-600"><i class="fa-solid fa-check"></i></button></form><?php endif;?><?php if($canDelete&&(int)$row['scalelock']):?><form method="post" onsubmit="return confirm('Unlock this approved Pay Scale?')"><input type="hidden" name="_csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><input type="hidden" name="action" value="unlock"><button title="Unlock" class="grid h-9 w-9 place-items-center rounded-lg border border-slate-200 text-amber-600"><i class="fa-solid fa-lock-open"></i></button></form><?php endif;?></div></td><?php endif;?></tr><?php endforeach;?><?php if(!$rows):?><tr><td colspan="<?=count($resultHeadings)?>" class="px-6 py-16 text-center font-semibold text-slate-400">No Pay Scale records found.</td></tr><?php endif;?></tbody></table></div><?php endif;?>
<?php if(!$filterOnly&&$pages>1):?><div class="flex items-center justify-between border-t border-slate-100 px-6 py-4 text-sm font-semibold text-slate-500"><span><?=number_format($total)?> records</span><div class="flex gap-2"><?php $query=$f;for($p=1;$p<=$pages;$p++):$query['page']=$p;?><a href="?<?=h(http_build_query($query))?>" class="rounded-lg border px-3 py-2 <?=$p===$page?'border-brand-600 bg-brand-600 text-white':'border-slate-200 bg-white'?>"><?=$p?></a><?php endfor;?></div></div><?php endif;?></section><?php console_footer();
