<?php
declare(strict_types=1);
ini_set('display_errors','0');
header('Cache-Control: private, no-store, max-age=0');
require_once __DIR__.'/../includes/console_shell.php';
require_login();
$pageLink='salary-config/add-gross-salary.php';
if(!defined('AGS_FORM_SCREEN')&&(($_GET['mode']??'')==='add'||(int)($_GET['edit']??0)>0)){
    $target='/salary-config/add-gross-salary-form.php';
    if((int)($_GET['edit']??0)>0)$target.='?edit='.(int)$_GET['edit'];
    redirect($target);
}
$acl=require_acl('can_view',$pageLink);
require_once __DIR__.'/gross-salary-report-common.php';
$canAdd=!empty($acl['can_add']);$canEdit=!empty($acl['can_edit']);$canDelete=!empty($acl['can_delete']);
$errors=[];$access=gsr_access($con);$payrolls=gsr_authorized_payrolls($con,$access);$employees=gsr_employee_options($con,$access);
$months=gsr_options($con,'SELECT id,month name FROM jos_app_mmonth ORDER BY id');
$years=gsr_options($con,'SELECT id,year name FROM jos_app_year ORDER BY id DESC LIMIT 3');
$salaryTypes=gsr_options($con,'SELECT id,name FROM jos_app_salarytype ORDER BY id');
$categories=gsr_category_enabled($con)?gsr_options($con,'SELECT id,designation_name name FROM jos_app_emp_category ORDER BY designation_name,id'):[];
$branches=gsr_options($con,'SELECT id,name FROM jos_app_orglocation ORDER BY name,id');
$flash=$_SESSION['flash_gross_salary']??null;unset($_SESSION['flash_gross_salary']);

function ags_record(mysqli $con,array $access,int $id):?array{
    if($id<1)return null;$where=['p.id=?','f.status IN (0,1)'];$types='i';$params=[$id];gsr_scope($access,$where,$types,$params);
    $rows=gsr_rows($con,'SELECT p.* FROM jos_app_emp_gross_pay p INNER JOIN jos_app_employee f ON f.id=p.empid LEFT JOIN jos_app_employee_locationlog b ON b.app_empid=f.id WHERE '.implode(' AND ',$where).' GROUP BY p.id LIMIT 1',$types,$params);return $rows[0]??null;
}
function ags_duplicate(mysqli $con,int $org,int $emp,int $month,int $year,int $exclude):bool{
    $stmt=gsr_stmt($con,'SELECT id FROM jos_app_emp_gross_pay WHERE orgid=? AND empid=? AND month=? AND year=? AND id<>? LIMIT 1');$stmt->bind_param('iiiii',$org,$emp,$month,$year,$exclude);$stmt->execute();$found=(bool)$stmt->get_result()->fetch_assoc();$stmt->close();return $found;
}
function ags_history(mysqli $con,int $id,array $v):void{
    $uid=(int)((current_user()['id']??0));$stmt=gsr_stmt($con,'INSERT INTO jos_app_emp_gross_pay_editlog (grossid,date,month,year,empid,s_type,rateperday,orgid,grosspay,rateperhr,modify_by) VALUES (?,CURDATE(),?,?,?,?,?,?,?,?,?)');
    $stmt->bind_param('iiiiididdi',$id,$v['month'],$v['year'],$v['empid'],$v['s_type'],$v['rateperday'],$v['orgid'],$v['grosspay'],$v['rateperhr'],$uid);$stmt->execute();$stmt->close();
}

$editId=max(0,(int)($_GET['edit']??0));$mode=$editId?'edit':(($_GET['mode']??'')==='add'?'add':'list');$record=$editId?ags_record($con,$access,$editId):null;
if($editId&&!$record){$errors[]='Gross salary record was not found or is outside your access.';$mode='list';}
if($mode==='add'&&!$canAdd){$errors[]='You do not have permission to add gross salary records.';$mode='list';}
if($mode==='edit'&&!$canEdit){$errors[]='You do not have permission to edit gross salary records.';$mode='list';}

if($_SERVER['REQUEST_METHOD']==='POST'){
    $action=(string)($_POST['action']??'');$id=max(0,(int)($_POST['id']??0));
    if(!verify_csrf($_POST['_csrf']??null))$errors[]='Security token expired. Please refresh and try again.';
    elseif($action==='delete'){
        if(!$canDelete)$errors[]='You do not have permission to delete gross salary records.';
        elseif(!ags_record($con,$access,$id))$errors[]='Gross salary record was not found or is outside your access.';
        else{$stmt=gsr_stmt($con,'DELETE FROM jos_app_emp_gross_pay WHERE id=?');$stmt->bind_param('i',$id);$stmt->execute();$stmt->close();audit_log('gross_salary.delete','jos_app_emp_gross_pay',(string)$id);$_SESSION['flash_gross_salary']='Gross salary record deleted successfully.';redirect('/'.$pageLink);}
    }elseif($action==='save'){
        $allowed=$id?$canEdit:$canAdd;$existing=$id?ags_record($con,$access,$id):null;
        $v=['empid'=>(int)($_POST['empid']??0),'orgid'=>(int)($_POST['orgid']??0),'month'=>(int)($_POST['month']??0),'year'=>(int)($_POST['year']??0),'s_type'=>(int)($_POST['s_type']??0),'grosspay'=>0.0,'rateperday'=>0.0,'rateperhr'=>0.0];
        $amount=(float)($_POST['amount']??0);if(in_array($v['s_type'],[1,5],true))$v['grosspay']=$amount;elseif(in_array($v['s_type'],[2,3],true))$v['rateperday']=$amount;elseif(in_array($v['s_type'],[4,6],true))$v['rateperhr']=$amount;
        if(!$allowed)$errors[]='You do not have permission to save this record.';if($id&&!$existing)$errors[]='Gross salary record was not found or is outside your access.';
        if(!gsr_id_in($employees,$v['empid']))$errors[]='Select a valid authorized employee.';if(!gsr_id_in($payrolls,$v['orgid']))$errors[]='Select a valid authorized payroll location.';
        if(!gsr_id_in($months,$v['month']))$errors[]='Select a valid month.';if(!gsr_id_in($years,$v['year']))$errors[]='Select a valid year.';if(!gsr_id_in($salaryTypes,$v['s_type']))$errors[]='Select a valid salary type.';if($amount<=0)$errors[]='Enter an amount greater than zero.';
        if(!$errors&&ags_duplicate($con,$v['orgid'],$v['empid'],$v['month'],$v['year'],$id))$errors[]='Gross salary is already configured for this employee, payroll location, month and year.';
        if(!$errors){$con->begin_transaction();try{if($id){$stmt=gsr_stmt($con,'UPDATE jos_app_emp_gross_pay SET date=CURDATE(),systemdate=NOW(),month=?,year=?,empid=?,s_type=?,orgid=?,rateperday=?,grosspay=?,rateperhr=? WHERE id=?');$stmt->bind_param('iiiiidddi',$v['month'],$v['year'],$v['empid'],$v['s_type'],$v['orgid'],$v['rateperday'],$v['grosspay'],$v['rateperhr'],$id);}else{$stmt=gsr_stmt($con,'INSERT INTO jos_app_emp_gross_pay (date,systemdate,month,year,empid,s_type,orgid,rateperday,grosspay,rateperhr) VALUES (CURDATE(),NOW(),?,?,?,?,?,?,?,?)');$stmt->bind_param('iiiiiddd',$v['month'],$v['year'],$v['empid'],$v['s_type'],$v['orgid'],$v['rateperday'],$v['grosspay'],$v['rateperhr']);}$stmt->execute();if(!$id)$id=$stmt->insert_id;$stmt->close();ags_history($con,$id,$v);$con->commit();audit_log('gross_salary.'.($existing?'update':'create'),'jos_app_emp_gross_pay',(string)$id);$_SESSION['flash_gross_salary']='Gross salary record '.($existing?'updated':'added').' successfully.';redirect('/'.$pageLink);}catch(Throwable $e){$con->rollback();$errors[]='The gross salary record could not be saved. No changes were committed.';}}
        $record=array_merge($record??[],$v);$record['amount']=$amount;$mode=$id?'edit':'add';
    }else $errors[]='Invalid request.';
}

$listFilters=['filter_emp'=>max(0,(int)($_GET['filter_emp']??0)),'filter_orglocation'=>max(0,(int)($_GET['filter_orglocation']??0)),'filter_branch'=>max(0,(int)($_GET['filter_branch']??0)),'filt_cat'=>max(0,(int)($_GET['filt_cat']??0)),'filt_month'=>max(0,(int)($_GET['filt_month']??0)),'filt_year'=>max(0,(int)($_GET['filt_year']??0)),'filt_salary'=>max(0,(int)($_GET['filt_salary']??0))];
foreach([['filter_emp',$employees],['filter_orglocation',$payrolls],['filter_branch',$branches],['filt_cat',$categories],['filt_month',$months],['filt_year',$years],['filt_salary',$salaryTypes]] as [$key,$options])if($listFilters[$key]&&!gsr_id_in($options,$listFilters[$key]))$listFilters[$key]=0;
$page=max(1,(int)($_GET['page']??1));$perPage=20;$offset=($page-1)*$perPage;$where=['f.status IN (0,1)'];$types='';$params=[];gsr_scope($access,$where,$types,$params);
foreach([['filter_emp','p.empid'],['filter_orglocation','p.orgid'],['filter_branch','f.branch_location'],['filt_cat','f.category'],['filt_month','p.month'],['filt_year','p.year'],['filt_salary','p.s_type']] as [$key,$column])if($listFilters[$key]){$where[]=$column.'=?';$types.='i';$params[]=$listFilters[$key];}
$from=' FROM jos_app_emp_gross_pay p INNER JOIN jos_app_employee f ON f.id=p.empid LEFT JOIN jos_app_employee_locationlog b ON b.app_empid=f.id LEFT JOIN jos_app_payrolllocation pl ON pl.id=p.orgid LEFT JOIN jos_app_salarytype st ON st.id=p.s_type LEFT JOIN jos_app_mmonth mm ON mm.id=p.month';
$countRows=gsr_rows($con,'SELECT COUNT(DISTINCT p.id) total'.$from.' WHERE '.implode(' AND ',$where),$types,$params);$total=(int)($countRows[0]['total']??0);
$rows=gsr_rows($con,'SELECT p.id,p.empid,p.month,p.year,p.s_type,p.grosspay,p.rateperday,p.rateperhr,f.name employee_name,pl.name payroll_name,st.name salary_type,mm.month month_name'.$from.' WHERE '.implode(' AND ',$where).' GROUP BY p.id ORDER BY p.year DESC,p.month DESC,p.id DESC LIMIT ? OFFSET ?',$types.'ii',array_merge($params,[$perPage,$offset]));

console_header($mode==='list'?'Add Gross Salary':($mode==='edit'?'Edit Gross Salary':'Add Gross Salary'),$pageLink);
$input='mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700 outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100';
?>
<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><span class="text-brand-600">Add Gross Salary</span></div><h1 class="text-2xl font-bold text-slate-900"><?=$mode==='edit'?'Edit Gross Salary':'Add Gross Salary'?></h1><p class="mt-1 text-sm text-slate-500"><?=$mode==='list'?'Manage employee gross salary configurations.':'Enter the employee salary configuration details.'?></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"><i class="fa-solid fa-circle-check mr-2"></i><?=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"><i class="fa-solid fa-circle-exclamation mr-2"></i><?=h(implode(' ',$errors))?></div><?php endif;?>
<?php if($mode!=='list'):$selectedType=(int)($record['s_type']??0);$amount=(float)($record['amount']??(in_array($selectedType,[1,5],true)?($record['grosspay']??0):(in_array($selectedType,[2,3],true)?($record['rateperday']??0):($record['rateperhr']??0))));?>
<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"><?=$mode==='edit'?'Edit Employee Gross Salary':'New Employee Gross Salary'?></h2><p class="mt-1 text-sm text-slate-400">All fields are required.</p></div><form method="post" class="grid gap-5 p-6 md:grid-cols-2 xl:grid-cols-3"><input type="hidden" name="_csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?=(int)($record['id']??0)?>">
<?php foreach([['Employee Name','empid',$employees,'Select Employee'],['Payroll Location','orgid',$payrolls,'Select Payroll Location'],['Month','month',$months,'Select Month'],['Year','year',$years,'Select Year'],['Salary Type','s_type',$salaryTypes,'Select Salary Type']] as [$label,$name,$opts,$placeholder]):?><label class="text-sm font-bold text-slate-700"><?=h($label)?><select required name="<?=h($name)?>" id="<?=h($name)?>" class="<?=$input?>"><option value=""><?=h($placeholder)?></option><?php foreach($opts as $o):?><option value="<?=(int)$o['id']?>" <?=(int)($record[$name]??0)===(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><?php endforeach;?>
<label id="amount-wrap" class="text-sm font-bold text-slate-700"><span id="amount-label">Salary Amount</span><input required min="0.01" step="0.01" type="number" name="amount" value="<?=h($amount>0?(string)$amount:'')?>" class="<?=$input?>"></label><div class="flex items-end gap-3 md:col-span-2 xl:col-span-3"><button class="rounded-xl bg-brand-600 px-7 py-3 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Submit</button><a href="/<?=$pageLink?>" class="rounded-xl border border-slate-200 px-7 py-3 text-sm font-bold text-slate-600">Cancel</a></div></form></section>
<script>const t=document.getElementById('s_type'),l=document.getElementById('amount-label'),w=document.getElementById('amount-wrap');function label(){const v=Number(t.value),known=[1,2,3,4,5,6].includes(v);w.classList.toggle('hidden',!known);l.textContent=[1,5].includes(v)?'Gross Salary':[2,3].includes(v)?'Rate Per Day':[4,6].includes(v)?'Rate Per Hour':'Salary Amount'}t.addEventListener('change',label);label();</script>
<?php else:$filterQuery=http_build_query(array_filter($listFilters,fn($v)=>$v>0));?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm"><div class="flex flex-col gap-4 border-b border-slate-100 px-6 py-5 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="text-lg font-bold text-slate-800">Employee Gross Salary List</h2><p class="mt-1 text-sm font-medium text-slate-400">Search and maintain employee gross salary configurations.</p></div><?php if($canAdd):?><a href="/salary-config/add-gross-salary-form.php" class="inline-flex items-center justify-center rounded-xl bg-brand-600 px-6 py-3 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-plus mr-2"></i>Add</a><?php endif;?></div>
<form method="get" class="grid gap-4 border-b border-slate-100 bg-slate-50/50 px-6 py-5 md:grid-cols-2 xl:grid-cols-5">
<?php foreach([['Employee Name','filter_emp',$employees,'All Employees'],['Payroll Location','filter_orglocation',$payrolls,'All Payroll Locations'],['Branch Location','filter_branch',$branches,'All Branch Locations'],['Category','filt_cat',$categories,'All Categories'],['Salary Type','filt_salary',$salaryTypes,'All Salary Types']] as [$label,$name,$opts,$placeholder]):?><label class="text-xs font-bold uppercase tracking-wide text-slate-600"><?=h($label)?><select name="<?=h($name)?>" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm font-semibold normal-case tracking-normal text-slate-700 outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100"><option value=""><?=h($placeholder)?></option><?php foreach($opts as $o):?><option value="<?=(int)$o['id']?>" <?=$listFilters[$name]===(int)$o['id']?'selected':''?>><?=h($o['name'])?></option><?php endforeach;?></select></label><?php endforeach;?>
<div class="flex flex-wrap gap-2 md:col-span-2 xl:col-span-5"><button class="rounded-xl bg-brand-600 px-6 py-3 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-arrow-right mr-2"></i>Go</button><a target="_blank" href="/salary-config/gross-salary-report-print.php<?=$filterQuery?'?'.h($filterQuery):''?>" class="rounded-xl border border-slate-200 bg-white px-6 py-3 text-sm font-bold text-slate-600"><i class="fa-solid fa-print mr-2"></i>Print</a><a href="/<?=$pageLink?>" class="rounded-xl border border-slate-200 bg-white px-6 py-3 text-sm font-bold text-slate-600">Reset</a></div></form>
<div class="flex items-center justify-between border-b border-slate-100 px-6 py-4"><p class="text-sm font-bold text-slate-700">Gross Salary Records</p><span class="rounded-full bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700"><?=$total?> record<?=$total===1?'':'s'?></span></div><div class="overflow-x-auto"><table class="w-full min-w-[1100px] text-left"><thead class="bg-slate-50 text-[11px] font-bold uppercase tracking-wide text-slate-600"><tr><th class="px-6 py-4">Sr No</th><th class="px-5 py-4">Employee Name</th><th class="px-5 py-4">Payroll Location</th><th class="px-5 py-4">Month</th><th class="px-5 py-4">Year</th><th class="px-5 py-4">Salary Type</th><th class="px-5 py-4 text-right">Gross Salary</th><th class="px-5 py-4 text-right">Rate Per Day</th><th class="px-5 py-4 text-right">Rate Per Hour</th><th class="px-6 py-4 text-right">Actions</th></tr></thead><tbody class="divide-y divide-slate-100 text-sm text-slate-700">
<?php foreach($rows as $i=>$r):?><tr class="hover:bg-slate-50/60"><td class="px-6 py-4 font-semibold text-slate-500"><?=($offset+$i+1)?></td><td class="px-5 py-4 font-bold text-slate-800"><?=h($r['employee_name'])?></td><td class="px-5 py-4"><?=h($r['payroll_name']??'-')?></td><td class="px-5 py-4"><?=h($r['month_name']??gsr_month_name($r['month']))?></td><td class="px-5 py-4"><?=h((string)$r['year'])?></td><td class="px-5 py-4"><?=h($r['salary_type']??'-')?></td><td class="px-5 py-4 text-right font-semibold"><?=number_format((float)$r['grosspay'],2)?></td><td class="px-5 py-4 text-right font-semibold"><?=number_format((float)$r['rateperday'],2)?></td><td class="px-5 py-4 text-right font-semibold"><?=number_format((float)$r['rateperhr'],2)?></td><td class="px-6 py-4"><div class="flex justify-end gap-2"><?php if($canEdit):?><a title="Edit" href="/salary-config/add-gross-salary-form.php?edit=<?=(int)$r['id']?>" class="grid h-9 w-9 place-items-center rounded-lg border border-slate-200 text-brand-600 hover:bg-brand-50"><i class="fa-solid fa-pen"></i></a><?php endif;?><?php if($canDelete):?><form method="post" onsubmit="return confirm('Delete this gross salary record?');"><input type="hidden" name="_csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=(int)$r['id']?>"><button title="Delete" class="grid h-9 w-9 place-items-center rounded-lg border border-red-100 text-red-600 hover:bg-red-50"><i class="fa-solid fa-trash"></i></button></form><?php endif;?></div></td></tr><?php endforeach;?>
<?php if(!$rows):?><tr><td colspan="10" class="px-6 py-20 text-center font-semibold text-slate-400">No employee gross salary records found.</td></tr><?php endif;?></tbody></table></div>
<?php $pages=max(1,(int)ceil($total/$perPage));if($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>Showing <?=($offset+1)?>–<?=min($offset+$perPage,$total)?> of <?=$total?></span><div class="flex gap-2"><?php if($page>1):?><a class="rounded-lg border border-slate-200 px-4 py-2" href="?<?=$filterQuery? h($filterQuery).'&amp;':''?>page=<?=$page-1?>">Previous</a><?php endif;?><?php if($page<$pages):?><a class="rounded-lg border border-slate-200 px-4 py-2" href="?<?=$filterQuery?h($filterQuery).'&amp;':''?>page=<?=$page+1?>">Next</a><?php endif;?></div></div><?php endif;?></section>
<?php endif;console_footer();
