<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
session_start();
if (empty($_SESSION['authenticated'])) { header("Location: signin.php"); exit(); }
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/module_helpers.php';
$context = payroll_org_context($conn);

function rs(mysqli $conn,string $sql,string $types='',array $params=[]){
    $stmt=$conn->prepare($sql); if(!$stmt){return null;}
    if($types!==''&&$params){$bind=[$types]; foreach($params as $i=>$v){$params[$i]=$v; $bind[]=&$params[$i];} call_user_func_array([$stmt,'bind_param'],$bind);}
    $stmt->execute(); $result=$stmt->get_result(); $row=$result?$result->fetch_row():null; $stmt->close(); return $row[0]??null;
}
function ra(mysqli $conn,string $sql,string $types='',array $params=[]): array {
    $stmt=$conn->prepare($sql); if(!$stmt){return [];}
    if($types!==''&&$params){$bind=[$types]; foreach($params as $i=>$v){$params[$i]=$v; $bind[]=&$params[$i];} call_user_func_array([$stmt,'bind_param'],$bind);}
    $stmt->execute(); $result=$stmt->get_result(); $rows=$result?$result->fetch_all(MYSQLI_ASSOC):[]; $stmt->close(); return $rows;
}
function rurl(string $view,array $extra=[]): string { return 'reports.php?'.http_build_query(array_merge(['view'=>$view],$extra)); }
function fiscal_year_label(DateTime $date): string {
    $year=(int)$date->format('Y'); $month=(int)$date->format('n');
    $startYear=$month>=4?$year:$year-1; $endYear=$startYear+1;
    return sprintf('%d - %02d',$startYear,$endYear%100);
}

$periods=['this-month'=>'This Month','this-quarter'=>'This Quarter','this-year'=>'This Year','previous-month'=>'Previous Month','previous-quarter'=>'Previous Quarter','previous-year'=>'Previous Year','custom'=>'Custom'];
$view=$_GET['view']??'list';
$valid=['list','payroll-summary','salary-register','salary-statement','pay-summary','payroll-liability','leave-encashment-summary','lop-summary','tds-summary','variable-pay-earnings-report','scheduled-earnings-summary','epf-summary','epf-ecr-report','esi-summary','esic-return-report','pt-summary','pt-monthly-statement','pt-annual-return-statement','lwf-summary','compensation-details','reimbursement-summary','perquisite-summary','full-and-final-settlement','salary-revision-report','salary-revision-history','salary-withhold-report','fbp-declaration-report','investment-declaration-report','proof-of-investment-report','benefits-deductions-summary','deductions-summary','benefits-summary','donations-summary','form-24q','loan-outstanding-summary','loan-perquisite-summary','loan-perquisite-projection','loan-overall-summary','journal','activity-log','audit-trail'];
if(!in_array($view,$valid,true)){$view='list';}
$period=$_GET['period']??'this-year'; if(!isset($periods[$period])){$period='this-year';}
$showPeriod=isset($_GET['show_period']); $showExport=isset($_GET['show_export']); $showCustomize=isset($_GET['show_customize']); $showMenu=isset($_GET['show_report_menu']); $monthWise=isset($_GET['month_wise_breakup']); $includeEmp=isset($_GET['include_employee_details']);
$showYearlyProjection=isset($_GET['is_yearly_projection']); $includeReleasedSalary=isset($_GET['include_released_salary']); $selectedHistoryEmployeeId=max(0,(int)($_GET['employee_id']??0)); $selectedActivityLogId=max(0,(int)($_GET['activity_log_id']??0));
$earning=(string)($_GET['earning']??($view==='scheduled-earnings-summary'?'':'Overtime Allowance'));

$now=new DateTime('now'); $rangeStart=null; $rangeEnd=null;
switch($period){
    case 'this-month': $rangeStart=new DateTime($now->format('Y-m-01')); $rangeEnd=(clone $rangeStart)->modify('last day of this month'); break;
    case 'this-quarter': $q=(int)ceil(((int)$now->format('n'))/3); $m=(($q-1)*3)+1; $rangeStart=new DateTime($now->format('Y').'-'.str_pad((string)$m,2,'0',STR_PAD_LEFT).'-01'); $rangeEnd=(clone $rangeStart)->modify('+2 months')->modify('last day of this month'); break;
    case 'previous-month': $rangeStart=new DateTime($now->format('Y-m-01')); $rangeStart->modify('-1 month'); $rangeEnd=(clone $rangeStart)->modify('last day of this month'); break;
    case 'previous-quarter': $q=(int)ceil(((int)$now->format('n'))/3); $m=(($q-1)*3)+1; $rangeStart=new DateTime($now->format('Y').'-'.str_pad((string)$m,2,'0',STR_PAD_LEFT).'-01'); $rangeStart->modify('-3 months'); $rangeEnd=(clone $rangeStart)->modify('+2 months')->modify('last day of this month'); break;
    case 'previous-year': $rangeStart=new DateTime(((int)$now->format('Y')-1).'-01-01'); $rangeEnd=new DateTime(((int)$now->format('Y')-1).'-12-31'); break;
    case 'custom': $rangeStart=new DateTime(((int)$now->format('Y')-1).'-04-01'); $rangeEnd=new DateTime($now->format('Y').'-03-31'); break;
    default: $y=(int)$now->format('Y'); $n=(int)$now->format('n'); if($n>=4){$rangeStart=new DateTime($y.'-04-01'); $rangeEnd=new DateTime(($y+1).'-03-31');} else {$rangeStart=new DateTime(($y-1).'-04-01'); $rangeEnd=new DateTime($y.'-03-31');}
}
if(!empty($_GET['from_date'])&&!empty($_GET['to_date'])){ $rangeStart=DateTime::createFromFormat('Y-m-d',(string)$_GET['from_date'])?:$rangeStart; $rangeEnd=DateTime::createFromFormat('Y-m-d',(string)$_GET['to_date'])?:$rangeEnd; }
$rangeStartSql=$rangeStart->format('Y-m-d'); $rangeEndSql=$rangeEnd->format('Y-m-d'); $dateRangeLabel=$rangeStart->format('d/m/Y').' to '.$rangeEnd->format('d/m/Y'); $monthLabel=$rangeEnd->format('F, Y');
$monthsInRange=(((int)$rangeEnd->format('Y')-(int)$rangeStart->format('Y'))*12)+((int)$rangeEnd->format('n')-(int)$rangeStart->format('n'))+1; $monthsInRange=max(1,$monthsInRange);
$orgId=(string)$context['org_id']; $orgName=(string)$context['org_name'];
$fiscalYearLabel=fiscal_year_label($rangeEnd);
$selectedFiscalYear=(string)($_GET['fiscal_year']??$fiscalYearLabel);
$employees=payroll_load_employees($conn);
$employeeMap=[]; $employeeOptions=[]; $compensationRows=[]; $investmentDeclarationRows=[]; $proofInvestmentRows=[];
foreach($employees as $employee){
    $empId=(int)($employee['id']??0);
    $empCode=payroll_employee_code($employee);
    $empName=payroll_employee_name($employee);
    $employeeMap[$empId]=$employee;
    $employeeOptions[]=['id'=>$empId,'label'=>$empName.' ('.($empCode!==''?$empCode:$empId).')'];
    $basicMonthly=(float)($employee['basic_monthly']??0);
    $fixedMonthly=(float)($employee['fixed_allowance_monthly']??0);
    $grossMonthly=$basicMonthly+$fixedMonthly;
    if($grossMonthly<=0 && (float)($employee['annual_ctc']??0)>0){$grossMonthly=(float)$employee['annual_ctc']/12;}
    $ctcMonthly=(float)($employee['annual_ctc']??0)>0?(float)$employee['annual_ctc']/12:$grossMonthly;
    $multiplier=$showYearlyProjection?12:1;
    $compensationRows[]=[
        'employee_id'=>$empCode!==''?$empCode:(string)$empId,
        'employee_name'=>$empName,
        'basic'=>$basicMonthly*$multiplier,
        'fixed_allowance'=>$fixedMonthly*$multiplier,
        'gross_pay'=>$grossMonthly*$multiplier,
        'ctc'=>$ctcMonthly*$multiplier,
    ];
}

$earnings=(float)(rs($conn,"SELECT COALESCE(SUM(CASE WHEN COALESCE(basic_monthly,0)+COALESCE(fixed_allowance_monthly,0)>0 THEN COALESCE(basic_monthly,0)+COALESCE(fixed_allowance_monthly,0) WHEN COALESCE(annual_ctc,0)>0 THEN annual_ctc/12 ELSE 0 END),0) FROM employees WHERE COALESCE(is_deleted,0)=0")??0)*$monthsInRange;
$benefits=(float)(rs($conn,"SELECT COALESCE(SUM(employer_contribution_amount),0) FROM employee_benefits WHERE DATE(created_at) BETWEEN ? AND ?",'ss',[$rangeStartSql,$rangeEndSql])??0);
$deductions=(float)(rs($conn,"SELECT COALESCE(SUM(total_amount_to_deduct),0) FROM employee_benefits WHERE DATE(created_at) BETWEEN ? AND ?",'ss',[$rangeStartSql,$rangeEndSql])??0);
$reimbursements=(float)(rs($conn,"SELECT COALESCE(SUM(total_approved_amount),0) FROM reimbursement_claims WHERE (org_id=? OR org_id=?) AND claim_month BETWEEN ? AND ?",'ssss',[$orgId,$orgName,$rangeStartSql,$rangeEndSql])??0);
$donationCount=(int)(rs($conn,"SELECT COUNT(*) FROM giving_campaigns WHERE org_id=? AND DATE(created_at) BETWEEN ? AND ?",'sss',[$orgId,$rangeStartSql,$rangeEndSql])??0);
$taxCount=(int)(rs($conn,"SELECT COUNT(*) FROM tax_details WHERE org_id=? AND DATE(created_at) BETWEEN ? AND ?",'sss',[$orgId,$rangeStartSql,$rangeEndSql])??0);
$donations=0.0; $taxes=0.0; $net=max(0,$earnings+$benefits+$reimbursements-$deductions-$taxes);
$st=$conn->prepare("SELECT earnings_amount,benefits_amount,donations_amount,deductions_amount,taxes_amount,reimbursements_amount,net_pay_amount FROM payroll_report_summaries WHERE org_id=? AND range_start=? AND range_end=? LIMIT 1");
if($st){$st->bind_param('sss',$orgId,$rangeStartSql,$rangeEndSql); $st->execute(); $r=$st->get_result(); if($row=$r->fetch_assoc()){$earnings=(float)$row['earnings_amount'];$benefits=(float)$row['benefits_amount'];$donations=(float)$row['donations_amount'];$deductions=(float)$row['deductions_amount'];$taxes=(float)$row['taxes_amount'];$reimbursements=(float)$row['reimbursements_amount'];$net=(float)$row['net_pay_amount'];} $st->close();}
$summaryRows=[['Earnings',$earnings>0?$earnings:null,'No data to display'],['Benefits',$benefits>0?$benefits:null,'No statutories were included during this period'],['Donations',$donations>0?$donations:null,$donationCount>0?'Campaigns are available, but no contribution totals are stored yet':'No data to display'],['Deductions',$deductions>0?$deductions:null,'No deductions were applied in this period'],['Taxes',$taxes>0?$taxes:null,$taxCount>0?'Tax setup exists, but no tax amount entries are stored yet':'No data to display'],['Reimbursements',$reimbursements>0?$reimbursements:null,'No data to display'],['Net Pay',$net,null]];

$paySummaryRows=ra($conn,"SELECT employee_id,employee_name,gross_pay,benefits,deductions,taxes,reimbursements,net_pay FROM report_pay_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$liabilityRows=ra($conn,"SELECT liability_name,employees_contribution,employer_contribution,total_contribution FROM report_payroll_liability WHERE org_id=? AND range_start=? AND range_end=? ORDER BY liability_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$leaveRows=ra($conn,"SELECT employee_id,employee_name,days,amount FROM report_leave_encashment WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$lopRows=ra($conn,"SELECT employee_name,employee_id,lop_days,lop_adjustment_days,actual_lop_days FROM report_lop_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$tdsRows=payroll_table_exists($conn,'tds_summary_report')
    ? ra($conn,"SELECT employee_id,employee_name,pan,taxable_amount_year,tax_on_income,surcharge_amount,cess_amount,total_tds_amount FROM tds_summary_report WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql])
    : ra($conn,"SELECT employee_id,employee_name,pan,taxable_amount_year,tax_on_income,surcharge_amount,cess_amount,total_tds_amount FROM report_tds_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$variableRows=ra($conn,"SELECT employee_id,employee_name,earning_name,earning_month,total_scheduled_amount,total_paid_amount,difference_amount FROM report_variable_earnings WHERE org_id=? AND range_start=? AND range_end=?".($earning!==''?" AND earning_name=?":"")." ORDER BY employee_name ASC, earning_month ASC",$earning!==''?'ssss':'sss',$earning!==''?[$orgId,$rangeStartSql,$rangeEndSql,$earning]:[$orgId,$rangeStartSql,$rangeEndSql]);
$epfSummaryRows=ra($conn,"SELECT employee_id,employee_name,pf_account_number,uan,pf_wage,employee_pf_amount,employee_vpf_amount,employer_pf_amount,employer_eps_amount,employer_edli_amount,pf_admin_charges,total_contribution FROM report_epf_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$epfEcrRows=ra($conn,"SELECT employee_id,uan,member_name,gross_wages,epf_wages,eps_wages,edli_wages,epf_contribution_remitted,eps_contribution_remitted,epf_eps_diff_remitted,ncp_days,refund_of_advances FROM report_epf_ecr WHERE org_id=? AND range_start=? AND range_end=? ORDER BY member_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$esiSummaryRows=ra($conn,"SELECT employee_id,employee_name,esi_number,esi_wages,employees_contribution,employers_contribution,total_contribution FROM report_esi_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$esicReturnRows=ra($conn,"SELECT insurance_person_number,insurance_person_name,paid_days,total_monthly_wages,reason_code_zero_working_days,last_working_day FROM report_esic_return WHERE org_id=? AND range_start=? AND range_end=? ORDER BY insurance_person_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$ptSummaryRows=ra($conn,"SELECT employee_id,employee_name,work_location,pt_amount FROM report_pt_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$ptMonthlyRows=ra($conn,"SELECT employee_id,employee_name,pt_wages,pt_amount FROM report_pt_monthly_statement WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$ptAnnualRows=ra($conn,"SELECT period_label,employee_count,pt_amount FROM report_pt_annual_return WHERE org_id=? AND range_start=? AND range_end=? ORDER BY period_order ASC, id ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$lwfRows=ra($conn,"SELECT employee_id,employee_name,employees_contribution,employers_contribution,total_contribution FROM report_lwf_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]);
$reimbursementSummaryRows=ra($conn,"SELECT c.employee_id,e.employee_code,e.full_name,e.first_name,e.middle_name,e.last_name,i.reimbursement_type,SUM(i.claim_amount) AS eligible_amount,SUM(i.approved_amount) AS paid_amount,SUM(i.claim_amount-i.approved_amount) AS unclaimed_amount FROM reimbursement_claims c LEFT JOIN reimbursement_items i ON i.claim_id=c.id LEFT JOIN employees e ON e.id=c.employee_id WHERE (c.org_id=? OR c.org_id=?) AND c.claim_month BETWEEN ? AND ? GROUP BY c.employee_id,i.reimbursement_type,e.employee_code,e.full_name,e.first_name,e.middle_name,e.last_name ORDER BY e.full_name ASC, i.reimbursement_type ASC",'ssss',[$orgId,$orgName,$rangeStartSql,$rangeEndSql]);
$perquisiteRows=ra($conn,"SELECT b.employee_id,e.employee_code,e.full_name,e.first_name,e.middle_name,e.last_name,b.benefit_name,b.employer_contribution_amount,b.total_amount_to_deduct FROM employee_benefits b LEFT JOIN employees e ON e.id=b.employee_id WHERE DATE(b.created_at) BETWEEN ? AND ? ORDER BY e.full_name ASC,b.benefit_name ASC",'ss',[$rangeStartSql,$rangeEndSql]);
$fullFinalRowsRaw=ra($conn,"SELECT * FROM employees WHERE COALESCE(is_deleted,0)=0 AND date_of_leaving IS NOT NULL AND date_of_leaving BETWEEN ? AND ? ORDER BY date_of_leaving DESC, full_name ASC",'ss',[$rangeStartSql,$rangeEndSql]);
$poiRows=ra($conn,"SELECT * FROM poi_submissions WHERE org_id=? AND fiscal_year=? ORDER BY updated_at DESC, id DESC",'ss',[$orgId,$fiscalYearLabel]);
$benefitsDeductionsSummaryRows=payroll_table_exists($conn,'benefit_deduction_summary')?ra($conn,"SELECT deduction_name,deduction_type,employees_contribution,employer_contribution,total_contribution FROM benefit_deduction_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY deduction_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$postTaxDeductionRows=payroll_table_exists($conn,'employee_post_tax_deductions_summary')?ra($conn,"SELECT employee_id,employee_name,employees_contribution FROM employee_post_tax_deductions_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$preTaxBenefitRows=payroll_table_exists($conn,'employee_pre_tax_benefits_summary')?ra($conn,"SELECT employee_id,employee_name,employees_contribution,employer_contribution,total_contribution FROM employee_pre_tax_benefits_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$donationSummaryRows=payroll_table_exists($conn,'employee_donation_summary')?ra($conn,"SELECT employee_id,employee_name,employees_contribution FROM employee_donation_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$tdsSummaryReportRows=payroll_table_exists($conn,'tds_summary_report')?ra($conn,"SELECT employee_id,employee_name,pan,taxable_amount_year,tax_on_income,surcharge_amount,cess_amount,total_tds_amount FROM tds_summary_report WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$form24QRows=payroll_table_exists($conn,'form24q_reports')?ra($conn,"SELECT * FROM form24q_reports WHERE org_id=? AND fiscal_year=? ORDER BY id DESC",'ss',[$orgId,$selectedFiscalYear]):[];
$loanOutstandingRows=payroll_table_exists($conn,'loan_outstanding_summary')?ra($conn,"SELECT employee_id,employee_name,loan_number,loan_name,loan_amount,outstanding_amount FROM loan_outstanding_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$loanPerquisiteRows=payroll_table_exists($conn,'loan_perquisite_summary')?ra($conn,"SELECT employee_id,employee_name,loan_number,loan_name,loan_amount,perquisite_amount FROM loan_perquisite_summary WHERE org_id=? AND fiscal_year=? ORDER BY employee_name ASC",'ss',[$orgId,$selectedFiscalYear]):[];
$loanPerquisiteProjectionRows=payroll_table_exists($conn,'loan_perquisite_projection')?ra($conn,"SELECT employee_id,employee_name,loan_number,loan_name,projected_perquisite_amount FROM loan_perquisite_projection WHERE org_id=? AND fiscal_year=? ORDER BY employee_name ASC",'ss',[$orgId,$selectedFiscalYear]):[];
$loanOverallRows=payroll_table_exists($conn,'loan_overall_summary')?ra($conn,"SELECT employee_id,employee_name,loan_number,loan_name,loan_amount,outstanding_amount,perquisite_amount FROM loan_overall_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY employee_name ASC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$journalRows=payroll_table_exists($conn,'payroll_journal_summary')?ra($conn,"SELECT journal_date,entry_name,debit_amount,credit_amount,reference_no,notes FROM payroll_journal_summary WHERE org_id=? AND range_start=? AND range_end=? ORDER BY journal_date DESC,id DESC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$activityLogRows=payroll_table_exists($conn,'activity_logs')?ra($conn,"SELECT id,activity_time,activity_details,description,performed_by FROM activity_logs WHERE org_id=? AND DATE(activity_time) BETWEEN ? AND ? ORDER BY activity_time DESC,id DESC",'sss',[$orgId,$rangeStartSql,$rangeEndSql]):[];
$activityVersionRows=($selectedActivityLogId>0 && payroll_table_exists($conn,'activity_log_versions'))?ra($conn,"SELECT version_no,version_time,performed_by,section_title,field_name,field_value FROM activity_log_versions WHERE activity_log_id=? ORDER BY id DESC",'i',[$selectedActivityLogId]):[];
$selectedActivityLog=null;
$availableFiscalYears=['2025 - 26','2026 - 27','2027 - 28'];
$poiLatestByEmployee=[]; foreach($poiRows as $poiRow){ $poiEmpId=(int)($poiRow['employee_id']??0); if(!isset($poiLatestByEmployee[$poiEmpId])){$poiLatestByEmployee[$poiEmpId]=$poiRow;} }
$salaryRevisionRows=[]; $salaryRevisionHistoryRows=[]; $salaryWithholdRows=[]; $fbpDeclarationRows=[]; $fullFinalRows=[];

foreach($reimbursementSummaryRows as &$row){
    $source=$employeeMap[(int)($row['employee_id']??0)]??$row;
    $row['employee_name']=payroll_employee_name($source);
    $row['employee_code']=payroll_employee_code($source);
}
unset($row);
foreach($perquisiteRows as &$row){
    $source=$employeeMap[(int)($row['employee_id']??0)]??$row;
    $row['employee_name']=payroll_employee_name($source);
    $row['employee_code']=payroll_employee_code($source);
    $row['chargeable_tax']=(float)($row['employer_contribution_amount']??0)-(float)($row['total_amount_to_deduct']??0);
    if($row['chargeable_tax']<0){$row['chargeable_tax']=0.0;}
}
unset($row);
foreach($fullFinalRowsRaw as $row){
    $joiningTs=strtotime((string)$row['date_of_joining']); $leavingTs=strtotime((string)$row['date_of_leaving']);
    $servicePeriod='-';
    if($joiningTs && $leavingTs && $leavingTs>=$joiningTs){
        $diff=(new DateTime((string)$row['date_of_joining']))->diff(new DateTime((string)$row['date_of_leaving']));
        $servicePeriod=trim(($diff->y>0?$diff->y.' yr ':'').($diff->m>0?$diff->m.' mo ':'').($diff->d>0?$diff->d.' days':'')); if($servicePeriod===''){$servicePeriod='0 days';}
    }
    $fullFinalRows[]=[
        'employee_name'=>payroll_employee_name($row),
        'designation'=>(string)($row['designation']??'-'),
        'date_of_joining'=>(string)($row['date_of_joining']??''),
        'last_working_date'=>(string)($row['date_of_leaving']??''),
        'service_period'=>$servicePeriod,
        'reason_for_exit'=>'-',
        'settlement_date'=>(string)($row['date_of_leaving']??''),
        'settlement_amount'=>0.0,
    ];
}
foreach($employees as $employee){
    $empId=(int)($employee['id']??0);
    $poi=$poiLatestByEmployee[$empId]??null;
    $taxRegime=(string)($poi['tax_regime']??'New Regime');
    $declared=(float)($poi['declared_amount']??0);
    $approved=(float)($poi['approved_amount']??0);
    $investmentDeclarationRows[]=[
        'employee_name'=>payroll_employee_name($employee),
        'tax_regime'=>$taxRegime,
        'chapter_vi_a'=>$approved,
        'allowance_amount'=>0.0,
        'hra_amount'=>0.0,
        'other_income_amount'=>0.0,
        'previous_employment_amount'=>0.0,
        'direct_tax_amount'=>0.0,
    ];
    $proofInvestmentRows[]=[
        'employee_name'=>payroll_employee_name($employee),
        'submitted_on'=>(string)($poi['submitted_at']??''),
        'approver_name'=>'',
        'status'=>$poi?ucfirst((string)$poi['status']):'',
        'tax_regime'=>$taxRegime,
        'actual_amount'=>$declared,
        'approved_amount'=>$approved,
        'document_count'=>0,
    ];
}
foreach($activityLogRows as $logRow){ if((int)($logRow['id']??0)===$selectedActivityLogId){ $selectedActivityLog=$logRow; break; } }

$variableGrouped=[]; $scheduledRows=[];
foreach($variableRows as $varRow){
    $key=(string)($varRow['employee_id']??'').'|'.(string)$varRow['employee_name'];
    if(!isset($variableGrouped[$key])){
        $variableGrouped[$key]=[
            'employee_id'=>$varRow['employee_id'],
            'employee_name'=>$varRow['employee_name'],
            'months'=>[],
            'total_paid_amount'=>0.0,
        ];
    }
    $monthKey=!empty($varRow['earning_month'])?date('Y-m',strtotime((string)$varRow['earning_month'])):'';
    if($monthKey!==''){
        $variableGrouped[$key]['months'][$monthKey]=(float)$varRow['total_paid_amount'];
    }
    $variableGrouped[$key]['total_paid_amount']+=(float)$varRow['total_paid_amount'];
    $scheduledRows[]=$varRow;
}

$reportColumns=['Payroll Overview'=>['Payroll Summary'=>'payroll-summary','Salary Register - Monthly'=>'salary-register','Salary Statement'=>'salary-statement','Pay Summary'=>'pay-summary','Payroll Liability Summary'=>'payroll-liability','Leave Encashment Summary'=>'leave-encashment-summary','LOP Summary'=>'lop-summary','Variable Pay Earnings Report'=>'variable-pay-earnings-report','Scheduled Earnings Report'=>'scheduled-earnings-summary'],'Statutory Reports'=>['EPF Summary'=>'epf-summary','EPF-ECR Report'=>'epf-ecr-report','ESI Summary'=>'esi-summary','ESIC Return Report'=>'esic-return-report','PT Summary'=>'pt-summary','PT Monthly Statement'=>'pt-monthly-statement','PT Annual Return Statement'=>'pt-annual-return-statement','LWF Summary'=>'lwf-summary'],'Employee Reports'=>['Compensation Details'=>'compensation-details','Reimbursement Summary'=>'reimbursement-summary','Perquisite Summary'=>'perquisite-summary','Full and Final Settlement'=>'full-and-final-settlement','Salary Revision Report'=>'salary-revision-report','Salary Revision History'=>'salary-revision-history','Salary Withhold Report'=>'salary-withhold-report'],'Declarations & Investments'=>['FBP Declaration Report'=>'fbp-declaration-report','Investment Declaration Report'=>'investment-declaration-report','Proof of Investment Report'=>'proof-of-investment-report'],'Deduction Reports'=>['Benefits & Deductions Summary'=>'benefits-deductions-summary','Deductions Summary'=>'deductions-summary','Benefits Summary'=>'benefits-summary','Donations Summary'=>'donations-summary'],'Taxes and Forms'=>['TDS (Tax Deduction Summary)'=>'tds-summary','Form 24Q'=>'form-24q'],'Loan Reports'=>['Loan Outstanding Summary'=>'loan-outstanding-summary','Loan Perquisite Summary'=>'loan-perquisite-summary','Loan Perquisite Projection'=>'loan-perquisite-projection','Loan Overall Summary'=>'loan-overall-summary'],'Payroll Journal'=>['Payroll Journal Summary'=>'journal'],'Activity'=>['Activity Logs'=>'activity-log']];
$layoutGroups=[['Payroll Overview','Statutory Reports','Employee Reports'],['Declarations & Investments','Deduction Reports','Taxes and Forms'],['Loan Reports','Payroll Journal','Activity']];
$menuSections=['PAYROLL OVERVIEW'=>$reportColumns['Payroll Overview'],'STATUTORY REPORTS'=>$reportColumns['Statutory Reports'],'EMPLOYEE REPORTS'=>$reportColumns['Employee Reports'],'DECLARATIONS & INVESTMENTS'=>$reportColumns['Declarations & Investments'],'DEDUCTION REPORTS'=>$reportColumns['Deduction Reports'],'TAXES AND FORMS'=>$reportColumns['Taxes and Forms'],'LOAN REPORTS'=>$reportColumns['Loan Reports'],'PAYROLL JOURNAL'=>$reportColumns['Payroll Journal'],'ACTIVITY'=>$reportColumns['Activity']];

$titles=['payroll-summary'=>'Payroll Summary','salary-register'=>sprintf('Salary Register for %s',$monthLabel),'salary-statement'=>'Salary Statement','pay-summary'=>'Pay Summary','payroll-liability'=>'Payroll Liability Summary','leave-encashment-summary'=>'Leave Encashment Summary','lop-summary'=>'LOP Summary','tds-summary'=>'TDS (Tax Deduction Summary)','variable-pay-earnings-report'=>'Variable Pay Earnings Report - '.$earning,'scheduled-earnings-summary'=>'Scheduled Earnings Report','epf-summary'=>'EPF Summary','epf-ecr-report'=>sprintf('EPF-ECR Report for %s',$monthLabel),'esi-summary'=>'ESI Summary','esic-return-report'=>sprintf('ESIC Return Report for %s',$monthLabel),'pt-summary'=>'PT Summary','pt-monthly-statement'=>sprintf('PT Statement for %s',$monthLabel),'pt-annual-return-statement'=>'PT Annual Return Statement','lwf-summary'=>'Labour Welfare Fund Summary','compensation-details'=>'Compensation Details','reimbursement-summary'=>'Reimbursement Summary','perquisite-summary'=>'Perquisite Summary','full-and-final-settlement'=>'Full and Final Settlement','salary-revision-report'=>'Salary Revision Report','salary-revision-history'=>'Salary Revision History','salary-withhold-report'=>'Salary Withhold Report','fbp-declaration-report'=>'FBP Declaration Report for '.$rangeStart->format('d F Y').' - Present Day','investment-declaration-report'=>'Investment Declaration Report for '.$rangeStart->format('d F Y').' - '.$rangeEnd->format('d F Y'),'proof-of-investment-report'=>'Proof of Investment Report','benefits-deductions-summary'=>'Benefits & Deductions Summary','deductions-summary'=>'Deductions Summary','benefits-summary'=>'Benefits Summary','donations-summary'=>'Donations Summary','form-24q'=>'Form 24Q','loan-outstanding-summary'=>'Loan Outstanding Summary','loan-perquisite-summary'=>'Loan Perquisite Summary','loan-perquisite-projection'=>'Loan Perquisite Projection','loan-overall-summary'=>'Loan Overall Summary','journal'=>'Payroll Journal Summary','activity-log'=>'Activity Logs','audit-trail'=>'Audit Trail'];
$emptyMessages=['salary-register'=>"You haven't paid any employees in this period.",'salary-statement'=>"You haven't paid any employees in this period.",'pay-summary'=>'No data to display','payroll-liability'=>'No data to display','leave-encashment-summary'=>'No leave encashment found in this period','lop-summary'=>'There are no LOP for employees during this period','tds-summary'=>'No data to display','epf-summary'=>'No PF was contributed during this period.','epf-ecr-report'=>'No PF was contributed during this period.','esi-summary'=>'No ESI was contributed during this period','esic-return-report'=>'No ESI was contributed during this period','pt-summary'=>'No PT deductions were made in this period.','pt-monthly-statement'=>'No PT deductions were made in this period.','pt-annual-return-statement'=>'No data to display','lwf-summary'=>'No data to display','reimbursement-summary'=>'No Reimbursements for this period','perquisite-summary'=>'No data to display','full-and-final-settlement'=>'No data to display','salary-revision-report'=>'No data to display','salary-revision-history'=>'Please select an Employee to view their Salary Revision History','salary-withhold-report'=>'You have not withheld any salary for this period.','fbp-declaration-report'=>'No fbp declarations have been submitted after the selected date in the current financial year. Select a different date to view the report.','investment-declaration-report'=>'No data to display','proof-of-investment-report'=>'No data to display','benefits-deductions-summary'=>'No data to display','deductions-summary'=>'No data to display','benefits-summary'=>'No data to display','donations-summary'=>'No data to display','form-24q'=>'Form 24Q has not been generated for this Fiscal Year.','loan-outstanding-summary'=>'No data to display','loan-perquisite-summary'=>'No data to display','loan-perquisite-projection'=>'No data to display','loan-overall-summary'=>'No data to display','journal'=>'No data to display','activity-log'=>'No data to display','audit-trail'=>'No versions found for this activity log.'];
$columns=['pay-summary'=>['ID','NAME','GROSS PAY','BENEFITS','DEDUCTIONS','TAXES','REIMBURSEMENTS','NET PAY'],'payroll-liability'=>['LIABILITY',"EMPLOYEES' CONTRIBUTION","EMPLOYER'S CONTRIBUTION",'TOTAL CONTRIBUTION'],'leave-encashment-summary'=>['EMPLOYEE ID','EMPLOYEE NAME','DAYS','AMOUNT'],'lop-summary'=>['EMPLOYEE NAME','EMPLOYEE ID','LOP DAYS','LOP ADJUSTMENT DAYS','ACTUAL LOP DAYS'],'tds-summary'=>['ID','NAME','PAN','TAXABLE AMOUNT (YEAR)','TAX ON INCOME','SURCHARGE AMOUNT','CESS AMOUNT','TOTAL TDS AMOUNT'],'epf-summary'=>['ID','NAME','PF ACCOUNT NUMBER','UAN','PF WAGE','EMPLOYEE PF AMOUNT','EMPLOYEE VPF AMOUNT','EMPLOYER PF AMOUNT','EMPLOYER EPS AMOUNT','EMPLOYER EDLI','PF ADMIN CHARGES','TOTAL CONTRIBUTION'],'epf-ecr-report'=>['ID','UAN','MEMBER NAME','GROSS WAGES','EPF WAGES','EPS WAGES','EDLI WAGES','EPF CONTRIBUTION REMITTED','EPS CONTRIBUTION REMITTED','EPF AND EPS DIFF REMITTED','NCP DAYS','REFUND OF ADVANCES'],'esi-summary'=>['ID','NAME','ESI NUMBER','ESI WAGES',"EMPLOYEES' CONTRIBUTION","EMPLOYER'S CONTRIBUTION",'TOTAL CONTRIBUTION'],'esic-return-report'=>['INSURANCE PERSON NUMBER','INSURANCE PERSON NAME','PAID DAYS','TOTAL MONTHLY WAGES','REASON CODE FOR ZERO WORKINGS DAYS','LAST WORKING DAY'],'pt-summary'=>['ID','NAME','WORK LOCATION','PT AMOUNT'],'pt-monthly-statement'=>['ID','NAME','PT WAGES','PT AMOUNT'],'pt-annual-return-statement'=>['PERIOD','NO. OF EMPLOYEES','PT AMOUNT'],'lwf-summary'=>['ID','NAME',"EMPLOYEES' CONTRIBUTION","EMPLOYER'S CONTRIBUTION",'TOTAL CONTRIBUTION'],'compensation-details'=>['ID','NAME','BASIC','FIXED ALLOWANCE','GROSS PAY',$showYearlyProjection?'ANNUAL CTC':'MONTHLY CTC'],'reimbursement-summary'=>['EMPLOYEE ID','EMPLOYEE NAME','REIMBURSEMENT TYPE','ELIGIBLE','PAID AMOUNT','UNCLAIMED'],'perquisite-summary'=>['EMPLOYEE ID','EMPLOYEE NAME','VALUE OF PERQUISITE AS PER RULES','AMOUNT RECOVERED FROM THE EMPLOYEE, IF ANY','AMOUNT OF PERQUISITE CHARGEABLE TO TAX'],'full-and-final-settlement'=>['EMPLOYEE','DESIGNATION','DATE OF JOINING','LAST WORKING DATE','SERVICE PERIOD','REASON FOR EXIT','FINAL SETTLEMENT DATE','FINAL SETTLEMENT AMOUNT'],'salary-revision-report'=>['EMPLOYEE','PREVIOUS CTC','REVISED CTC','DIFFERENCE','EFFECTIVE FROM','PAYOUT MONTH','STATUS'],'salary-revision-history'=>['PREVIOUS CTC','REVISED CTC','DIFFERENCE','EFFECTIVE FROM','PAYOUT MONTH'],'salary-withhold-report'=>['NAME','DESIGNATION','EMPLOYEE STATUS','WITHHELD MONTH','AMOUNT TO PAY','WITHHELD REASON','RELEASE STATUS','RELEASE MONTH'],'investment-declaration-report'=>['EMPLOYEE NAME','TAX REGIME','TOTAL CHAPTER VI-A AMOUNT','TOTAL ALLOWANCE AMOUNT','TOTAL HRA AMOUNT','TOTAL OTHER INCOME AMOUNT','TOTAL PREVIOUS EMPLOYMENT AMOUNT','TOTAL DIRECT TAX AMOUNT'],'proof-of-investment-report'=>['EMPLOYEE NAME','SUBMITTED ON','APPROVER NAME','STATUS','TAX REGIME','ACTUAL AMOUNT','APPROVED AMOUNT','DOCUMENT COUNT'],'benefits-deductions-summary'=>['DEDUCTION NAME','DEDUCTION TYPE',"EMPLOYEES' CONTRIBUTION","EMPLOYER'S CONTRIBUTION",'TOTAL CONTRIBUTION'],'deductions-summary'=>['ID','NAME',"EMPLOYEE'S CONTRIBUTION"],'benefits-summary'=>['ID','NAME',"EMPLOYEE'S CONTRIBUTION","EMPLOYER'S CONTRIBUTION",'TOTAL CONTRIBUTION'],'donations-summary'=>['EMPLOYEE ID','EMPLOYEE NAME',"EMPLOYEE'S CONTRIBUTION"],'loan-outstanding-summary'=>['EMPLOYEE ID','EMPLOYEE NAME','LOAN NUMBER','LOAN NAME','LOAN AMOUNT','OUTSTANDING AMOUNT'],'loan-perquisite-summary'=>['EMPLOYEE ID','EMPLOYEE NAME','LOAN NUMBER','LOAN NAME','LOAN AMOUNT','PERQUISITE AMOUNT'],'loan-perquisite-projection'=>['EMPLOYEE ID','EMPLOYEE NAME','LOAN NUMBER','LOAN NAME','PROJECTED PERQUISITE AMOUNT'],'loan-overall-summary'=>['EMPLOYEE ID','EMPLOYEE NAME','LOAN NUMBER','LOAN NAME','LOAN AMOUNT','OUTSTANDING AMOUNT','PERQUISITE AMOUNT'],'journal'=>['DATE','ENTRY NAME','DEBIT AMOUNT','CREDIT AMOUNT','REFERENCE NO','NOTES'],'activity-log'=>['TIME','ACTIVITY DETAILS','DESCRIPTION',''],'audit-trail'=>['VERSION','TIME','SECTION','FIELD','VALUE']];
$exportOptions=$view==='tds-summary'?['PDF','CSV (Comma Separated Values)','XLS (Microsoft Excel 1997-2004 Compatible)','XLSX (Microsoft Excel)','Export to Zoho Sheet','Annual TDS Worksheet Report']:(in_array($view,['salary-statement','compensation-details','investment-declaration-report','proof-of-investment-report'],true)?['XLS (Microsoft Excel 1997-2004 Compatible)','XLSX (Microsoft Excel)','Export to Zoho Sheet']:['PDF','XLS (Microsoft Excel 1997-2004 Compatible)','XLSX (Microsoft Excel)','Export to Zoho Sheet']);
$base=['period'=>$period,'from_date'=>$rangeStartSql,'to_date'=>$rangeEndSql]; if($earning!==''){$base['earning']=$earning;} if($monthWise){$base['month_wise_breakup']=1;} if($includeEmp){$base['include_employee_details']=1;} if($showYearlyProjection){$base['is_yearly_projection']=1;} if($includeReleasedSalary){$base['include_released_salary']=1;} if($selectedHistoryEmployeeId>0){$base['employee_id']=$selectedHistoryEmployeeId;} if($selectedFiscalYear!==''){$base['fiscal_year']=$selectedFiscalYear;} if($selectedActivityLogId>0){$base['activity_log_id']=$selectedActivityLogId;}
$subtitlePrefix=in_array($view,['tds-summary'],true)?'Deduction period from ':(in_array($view,['epf-summary','esi-summary','pt-summary'],true)?'Contribution period from ':'');
$reportSubtitle=$subtitlePrefix.$dateRangeLabel;
if($view==='compensation-details'){$reportSubtitle='As of '.$monthLabel;}
elseif(in_array($view,['perquisite-summary','investment-declaration-report','proof-of-investment-report'],true)){$reportSubtitle='Fiscal Year : '.$fiscalYearLabel;}
elseif($view==='salary-revision-history'){$reportSubtitle='';}
elseif(in_array($view,['benefits-deductions-summary','deductions-summary','benefits-summary'],true)){$reportSubtitle='Deduction period from '.$dateRangeLabel;}
elseif($view==='donations-summary' || $view==='journal' || $view==='activity-log'){$reportSubtitle=$dateRangeLabel;}
elseif(in_array($view,['loan-perquisite-summary','loan-perquisite-projection','form-24q'],true)){$reportSubtitle='Fiscal Year : '.$selectedFiscalYear;}
elseif($view==='audit-trail'){$reportSubtitle='';}
?>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>"><title>Reports | Payroll</title><link rel="stylesheet" href="dashboard.css"><link rel="stylesheet" href="assets/fontawesome/css/all.min.css"><link rel="stylesheet" href="assets/font-inter.css"><link rel="stylesheet" href="modules.css"></head>
<body class="module-page"><div class="module-shell loans-shell"><aside class="module-sidebar"><div class="module-brand"><img src="images/zoho-payroll-logo.svg" alt="Payroll"><span>Payroll</span></div><div class="module-sidebar-scroll"><div class="module-sidebar-section"><div class="module-getting-started"><div class="module-gs-top"><i class="fa-solid fa-wand-magic-sparkles"></i><span>Getting Started</span></div><div class="module-progress-bar"><div class="module-progress-fill"></div></div></div></div><nav class="module-nav"><a href="dashboard.php"><i class="fa-regular fa-circle-dot"></i><span>Dashboard</span></a><a href="employees.php"><i class="fa-regular fa-user"></i><span>Employees</span></a><a href="payruns.php"><i class="fa-regular fa-calendar-check"></i><span>Pay Runs</span></a><a href="#"><i class="fa-regular fa-square-check"></i><span>Approvals</span></a><a href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a><a href="loans.php"><i class="fa-solid fa-indian-rupee-sign"></i><span>Loans</span></a><a href="giving.php"><i class="fa-regular fa-heart"></i><span>Giving</span></a><a href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a><a class="active" href="reports.php"><i class="fa-regular fa-chart-bar"></i><span>Reports</span></a><a href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a></nav></div><div class="module-sidebar-footer"><a class="module-support-link" href="#">Contact Support <i class="fa-solid fa-angle-right"></i></a></div><div class="module-support-tile"><div class="module-support-title">Track TDS Liabilities and Generate Form 24Q</div><a class="module-support-action" href="#">View Details</a></div></aside>
<main class="module-main loans-main reports-main"><div class="module-topbar loans-topbar"><div class="module-search"><i class="fa-solid fa-magnifying-glass"></i><input type="text" placeholder="Search in Employee"></div><div class="module-user"><span><?php echo htmlspecialchars($context['display_name']); ?></span><span class="module-avatar"><?php echo htmlspecialchars(strtoupper(substr($context['display_name'],0,1))); ?></span></div></div>
<?php if($view==='list'): ?><section class="reports-hub-page"><div class="reports-page-head"><h1>Reports</h1></div><?php foreach($layoutGroups as $group): ?><div class="reports-grid-row"><?php foreach($group as $sectionTitle): ?><div class="reports-list-card"><h2><?php echo htmlspecialchars($sectionTitle); ?></h2><div class="reports-links"><?php foreach($reportColumns[$sectionTitle] as $label=>$target): ?><a href="<?php echo htmlspecialchars(rurl($target)); ?>"><i class="fa-solid fa-angle-right"></i><span><?php echo htmlspecialchars($label); ?></span></a><?php endforeach; ?></div></div><?php endforeach; ?></div><?php endforeach; ?></section>
<?php else: ?><section class="reports-detail-page"><div class="reports-detail-toolbar"><div class="reports-detail-tools-left"><a class="reports-icon-square" href="<?php echo htmlspecialchars(rurl($view,$base+['show_report_menu'=>$showMenu?0:1])); ?>"><i class="fa-solid fa-bars"></i></a><?php if($view==='audit-trail'): ?><a class="reports-customize-link" href="<?php echo htmlspecialchars(rurl('activity-log',['period'=>$period,'from_date'=>$rangeStartSql,'to_date'=>$rangeEndSql])); ?>"><i class="fa-solid fa-arrow-left"></i><span>Back</span></a><?php else: ?><div class="reports-period-wrap"><button class="reports-period-btn" type="button" data-report-period-toggle><i class="fa-regular fa-calendar"></i><span><?php echo htmlspecialchars($periods[$period]); ?></span><i class="fa-solid fa-angle-down"></i></button><div class="reports-period-menu <?php echo $showPeriod?'open':''; ?>" data-report-period-menu><?php foreach($periods as $k=>$txt): ?><a class="<?php echo $period===$k?'active':''; ?>" href="<?php echo htmlspecialchars(rurl($view,array_merge($base,['period'=>$k,'show_period'=>1]))); ?>"><?php echo htmlspecialchars($txt); ?></a><?php endforeach; ?></div></div><?php endif; ?><?php if($view==='salary-register'): ?><label class="reports-checkbox-line"><input type="checkbox" <?php echo $includeEmp?'checked':''; ?>><span>Include Employee Details</span></label><?php endif; ?><?php if($view==='compensation-details'): ?><a class="reports-checkbox-line" href="<?php echo htmlspecialchars(rurl($view,$base+['is_yearly_projection'=>$showYearlyProjection?0:1])); ?>"><input type="checkbox" <?php echo $showYearlyProjection?'checked':''; ?>><span>Show Yearly Projection</span></a><?php endif; ?><?php if($view==='salary-withhold-report'): ?><a class="reports-checkbox-line" href="<?php echo htmlspecialchars(rurl($view,$base+['include_released_salary'=>$includeReleasedSalary?0:1])); ?>"><input type="checkbox" <?php echo $includeReleasedSalary?'checked':''; ?>><span>Include Released Salary Details</span></a><?php endif; ?><?php if(in_array($view,['form-24q','loan-perquisite-summary','loan-perquisite-projection'],true)): ?><div class="reports-inline-select-wrap"><span class="reports-inline-label">Fiscal Year:</span><button class="reports-inline-select" type="button" data-fiscal-toggle><span><?php echo htmlspecialchars($selectedFiscalYear!==''?$selectedFiscalYear:'Select'); ?></span><i class="fa-solid fa-angle-down"></i></button><div class="reports-inline-menu <?php echo isset($_GET['show_fiscal_year'])?'open':''; ?>" data-fiscal-menu><?php foreach($availableFiscalYears as $fy): ?><a class="<?php echo $selectedFiscalYear===$fy?'active':''; ?>" href="<?php echo htmlspecialchars(rurl($view,array_merge($base,['fiscal_year'=>$fy,'show_fiscal_year'=>1]))); ?>"><?php echo htmlspecialchars($fy); ?></a><?php endforeach; ?></div></div><?php endif; ?><?php if($view==='variable-pay-earnings-report'||$view==='scheduled-earnings-summary'): ?><div class="reports-inline-select-wrap"><span class="reports-inline-label">Earning:</span><button class="reports-inline-select" type="button" data-earning-toggle><span><?php echo htmlspecialchars($earning!==''?$earning:'Select'); ?></span><i class="fa-solid fa-angle-down"></i></button><div class="reports-inline-menu <?php echo isset($_GET['show_earning'])?'open':''; ?>" data-earning-menu><div class="reports-dropdown-search"><i class="fa-solid fa-magnifying-glass"></i><input type="text" placeholder=""></div><?php $opts=$view==='scheduled-earnings-summary'?[]:['Overtime Allowance','Gratuity','Bonus','Commission','Leave Encashment','Notice Pay','Hold Salary']; ?><?php if(!$opts): ?><div class="reports-inline-empty">SORRY! NO RESULTS FOUND</div><?php else: foreach($opts as $opt): ?><a class="<?php echo $earning===$opt?'active':''; ?>" href="<?php echo htmlspecialchars(rurl($view,array_merge($base,['earning'=>$opt,'show_earning'=>1]))); ?>"><?php echo htmlspecialchars($opt); ?><?php echo $earning===$opt?' <i class="fa-solid fa-check"></i>':''; ?></a><?php endforeach; endif; ?></div></div><?php if($view==='variable-pay-earnings-report'): ?><label class="reports-checkbox-line"><input type="checkbox" <?php echo $monthWise?'checked':''; ?>><span>Include Month wise breakup</span></label><?php endif; ?><?php endif; ?><?php if($view==='salary-revision-history'): ?><div class="reports-inline-select-wrap"><span class="reports-inline-label">Employee:</span><button class="reports-inline-select" type="button" data-history-toggle><span><?php echo htmlspecialchars($selectedHistoryEmployeeId>0?($employeeMap[$selectedHistoryEmployeeId]['full_name']??payroll_employee_name($employeeMap[$selectedHistoryEmployeeId]??[])):'Select'); ?></span><i class="fa-solid fa-angle-down"></i></button><div class="reports-inline-menu <?php echo isset($_GET['show_history_employee'])?'open':''; ?>" data-history-menu><div class="reports-dropdown-search"><i class="fa-solid fa-magnifying-glass"></i><input type="text" placeholder=""></div><?php foreach($employeeOptions as $option): ?><a class="<?php echo $selectedHistoryEmployeeId===$option['id']?'active':''; ?>" href="<?php echo htmlspecialchars(rurl($view,array_merge($base,['employee_id'=>$option['id'],'show_history_employee'=>1]))); ?>"><?php echo htmlspecialchars($option['label']); ?></a><?php endforeach; ?></div></div><?php endif; ?><?php if($view!=='audit-trail'): ?><a class="reports-customize-link" href="<?php echo htmlspecialchars(rurl($view,$base+['show_customize'=>1])); ?>"><i class="fa-solid fa-gear"></i><span>Customize Report</span></a><?php endif; ?></div><div class="reports-detail-tools-right"><?php if($view!=='audit-trail'): ?><div class="reports-export-wrap"><a class="reports-export-btn" href="<?php echo htmlspecialchars(rurl($view,$base+['show_export'=>1])); ?>">Export as <i class="fa-solid fa-angle-down"></i></a><?php if($showExport): ?><div class="reports-export-menu open"><?php foreach($exportOptions as $i=>$opt): ?><a class="<?php echo $i===0?'active':''; ?>" href="#"><?php echo htmlspecialchars($opt); ?></a><?php endforeach; ?></div><?php endif; ?></div><?php endif; ?><a class="icon-btn ghost" href="<?php echo htmlspecialchars(rurl($view,$base)); ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a></div></div>
<div class="reports-detail-canvas<?php echo $showMenu?' with-menu':''; ?>"><?php if($showMenu): ?><aside class="reports-side-menu"><div class="reports-side-head"><h3>Reports</h3><a href="<?php echo htmlspecialchars(rurl($view,$base)); ?>"><i class="fa-solid fa-xmark"></i></a></div><div class="reports-side-search"><i class="fa-solid fa-magnifying-glass"></i><input type="text" placeholder="Search"></div><div class="reports-side-scroll"><?php foreach($menuSections as $sectionName=>$items): ?><div class="reports-side-section-title"><?php echo htmlspecialchars($sectionName); ?></div><?php foreach($items as $label=>$target): ?><a class="reports-side-link <?php echo $target===$view?'active':''; ?>" href="<?php echo htmlspecialchars(rurl($target,$base+['show_report_menu'=>1])); ?>"><?php echo htmlspecialchars($label); ?></a><?php endforeach; ?><?php endforeach; ?></div></aside><?php endif; ?><div class="reports-view-shell"><?php if($showCustomize): ?><div class="reports-customize-panel"><div class="reports-customize-head"><h2>Customize Report</h2></div><div class="reports-customize-body"><div class="reports-customize-grid"><label>Date Range</label><div class="reports-customize-field"><?php echo htmlspecialchars($periods[$period]); ?> <i class="fa-solid fa-angle-down"></i></div><label>Work Location</label><input type="text" placeholder="Work Location"><label>Department</label><input type="text" placeholder="Department"><label>Designation</label><input type="text" placeholder="Designation"><label>Payrun Status</label><div class="reports-customize-field">Paid <i class="fa-solid fa-angle-down"></i></div></div></div><div class="reports-customize-foot"><a class="btn-primary" href="<?php echo htmlspecialchars(rurl($view,$base)); ?>">Run Report</a><a class="btn-secondary" href="<?php echo htmlspecialchars(rurl($view,$base)); ?>">Cancel</a></div></div><?php else: ?><div class="reports-summary-sheet"><div class="reports-summary-head"><div class="reports-summary-org"><?php echo htmlspecialchars($context['org_name']); ?></div><h1><?php echo htmlspecialchars($titles[$view]); ?></h1><?php if($reportSubtitle!==''): ?><div class="reports-summary-range"><?php echo htmlspecialchars($reportSubtitle); ?></div><?php endif; ?></div>
<?php if($view==='payroll-summary'): ?><div class="reports-summary-table"><div class="reports-summary-table-head"><span>PAY COMPONENTS</span><span>AMOUNT (&#8377;)</span></div><?php foreach($summaryRows as $row): ?><div class="reports-summary-row"><div class="reports-summary-label"><?php echo htmlspecialchars($row[0]); ?></div><?php if($row[1]===null): ?><div class="reports-summary-empty"><?php echo htmlspecialchars((string)$row[2]); ?></div><div class="reports-summary-value"></div><?php else: ?><div class="reports-summary-empty"></div><div class="reports-summary-value"><?php echo htmlspecialchars(payroll_format_currency((float)$row[1])); ?></div><?php endif; ?></div><?php endforeach; ?></div>
<?php elseif($view==='salary-register'||$view==='salary-statement'): ?><?php if(!$paySummaryRows): ?><div class="reports-empty-message"><?php echo htmlspecialchars($emptyMessages[$view]); ?></div><?php else: ?><div class="reports-generic-table"><table class="module-table"><thead><tr><th>ID</th><th>NAME</th><th>GROSS PAY</th><th>BENEFITS</th><th>DEDUCTIONS</th><th>TAXES</th><th>REIMBURSEMENTS</th><th>NET PAY</th></tr></thead><tbody><?php foreach($paySummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['gross_pay'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['benefits'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['deductions'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['taxes'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['reimbursements'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['net_pay'])); ?></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?>
<?php elseif($view==='compensation-details'): ?><div class="reports-generic-table"><table class="module-table"><thead><tr><?php foreach($columns[$view] as $col): ?><th><?php echo htmlspecialchars($col); ?></th><?php endforeach; ?></tr></thead><tbody><?php if(!$compensationRows): ?><tr><td colspan="<?php echo count($columns[$view]); ?>" class="reports-table-empty">No data to display</td></tr><?php else: foreach($compensationRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['basic'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['fixed_allowance'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['gross_pay'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['ctc'])); ?></td></tr><?php endforeach; endif; ?></tbody></table></div>
<?php elseif($view==='variable-pay-earnings-report'): ?><div class="reports-generic-table"><table class="module-table"><thead><tr><th>EMPLOYEE ID</th><th>EMPLOYEE NAME</th><?php if($monthWise): $cursor=clone $rangeStart; while($cursor<=$rangeEnd): ?><th><?php echo strtoupper($cursor->format('F Y')); ?></th><?php $cursor->modify('+1 month'); endwhile; else: ?><th>TOTAL AMOUNT PAID</th><?php endif; ?></tr></thead><tbody><?php if(!$variableGrouped): ?><tr><td colspan="<?php echo $monthWise?(2+$monthsInRange):3; ?>" class="reports-table-empty">No employees found</td></tr><?php else: foreach($variableGrouped as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><?php if($monthWise): $cursor=clone $rangeStart; while($cursor<=$rangeEnd): $monthKey=$cursor->format('Y-m'); ?><td><?php echo isset($row['months'][$monthKey])?htmlspecialchars(payroll_format_currency((float)$row['months'][$monthKey])):'-'; ?></td><?php $cursor->modify('+1 month'); endwhile; else: ?><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_paid_amount'])); ?></td><?php endif; ?></tr><?php endforeach; endif; ?></tbody></table></div>
<?php elseif($view==='scheduled-earnings-summary'): ?><div class="reports-generic-table"><table class="module-table"><thead><tr><th>EMPLOYEE ID</th><th>EMPLOYEE NAME</th><th>EARNING NAME</th><th>TOTAL SCHEDULED AMOUNT</th><th>TOTAL PAID AMOUNT</th><th>DIFFERENCE</th></tr></thead><tbody><?php if(!$scheduledRows): ?><tr><td colspan="6" class="reports-table-empty">No data to display</td></tr><?php else: foreach($scheduledRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['earning_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_scheduled_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_paid_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['difference_amount'])); ?></td></tr><?php endforeach; endif; ?></tbody></table></div>
<?php elseif($view==='fbp-declaration-report'): ?><div class="reports-empty-message"><?php echo htmlspecialchars($emptyMessages[$view]); ?></div>
<?php elseif($view==='form-24q'): ?><div class="reports-empty-message"><?php echo htmlspecialchars($emptyMessages[$view]); ?></div>
<?php elseif($view==='loan-perquisite-projection' && !$loanPerquisiteProjectionRows): ?><div class="reports-empty-message"><?php echo htmlspecialchars($emptyMessages[$view]); ?></div>
<?php elseif($view==='loan-overall-summary' && !$loanOverallRows): ?><div class="reports-empty-message"><?php echo htmlspecialchars($emptyMessages[$view]); ?></div>
<?php elseif($view==='journal' && !$journalRows): ?><div class="reports-empty-message"><?php echo htmlspecialchars($emptyMessages[$view]); ?></div>
<?php elseif($view==='audit-trail'): ?><div class="reports-generic-table"><table class="module-table"><thead><tr><?php foreach($columns[$view] as $col): ?><th><?php echo htmlspecialchars($col); ?></th><?php endforeach; ?></tr></thead><tbody><?php if(!$activityVersionRows): ?><tr><td colspan="<?php echo count($columns[$view]); ?>" class="reports-table-empty"><?php echo htmlspecialchars($emptyMessages[$view]); ?></td></tr><?php else: foreach($activityVersionRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['version_no']); ?></td><td><?php echo htmlspecialchars(payroll_date_label((string)$row['version_time'])); ?></td><td><?php echo htmlspecialchars((string)($row['section_title']?:'-')); ?></td><td><?php echo htmlspecialchars((string)($row['field_name']?:'-')); ?></td><td><?php echo htmlspecialchars((string)($row['field_value']?:'-')); ?></td></tr><?php endforeach; endif; ?></tbody></table></div>
<?php else: ?><div class="reports-generic-table"><table class="module-table"><thead><tr><?php foreach($columns[$view] as $col): ?><th><?php echo htmlspecialchars($col); ?></th><?php endforeach; ?></tr></thead><tbody><?php if($view==='pay-summary' && $paySummaryRows): ?><?php foreach($paySummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['gross_pay'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['benefits'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['deductions'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['taxes'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['reimbursements'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['net_pay'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='benefits-deductions-summary' && $benefitsDeductionsSummaryRows): ?><?php foreach($benefitsDeductionsSummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['deduction_name']); ?></td><td><?php echo htmlspecialchars(ucfirst((string)$row['deduction_type'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employees_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employer_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_contribution'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='deductions-summary' && $postTaxDeductionRows): ?><?php foreach($postTaxDeductionRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employees_contribution'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='benefits-summary' && $preTaxBenefitRows): ?><?php foreach($preTaxBenefitRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employees_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employer_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_contribution'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='donations-summary' && $donationSummaryRows): ?><?php foreach($donationSummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employees_contribution'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='reimbursement-summary' && $reimbursementSummaryRows): ?><?php foreach($reimbursementSummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)($row['employee_code']!==''?$row['employee_code']:$row['employee_id'])); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)($row['reimbursement_type']?:'-')); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['eligible_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['paid_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['unclaimed_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='perquisite-summary' && $perquisiteRows): ?><?php foreach($perquisiteRows as $row): ?><tr><td><?php echo htmlspecialchars((string)($row['employee_code']!==''?$row['employee_code']:$row['employee_id'])); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employer_contribution_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_amount_to_deduct'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['chargeable_tax'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='full-and-final-settlement' && $fullFinalRows): ?><?php foreach($fullFinalRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['designation']); ?></td><td><?php echo htmlspecialchars(payroll_date_label((string)$row['date_of_joining'])); ?></td><td><?php echo htmlspecialchars(payroll_date_label((string)$row['last_working_date'])); ?></td><td><?php echo htmlspecialchars((string)$row['service_period']); ?></td><td><?php echo htmlspecialchars((string)$row['reason_for_exit']); ?></td><td><?php echo htmlspecialchars(payroll_date_label((string)$row['settlement_date'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['settlement_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='salary-revision-report' && $salaryRevisionRows): ?><?php foreach($salaryRevisionRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['previous_ctc'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['revised_ctc'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['difference'])); ?></td><td><?php echo htmlspecialchars(payroll_date_label((string)$row['effective_from'])); ?></td><td><?php echo htmlspecialchars((string)$row['payout_month']); ?></td><td><?php echo htmlspecialchars((string)$row['status']); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='salary-revision-history' && $salaryRevisionHistoryRows): ?><?php foreach($salaryRevisionHistoryRows as $row): ?><tr><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['previous_ctc'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['revised_ctc'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['difference'])); ?></td><td><?php echo htmlspecialchars(payroll_date_label((string)$row['effective_from'])); ?></td><td><?php echo htmlspecialchars((string)$row['payout_month']); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='salary-withhold-report' && $salaryWithholdRows): ?><?php foreach($salaryWithholdRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['designation']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_status']); ?></td><td><?php echo htmlspecialchars((string)$row['withheld_month']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['amount_to_pay'])); ?></td><td><?php echo htmlspecialchars((string)$row['withheld_reason']); ?></td><td><?php echo htmlspecialchars((string)$row['release_status']); ?></td><td><?php echo htmlspecialchars((string)$row['release_month']); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='investment-declaration-report' && $investmentDeclarationRows): ?><?php foreach($investmentDeclarationRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['tax_regime']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['chapter_vi_a'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['allowance_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['hra_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['other_income_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['previous_employment_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['direct_tax_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='proof-of-investment-report' && $proofInvestmentRows): ?><?php foreach($proofInvestmentRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_date_label((string)$row['submitted_on'])); ?></td><td><?php echo htmlspecialchars((string)$row['approver_name']); ?></td><td><?php echo htmlspecialchars((string)$row['status']); ?></td><td><?php echo htmlspecialchars((string)$row['tax_regime']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['actual_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['approved_amount'])); ?></td><td><?php echo htmlspecialchars((string)$row['document_count']); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='loan-outstanding-summary' && $loanOutstandingRows): ?><?php foreach($loanOutstandingRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_number']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['loan_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['outstanding_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='loan-perquisite-summary' && $loanPerquisiteRows): ?><?php foreach($loanPerquisiteRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_number']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['loan_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['perquisite_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='loan-perquisite-projection' && $loanPerquisiteProjectionRows): ?><?php foreach($loanPerquisiteProjectionRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_number']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['projected_perquisite_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='loan-overall-summary' && $loanOverallRows): ?><?php foreach($loanOverallRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_number']); ?></td><td><?php echo htmlspecialchars((string)$row['loan_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['loan_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['outstanding_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['perquisite_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='journal' && $journalRows): ?><?php foreach($journalRows as $row): ?><tr><td><?php echo htmlspecialchars(payroll_date_label((string)$row['journal_date'])); ?></td><td><?php echo htmlspecialchars((string)$row['entry_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['debit_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['credit_amount'])); ?></td><td><?php echo htmlspecialchars((string)($row['reference_no']?:'-')); ?></td><td><?php echo htmlspecialchars((string)($row['notes']?:'-')); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='activity-log' && $activityLogRows): ?><?php foreach($activityLogRows as $row): ?><tr><td><?php echo htmlspecialchars(date('d/m/Y h:i A',strtotime((string)$row['activity_time']))); ?></td><td><?php echo htmlspecialchars((string)$row['activity_details']); ?></td><td><?php echo htmlspecialchars((string)$row['description']).(!empty($row['performed_by'])?' by '.htmlspecialchars((string)$row['performed_by']):''); ?></td><td><a href="<?php echo htmlspecialchars(rurl('audit-trail',['activity_log_id'=>(int)$row['id'],'period'=>$period,'from_date'=>$rangeStartSql,'to_date'=>$rangeEndSql])); ?>"><i class="fa-solid fa-angle-right"></i></a></td></tr><?php endforeach; ?>
<?php elseif($view==='payroll-liability' && $liabilityRows): ?><?php foreach($liabilityRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['liability_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employees_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employer_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_contribution'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='leave-encashment-summary' && $leaveRows): ?><?php foreach($leaveRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['days']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='lop-summary' && $lopRows): ?><?php foreach($lopRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['lop_days']); ?></td><td><?php echo htmlspecialchars((string)$row['lop_adjustment_days']); ?></td><td><?php echo htmlspecialchars((string)$row['actual_lop_days']); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='tds-summary' && $tdsRows): ?><?php foreach($tdsRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['pan']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['taxable_amount_year'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['tax_on_income'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['surcharge_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['cess_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_tds_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='epf-summary' && $epfSummaryRows): ?><?php foreach($epfSummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['pf_account_number']); ?></td><td><?php echo htmlspecialchars((string)$row['uan']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['pf_wage'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employee_pf_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employee_vpf_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employer_pf_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employer_eps_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employer_edli_amount'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['pf_admin_charges'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_contribution'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='epf-ecr-report' && $epfEcrRows): ?><?php foreach($epfEcrRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['uan']); ?></td><td><?php echo htmlspecialchars((string)$row['member_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['gross_wages'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['epf_wages'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['eps_wages'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['edli_wages'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['epf_contribution_remitted'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['eps_contribution_remitted'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['epf_eps_diff_remitted'])); ?></td><td><?php echo htmlspecialchars((string)$row['ncp_days']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['refund_of_advances'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='esi-summary' && $esiSummaryRows): ?><?php foreach($esiSummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['esi_number']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['esi_wages'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employees_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employers_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_contribution'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='esic-return-report' && $esicReturnRows): ?><?php foreach($esicReturnRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['insurance_person_number']); ?></td><td><?php echo htmlspecialchars((string)$row['insurance_person_name']); ?></td><td><?php echo htmlspecialchars((string)$row['paid_days']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_monthly_wages'])); ?></td><td><?php echo htmlspecialchars((string)$row['reason_code_zero_working_days']); ?></td><td><?php echo htmlspecialchars((string)$row['last_working_day']); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='pt-summary' && $ptSummaryRows): ?><?php foreach($ptSummaryRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars((string)$row['work_location']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['pt_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='pt-monthly-statement' && $ptMonthlyRows): ?><?php foreach($ptMonthlyRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['pt_wages'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['pt_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='pt-annual-return-statement' && $ptAnnualRows): ?><?php foreach($ptAnnualRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['period_label']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_count']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['pt_amount'])); ?></td></tr><?php endforeach; ?>
<?php elseif($view==='lwf-summary' && $lwfRows): ?><?php foreach($lwfRows as $row): ?><tr><td><?php echo htmlspecialchars((string)$row['employee_id']); ?></td><td><?php echo htmlspecialchars((string)$row['employee_name']); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employees_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['employers_contribution'])); ?></td><td><?php echo htmlspecialchars(payroll_format_currency((float)$row['total_contribution'])); ?></td></tr><?php endforeach; ?>
<?php else: ?><tr><td colspan="<?php echo count($columns[$view]); ?>" class="reports-table-empty"><?php echo htmlspecialchars($emptyMessages[$view]); ?></td></tr><?php endif; ?></tbody></table></div><?php endif; ?>
</div><?php endif; ?></div></div></section><?php endif; ?></main></div>
<script>(function(){const bindMenu=(toggleSel,menuSel)=>{const t=document.querySelector(toggleSel),m=document.querySelector(menuSel);if(!t||!m)return;t.addEventListener('click',e=>{e.stopPropagation();m.classList.toggle('open')});document.addEventListener('click',e=>{if(!m.contains(e.target)&&!t.contains(e.target))m.classList.remove('open')});};bindMenu('[data-report-period-toggle]','[data-report-period-menu]');bindMenu('[data-earning-toggle]','[data-earning-menu]');bindMenu('[data-history-toggle]','[data-history-menu]');bindMenu('[data-fiscal-toggle]','[data-fiscal-menu]');})();</script>
</body></html>

