<?php
/* Enhanced FNPF Deduction Report — React/Ant Design Dashboard */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
ob_start();
include('includes/session.inc');
$Title=_('FNPF Deduction Report');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');
include('includes/GetPaymentMethods.php');
include('includes/GetPrice.inc');

/* ── Loading Modal (flush first) ── */
?>
<div id="fnpf-loading-modal" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(255,255,255,0.92);z-index:99999;display:flex;align-items:center;justify-content:center;flex-direction:column;">
    <div style="text-align:center;">
        <div style="width:44px;height:44px;border:4px solid #E6F7F8;border-top:4px solid #2AABB3;border-radius:50%;animation:fnpf-spin 0.8s linear infinite;margin:0 auto 14px;"></div>
        <div style="font-family:'Poppins',sans-serif;font-size:14px;color:#1F2937;font-weight:500;">Loading FNPF Report...</div>
        <div id="fnpf-load-timer" style="font-family:'Poppins',sans-serif;font-size:12px;color:#6B7280;margin-top:4px;">0s</div>
    </div>
</div>
<style>@keyframes fnpf-spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style>
<script>(function(){var s=0,el=document.getElementById('fnpf-load-timer');window._fnpfT=setInterval(function(){s++;if(el)el.textContent=s+'s';},1000);})();</script>
<?php ob_flush(); flush(); ?>

<?php
/* ══════════════════════════════════════════════
   Dashboard Data — direct mysqli (optimized)
   ══════════════════════════════════════════════ */
$dbHost='localhost'; $dbUser='sooggoo'; $dbPass='4Compassion*'; $dbName='evergreenint';
$dbc = new mysqli($dbHost,$dbUser,$dbPass,$dbName);
if($dbc->connect_error) $dbc=null;

$totalEmployees=0; $totalGross=0; $totalEmployeeContrib=0; $totalEmployerContrib=0;
$totalCompulsory=0; $avgContribPerEmp=0;
$byDepartment=array(); $recentPeriods=array(); $topContributors=array();
$calendarPeriods=array();

if($dbc){

    /* Q1: Overall FNPF summary (latest 5 periods) */
    $r = $dbc->query("SELECT COUNT(DISTINCT p.employeeid) as emp_count,
        IFNULL(SUM(p.totalgross_amount),0) as total_gross,
        IFNULL(SUM(p.employee_fnpf),0) as emp_contrib,
        IFNULL(SUM(p.fnpf_employer),0) as er_contrib
        FROM payrun_details p
        INNER JOIN calendar_management c ON p.id=c.id
        ORDER BY p.id DESC");
    if($r){
        $row=$r->fetch_assoc();
        if($row){
            $totalEmployees=intval($row['emp_count']);
            $totalGross=floatval($row['total_gross']);
            $totalEmployeeContrib=floatval($row['emp_contrib']);
            $totalEmployerContrib=floatval($row['er_contrib']);
            $totalCompulsory=$totalEmployeeContrib+$totalEmployerContrib;
            $avgContribPerEmp=$totalEmployees>0?round($totalCompulsory/$totalEmployees,2):0;
        }
        $r->free();
    }

    /* Q2: Contributions by recent periods (last 8) */
    $r = $dbc->query("SELECT p.id, c.end_date,
        COUNT(DISTINCT p.employeeid) as emp_count,
        IFNULL(SUM(p.employee_fnpf),0) as emp_contrib,
        IFNULL(SUM(p.fnpf_employer),0) as er_contrib
        FROM payrun_details p
        INNER JOIN calendar_management c ON p.id=c.id
        GROUP BY p.id ORDER BY p.id DESC LIMIT 8");
    if($r){
        while($row=$r->fetch_assoc()){
            $recentPeriods[] = array(
                'id'=>$row['id'],
                'end_date'=>isset($row['end_date'])?$row['end_date']:'',
                'emp_count'=>intval($row['emp_count']),
                'emp_contrib'=>floatval($row['emp_contrib']),
                'er_contrib'=>floatval($row['er_contrib']),
                'total'=>floatval($row['emp_contrib'])+floatval($row['er_contrib'])
            );
        }
        $r->free();
        $recentPeriods=array_reverse($recentPeriods); // chronological for chart
    }

    /* Q3: By department (latest period only for speed) */
    $latestId=0;
    $r2=$dbc->query("SELECT MAX(id) as mid FROM payrun_details");
    if($r2){ $rr=$r2->fetch_assoc(); $latestId=intval($rr['mid']); $r2->free(); }

    if($latestId>0){
        $r = $dbc->query("SELECT d.departmentname as dept,
            COUNT(DISTINCT p.employeeid) as cnt,
            IFNULL(SUM(p.employee_fnpf),0) as emp_c,
            IFNULL(SUM(p.fnpf_employer),0) as er_c
            FROM payrun_details p
            LEFT JOIN employeemaster e ON p.employeeid=e.employeeid
            LEFT JOIN department d ON e.department=d.departmentid
            WHERE p.id='".$latestId."'
            GROUP BY e.department ORDER BY emp_c DESC LIMIT 6");
        if($r){
            while($row=$r->fetch_assoc()){
                $byDepartment[]=array(
                    'name'=>(isset($row['dept'])&&$row['dept'])?$row['dept']:'Unassigned',
                    'count'=>intval($row['cnt']),
                    'employee'=>floatval($row['emp_c']),
                    'employer'=>floatval($row['er_c'])
                );
            }
            $r->free();
        }
    }

    /* Q4: Top contributors (latest period) */
    if($latestId>0){
        $r = $dbc->query("SELECT e.first_name, e.last_name, e.fnpf,
            p.employee_fnpf as emp_c, p.fnpf_employer as er_c,
            (p.employee_fnpf + p.fnpf_employer) as total_c
            FROM payrun_details p
            LEFT JOIN employeemaster e ON p.employeeid=e.employeeid
            WHERE p.id='".$latestId."' AND (p.employee_fnpf+p.fnpf_employer)>0
            ORDER BY total_c DESC LIMIT 6");
        if($r){
            while($row=$r->fetch_assoc()) $topContributors[]=$row;
            $r->free();
        }
    }

    /* Calendar periods for form dropdowns */
    $r = $dbc->query("SELECT id, end_date FROM calendar_management ORDER BY id DESC");
    if($r){
        while($row=$r->fetch_assoc()) $calendarPeriods[]=$row;
        $r->free();
    }

    $dbc->close();
}

$recentPeriodsJSON=json_encode($recentPeriods);
$byDepartmentJSON=json_encode($byDepartment);
$topContributorsJSON=json_encode($topContributors);

$userid = isset($_SESSION['UserID']) ? $_SESSION['UserID'] : '';
$isAuthorized = ($userid=='admin'||$userid=='jprasad'||$userid=='sharukh'||$userid=='mkhan');
$isSubmitted = isset($_POST['quote']);
?>

<!-- Chart.js + Icons -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>

<style>
.fnpf-page *{box-sizing:border-box;font-family:'Poppins',sans-serif;}

/* Banner */
.fnpf-banner{background:linear-gradient(135deg,#2AABB3 0%,#1E8F96 50%,#187278 100%);border-radius:12px;padding:24px 28px;margin:0 0 20px 0;color:#fff;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;}
.fnpf-banner h1{font-size:20px;font-weight:700;margin:0 0 3px 0;color:#fff;}
.fnpf-breadcrumb{font-size:12px;opacity:0.85;display:flex;align-items:center;gap:5px;}
.fnpf-breadcrumb a{color:#fff;text-decoration:none;opacity:0.8;}
.fnpf-breadcrumb a:hover{opacity:1;}
.fnpf-banner-btn{background:rgba(255,255,255,0.18);border:1px solid rgba(255,255,255,0.25);color:#fff;border-radius:8px;padding:7px 14px;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s;display:inline-flex;align-items:center;gap:5px;text-decoration:none;}
.fnpf-banner-btn:hover{background:rgba(255,255,255,0.28);color:#fff;}

/* Toggle */
.fnpf-dash-toggle{display:flex;align-items:center;gap:7px;padding:8px 0;margin-bottom:6px;cursor:pointer;font-size:13px;font-weight:600;color:#1F2937;user-select:none;}
.fnpf-dash-toggle i{color:#2AABB3;transition:transform 0.3s;font-size:11px;}
.fnpf-dash-toggle.collapsed i{transform:rotate(-90deg);}

/* KPIs */
.fnpf-kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px;}
.fnpf-kpi-card{background:#fff;border-radius:10px;padding:16px 18px;border:1px solid #E5E7EB;border-left:4px solid #2AABB3;display:flex;align-items:center;gap:12px;transition:box-shadow 0.2s;}
.fnpf-kpi-card:hover{box-shadow:0 3px 10px rgba(42,171,179,0.1);}
.fnpf-kpi-card.warning{border-left-color:#FAAD14;}
.fnpf-kpi-card.success{border-left-color:#52C41A;}
.fnpf-kpi-card.danger{border-left-color:#FF4D4F;}
.fnpf-kpi-card.info{border-left-color:#1890FF;}
.fnpf-kpi-card.purple{border-left-color:#722ED1;}
.fnpf-kpi-icon{width:40px;height:40px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0;}
.fnpf-kpi-icon.primary{background:#E6F7F8;color:#2AABB3;}
.fnpf-kpi-icon.warning{background:#FFF8E6;color:#FAAD14;}
.fnpf-kpi-icon.success{background:#E8F8E8;color:#52C41A;}
.fnpf-kpi-icon.danger{background:#FFE8E8;color:#FF4D4F;}
.fnpf-kpi-icon.info{background:#E6F0FF;color:#1890FF;}
.fnpf-kpi-icon.purple{background:#F3E8FF;color:#722ED1;}
.fnpf-kpi-value{font-size:20px;font-weight:700;color:#1F2937;line-height:1.2;}
.fnpf-kpi-label{font-size:11px;color:#6B7280;font-weight:500;margin-top:1px;}

/* Charts */
.fnpf-chart-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-bottom:20px;}
.fnpf-chart-card{background:#fff;border-radius:10px;border:1px solid #E5E7EB;padding:16px 18px;}
.fnpf-chart-title{font-size:13px;font-weight:600;color:#1F2937;margin:0 0 12px 0;display:flex;align-items:center;gap:7px;}
.fnpf-chart-title i{color:#2AABB3;font-size:13px;}
.fnpf-chart-wrap{position:relative;width:100%;height:200px;max-height:200px;overflow:hidden;}

/* Panels */
.fnpf-panel-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;margin-bottom:20px;}
.fnpf-panel-card{background:#fff;border-radius:10px;border:1px solid #E5E7EB;padding:16px 18px;max-height:310px;overflow-y:auto;}
.fnpf-panel-card::-webkit-scrollbar{width:4px;}
.fnpf-panel-card::-webkit-scrollbar-thumb{background:#d1d5db;border-radius:4px;}
.fnpf-panel-title{font-size:13px;font-weight:600;color:#1F2937;margin:0 0 10px 0;display:flex;align-items:center;gap:7px;}
.fnpf-panel-title i{color:#2AABB3;}
.fnpf-list-row{display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid #F3F4F6;gap:8px;}
.fnpf-list-row:last-child{border-bottom:none;}
.fnpf-list-name{font-size:12px;color:#1F2937;font-weight:500;}
.fnpf-list-sub{font-size:11px;color:#6B7280;}
.fnpf-list-amount{font-size:12px;font-weight:600;color:#1F2937;text-align:right;white-space:nowrap;}

/* Progress */
.fnpf-progress-wrap{display:flex;align-items:center;gap:8px;margin-bottom:8px;}
.fnpf-progress-label{font-size:11px;color:#1F2937;font-weight:500;width:90px;flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.fnpf-progress-bar{flex:1;height:7px;background:#F3F4F6;border-radius:4px;overflow:hidden;}
.fnpf-progress-fill{height:100%;border-radius:4px;}
.fnpf-progress-val{font-size:11px;color:#6B7280;font-weight:600;width:65px;text-align:right;}

/* ── Modern Form Styling ── */
.fnpf-form-card{background:#fff;border-radius:12px;border:1px solid #E5E7EB;padding:28px 32px;margin-bottom:24px;max-width:700px;}
.fnpf-form-card h3{font-size:16px;font-weight:600;color:#1F2937;margin:0 0 6px 0;display:flex;align-items:center;gap:8px;}
.fnpf-form-card h3 i{color:#2AABB3;}
.fnpf-form-card p{font-size:12px;color:#6B7280;margin:0 0 20px 0;}
.fnpf-form-group{margin-bottom:16px;}
.fnpf-form-group label{display:block;font-size:12px;font-weight:600;color:#374151;margin-bottom:5px;}
.fnpf-form-group select{width:100%;padding:9px 12px;border:1px solid #D1D5DB;border-radius:8px;font-family:'Poppins',sans-serif;font-size:13px;color:#1F2937;background:#fff;outline:none;transition:border 0.2s;appearance:auto;}
.fnpf-form-group select:focus{border-color:#2AABB3;box-shadow:0 0 0 3px rgba(42,171,179,0.12);}
.fnpf-form-submit{background:linear-gradient(135deg,#2AABB3,#1E8F96);color:#fff;border:none;border-radius:8px;padding:10px 28px;font-family:'Poppins',sans-serif;font-size:13px;font-weight:600;cursor:pointer;transition:all 0.2s;display:inline-flex;align-items:center;gap:7px;margin-top:4px;}
.fnpf-form-submit:hover{box-shadow:0 4px 12px rgba(42,171,179,0.3);transform:translateY(-1px);}
.fnpf-form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;}

/* ── Report Results Styling ── */
.fnpf-report-wrapper{background:#fff;border-radius:12px;border:1px solid #E5E7EB;padding:20px 24px;margin-bottom:24px;}
.fnpf-report-wrapper .table-responsive{margin:0;}
.fnpf-report-wrapper table.dataTable thead th{background:linear-gradient(135deg,#2AABB3,#1E8F96)!important;color:#fff!important;font-family:'Poppins',sans-serif!important;font-size:11px!important;font-weight:600!important;padding:10px 8px!important;}
.fnpf-report-wrapper table.dataTable tbody td{font-family:'Poppins',sans-serif!important;font-size:12px!important;padding:8px!important;}
.fnpf-report-wrapper table.dataTable tbody tr:hover td{background:#E6F7F8!important;}
.fnpf-report-wrapper table.dataTable tfoot td{font-family:'Poppins',sans-serif!important;font-size:12px!important;background:#F9FAFB!important;}

/* Dashboard collapse */
.fnpf-dashboard{transition:max-height 0.4s ease,opacity 0.3s ease;overflow:hidden;}
.fnpf-dashboard.hidden{max-height:0!important;opacity:0;padding:0!important;margin:0!important;}

/* Responsive */
@media(max-width:1200px){.fnpf-kpi-grid{grid-template-columns:repeat(2,1fr);}}
@media(max-width:768px){.fnpf-kpi-grid{grid-template-columns:1fr;}.fnpf-chart-grid,.fnpf-panel-grid{grid-template-columns:1fr;}.fnpf-banner{padding:16px;}.fnpf-banner h1{font-size:16px;}.fnpf-form-row{grid-template-columns:1fr;}}
</style>

<div class="fnpf-page" style="padding:0 8px;">

<!-- ── Banner ── -->
<div class="fnpf-banner">
    <div>
        <h1><i class="fas fa-university" style="margin-right:7px;"></i> FNPF Deduction Report</h1>
        <div class="fnpf-breadcrumb">
            <a href="index.php"><i class="fas fa-home"></i> Home</a><span>/</span>
            <a href="#">Payroll</a><span>/</span>
            <a href="#">Reports</a><span>/</span>
            <span>FNPF Deductions</span>
        </div>
    </div>
    <div>
        <button class="fnpf-banner-btn" onclick="window.location.reload()"><i class="fas fa-sync-alt"></i> Refresh</button>
        <a class="fnpf-banner-btn" href="<?php echo htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8'); ?>"><i class="fas fa-file-alt"></i> New Report</a>
    </div>
</div>

<?php if($isAuthorized): ?>

<!-- ── Toggle ── -->
<div class="fnpf-dash-toggle" id="fnpf-dash-toggle" onclick="fnpfToggleDash()">
    <i class="fas fa-chevron-down"></i>
    <span>Dashboard Overview</span>
    <span style="font-size:11px;font-weight:400;color:#6B7280;margin-left:4px;" id="fnpf-toggle-hint">(click to collapse)</span>
</div>

<!-- ── Dashboard ── -->
<div class="fnpf-dashboard" id="fnpf-dashboard">

    <!-- KPI Row 1 -->
    <div class="fnpf-kpi-grid">
        <div class="fnpf-kpi-card">
            <div class="fnpf-kpi-icon primary"><i class="fas fa-users"></i></div>
            <div><div class="fnpf-kpi-value"><?php echo number_format($totalEmployees); ?></div><div class="fnpf-kpi-label">Contributing Employees</div></div>
        </div>
        <div class="fnpf-kpi-card success">
            <div class="fnpf-kpi-icon success"><i class="fas fa-hand-holding-usd"></i></div>
            <div><div class="fnpf-kpi-value">$<?php echo number_format($totalEmployeeContrib,2); ?></div><div class="fnpf-kpi-label">Total Employee FNPF</div></div>
        </div>
        <div class="fnpf-kpi-card info">
            <div class="fnpf-kpi-icon info"><i class="fas fa-building"></i></div>
            <div><div class="fnpf-kpi-value">$<?php echo number_format($totalEmployerContrib,2); ?></div><div class="fnpf-kpi-label">Total Employer FNPF</div></div>
        </div>
        <div class="fnpf-kpi-card warning">
            <div class="fnpf-kpi-icon warning"><i class="fas fa-coins"></i></div>
            <div><div class="fnpf-kpi-value">$<?php echo number_format($totalCompulsory,2); ?></div><div class="fnpf-kpi-label">Total Compulsory</div></div>
        </div>
    </div>

    <!-- KPI Row 2 -->
    <div class="fnpf-kpi-grid">
        <div class="fnpf-kpi-card purple">
            <div class="fnpf-kpi-icon purple"><i class="fas fa-dollar-sign"></i></div>
            <div><div class="fnpf-kpi-value">$<?php echo number_format($totalGross,2); ?></div><div class="fnpf-kpi-label">Total Gross Amount</div></div>
        </div>
        <div class="fnpf-kpi-card danger">
            <div class="fnpf-kpi-icon danger"><i class="fas fa-user-check"></i></div>
            <div><div class="fnpf-kpi-value">$<?php echo number_format($avgContribPerEmp,2); ?></div><div class="fnpf-kpi-label">Avg Contrib/Employee</div></div>
        </div>
        <div class="fnpf-kpi-card">
            <div class="fnpf-kpi-icon primary"><i class="fas fa-percentage"></i></div>
            <div><div class="fnpf-kpi-value"><?php echo $totalGross>0?round(($totalEmployeeContrib/$totalGross)*100,1):0; ?>%</div><div class="fnpf-kpi-label">Employee Rate</div></div>
        </div>
        <div class="fnpf-kpi-card success">
            <div class="fnpf-kpi-icon success"><i class="fas fa-percentage"></i></div>
            <div><div class="fnpf-kpi-value"><?php echo $totalGross>0?round(($totalEmployerContrib/$totalGross)*100,1):0; ?>%</div><div class="fnpf-kpi-label">Employer Rate</div></div>
        </div>
    </div>

    <!-- Charts -->
    <div class="fnpf-chart-grid">
        <div class="fnpf-chart-card">
            <div class="fnpf-chart-title"><i class="fas fa-chart-line"></i> Contributions by Period (Last 8)</div>
            <div class="fnpf-chart-wrap"><canvas id="fnpfTrendChart"></canvas></div>
        </div>
        <div class="fnpf-chart-card">
            <div class="fnpf-chart-title"><i class="fas fa-chart-pie"></i> Employee vs Employer Split</div>
            <div class="fnpf-chart-wrap"><canvas id="fnpfSplitChart"></canvas></div>
        </div>
    </div>

    <div class="fnpf-chart-grid">
        <div class="fnpf-chart-card">
            <div class="fnpf-chart-title"><i class="fas fa-building"></i> By Department (Latest Period)</div>
            <div class="fnpf-chart-wrap"><canvas id="fnpfDeptChart"></canvas></div>
        </div>
        <div class="fnpf-chart-card">
            <div class="fnpf-panel-title"><i class="fas fa-trophy"></i> Top Contributors (Latest Period)</div>
            <div id="fnpf-toplist" style="max-height:180px;overflow-y:auto;"></div>
        </div>
    </div>

    <!-- Department Progress -->
    <?php if(count($byDepartment)>0): ?>
    <div class="fnpf-chart-card" style="margin-bottom:20px;">
        <div class="fnpf-chart-title"><i class="fas fa-chart-bar"></i> Department Contribution Breakdown</div>
        <div id="fnpf-deptprog"></div>
    </div>
    <?php endif; ?>

</div><!-- end dashboard -->

<!-- ══════════════════════════════════════
     Form / Report Section (preserved logic)
     ══════════════════════════════════════ -->

<?php
if($isSubmitted){
    $fromid = intval($_POST['fromdate']);
    $toid   = intval($_POST['todate']);
?>

<!-- Report Results -->
<div class="fnpf-report-wrapper">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:8px;">
        <div>
            <h3 style="font-size:15px;font-weight:600;color:#1F2937;margin:0;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-table" style="color:#2AABB3;"></i> FNPF Report — Period <?php echo $fromid; ?> to <?php echo $toid; ?>
            </h3>
            <p style="font-size:11px;color:#6B7280;margin:4px 0 0 0;">Generated: <?php echo date('d M Y, h:i A'); ?></p>
        </div>
        <a class="fnpf-banner-btn" href="<?php echo htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8'); ?>" style="background:#2AABB3;border-color:#2AABB3;">
            <i class="fas fa-arrow-left"></i> Back to Form
        </a>
    </div>

    <!-- DataTables CSS/JS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css"/>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css"/>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>

    <div class="table-responsive">
    <table id="projectreport" class="display nowrap" style="width:100%">
        <thead>
            <tr class="info">
                <th><?php echo _('Employee ID'); ?></th>
                <th><?php echo _('FNPF Member No:'); ?></th>
                <th><?php echo _('TIN:'); ?></th>
                <th><?php echo _('First Name'); ?></th>
                <th><?php echo _('Middle Name'); ?></th>
                <th><?php echo _('Last Name'); ?></th>
                <th><?php echo _('Total Gross Amount'); ?></th>
                <th><?php echo _('Employee Contribution'); ?></th>
                <th><?php echo _('Employer Contribution'); ?></th>
                <th><?php echo _('Total Compulsory Amount'); ?></th>
            </tr>
        </thead>
        <tbody>
    <?php
    $grandtotal = 0;
    $querypayrun = "
        SELECT payrun_details.id, payrun_details.employeeid, employeemaster.fnpf, employeemaster.tin, employeemaster.first_name,
               employeemaster.middle_name, employeemaster.last_name,
               SUM(payrun_details.totalgross_amount) as totalgross,
               SUM(payrun_details.employee_fnpf) as totalemployee,
               SUM(payrun_details.fnpf_employer) as totalemployer
        FROM payrun_details
        INNER JOIN calendar_management on payrun_details.id = calendar_management.id
        INNER JOIN employeemaster on payrun_details.employeeid = employeemaster.employeeid
        WHERE payrun_details.id BETWEEN '" . $fromid . "' AND '" . $toid . "'
        GROUP BY payrun_details.employeeid
    ";
    $resultpayrun = DB_query($querypayrun);

    while ($myrowpayrun = DB_fetch_array($resultpayrun)) {
        $totalamounttopay = $myrowpayrun['totalemployee'] + $myrowpayrun['totalemployer'];
        if ($myrowpayrun['id'] <= 112) {
            $totalgrossamount = round($totalamounttopay / 0.14, 2);
        } else {
            $totalgrossamount = round($totalamounttopay / 0.18, 2);
        }

        if ($totalamounttopay > 0) {
            echo '<tr>
                <td>' . $myrowpayrun['employeeid'] . '</td>
                <td>' . $myrowpayrun['fnpf'] . '</td>
                <td>' . $myrowpayrun['tin'] . '</td>
                <td>' . $myrowpayrun['first_name'] . '</td>
                <td>' . $myrowpayrun['middle_name'] . '</td>
                <td>' . $myrowpayrun['last_name'] . '</td>
                <td>' . $totalgrossamount . '</td>
                <td>' . $myrowpayrun['totalemployee'] . '</td>
                <td>' . $myrowpayrun['totalemployer'] . '</td>
                <td>' . $totalamounttopay . '</td>
            </tr>';
            $grandtotal += $totalamounttopay;
        }
    }
    ?>
        </tbody>
        <tfoot>
            <tr>
                <td><b>Grand Total Amount:</b></td>
                <td colspan="8"></td>
                <td><b><?php echo round($grandtotal,2); ?></b></td>
            </tr>
        </tfoot>
    </table>
    </div>

    <script>
    $(document).ready(function() {
        $('#projectreport').DataTable({
            dom: 'Bfrtip',
            buttons: [
                { extend:'pdfHtml5', orientation:'portrait', pageSize:'A4',
                  customize:function(doc){ doc.defaultStyle.fontSize=10; } },
                { extend:'excelHtml5' },
                { extend:'copyHtml5' }
            ]
        });
    });
    </script>
</div><!-- end report wrapper -->

<?php
} else {
    // ── Show Form ──
?>

<div class="fnpf-form-card">
    <h3><i class="fas fa-filter"></i> Generate FNPF Report</h3>
    <p>FNPF General Report for in-house use only. Select the period range below.</p>

    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8'); ?>">
        <input type="hidden" name="FormID" value="<?php echo isset($_SESSION['FormID']) ? $_SESSION['FormID'] : ''; ?>" />

        <div class="fnpf-form-row">
            <div class="fnpf-form-group">
                <label><i class="fas fa-calendar-alt" style="color:#2AABB3;margin-right:4px;"></i> From Period</label>
                <select name="fromdate" required>
                    <?php foreach($calendarPeriods as $cp): ?>
                    <option value="<?php echo $cp['id']; ?>"><?php echo $cp['id'].' - '.$cp['end_date']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fnpf-form-group">
                <label><i class="fas fa-calendar-check" style="color:#2AABB3;margin-right:4px;"></i> To Period</label>
                <select name="todate" required>
                    <?php foreach($calendarPeriods as $cp): ?>
                    <option value="<?php echo $cp['id']; ?>"><?php echo $cp['id'].' - '.$cp['end_date']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <button type="submit" name="quote" class="fnpf-form-submit">
            <i class="fas fa-search"></i> Generate Report
        </button>
    </form>
</div>

<?php
}
// end form/report
?>

<?php else: ?>
    <div style="background:#fff;border-radius:10px;border:1px solid #E5E7EB;padding:40px;text-align:center;margin:20px 0;">
        <i class="fas fa-lock" style="font-size:32px;color:#FF4D4F;margin-bottom:12px;"></i>
        <p style="font-size:14px;color:#1F2937;font-weight:500;">Not authorized to view this section</p>
    </div>
<?php endif; ?>

</div><!-- end fnpf-page -->

</div></div></div>

<div id="m_scroll_top" class="m-scroll-top"><i class="la la-arrow-up"></i></div>
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

<?php
include('includes/MainMenuLinksArray.php');
if(isset($SupplierLogin) AND $SupplierLogin==1){
    echo '<table class="table_index"><tr><td class="menu_group_item"><p>&bull; <a href="'.$RootPath.'/SupplierTenders.php?TenderType=1">'._('View or Amend outstanding offers').'</a></p></td></tr><tr><td class="menu_group_item"><p>&bull; <a href="'.$RootPath.'/SupplierTenders.php?TenderType=2">'._('Create a new offer').'</a></p></td></tr><tr><td class="menu_group_item"><p>&bull; <a href="'.$RootPath.'/SupplierTenders.php?TenderType=3">'._('View any open tenders without an offer').'</a></p></td></tr></table>';
    include('includes/footer.inc'); exit;
} elseif(isset($CustomerLogin) AND $CustomerLogin==1){
    echo '<table class="table_index"><tr><td class="menu_group_item"><p>&bull; <a href="'.$RootPath.'/CustomerInquiry.php?CustomerID='.$_SESSION['CustomerID'].'">'._('Account Status').'</a></p></td></tr><tr><td class="menu_group_item"><p>&bull; <a href="'.$RootPath.'/SelectOrderItems.php?NewOrder=Yes">'._('Place An Order').'</a></p></td></tr><tr><td class="menu_group_item"><p>&bull; <a href="'.$RootPath.'/SelectCompletedOrder.php?SelectedCustomer='.$_SESSION['CustomerID'].'">'._('Order Status').'</a></p></td></tr></table>';
    include('includes/footer.inc'); exit;
}
if(isset($_GET['Application'])){ $_SESSION['Module']=$_GET['Application']; }
?>

<!-- ══════════════════════════════════════
     Dashboard JS — Optimized
     • animation:false, fixed 200px chart wraps
     • data capped at 6-8 items
     ══════════════════════════════════════ -->
<script>
document.addEventListener('DOMContentLoaded', function(){
    // Kill loader
    var lm = document.getElementById('fnpf-loading-modal');
    if(lm) lm.style.display = 'none';
    clearInterval(window._fnpfT);

    var PERIODS = <?php echo $recentPeriodsJSON; ?>;
    var DEPT    = <?php echo $byDepartmentJSON; ?>;
    var TOPC    = <?php echo $topContributorsJSON; ?>;

    var COLORS = ['#2AABB3','#1E8F96','#187278','#52C41A','#FAAD14','#FF4D4F'];
    var BASE = {animation:false, responsive:true, maintainAspectRatio:false};

    /* ── Trend Line Chart (contributions over periods) ── */
    if(PERIODS.length > 0){
        var labels = PERIODS.map(function(d){
            if(d.end_date){
                var parts = d.end_date.split('-');
                return (parts[2]||'')+' '+(parts[1]||'');
            }
            return 'P'+d.id;
        });
        new Chart(document.getElementById('fnpfTrendChart'), {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Employee',
                        data: PERIODS.map(function(d){return d.emp_contrib;}),
                        borderColor: '#2AABB3',
                        backgroundColor: 'rgba(42,171,179,0.1)',
                        fill: true,
                        tension: 0.3,
                        pointRadius: 3,
                        pointBackgroundColor: '#2AABB3',
                        borderWidth: 2
                    },
                    {
                        label: 'Employer',
                        data: PERIODS.map(function(d){return d.er_contrib;}),
                        borderColor: '#FAAD14',
                        backgroundColor: 'rgba(250,173,20,0.1)',
                        fill: true,
                        tension: 0.3,
                        pointRadius: 3,
                        pointBackgroundColor: '#FAAD14',
                        borderWidth: 2
                    }
                ]
            },
            options: Object.assign({}, BASE, {
                plugins: { legend:{position:'bottom', labels:{padding:10, usePointStyle:true, font:{size:11}}} },
                scales: {
                    y: {beginAtZero:true, ticks:{callback:function(v){return '$'+v.toLocaleString();}, font:{size:10}}},
                    x: {ticks:{font:{size:9}, maxRotation:45}}
                }
            })
        });
    }

    /* ── Split Doughnut ── */
    new Chart(document.getElementById('fnpfSplitChart'), {
        type: 'doughnut',
        data: {
            labels: ['Employee Contribution','Employer Contribution'],
            datasets: [{
                data: [<?php echo $totalEmployeeContrib.','.$totalEmployerContrib; ?>],
                backgroundColor: ['#2AABB3','#FAAD14'],
                borderWidth: 2, borderColor: '#fff'
            }]
        },
        options: Object.assign({}, BASE, {
            cutout: '58%',
            plugins: { legend:{position:'bottom', labels:{padding:10, usePointStyle:true, font:{size:11}}} }
        })
    });

    /* ── Department Bar ── */
    if(DEPT.length > 0){
        new Chart(document.getElementById('fnpfDeptChart'), {
            type: 'bar',
            data: {
                labels: DEPT.map(function(d){ return d.name && d.name.length>14 ? d.name.substring(0,14)+'…' : d.name; }),
                datasets: [
                    {
                        label: 'Employee',
                        data: DEPT.map(function(d){return d.employee;}),
                        backgroundColor: '#2AABB3',
                        borderRadius: 4,
                        barThickness: 14,
                        maxBarThickness: 18
                    },
                    {
                        label: 'Employer',
                        data: DEPT.map(function(d){return d.employer;}),
                        backgroundColor: '#FAAD14',
                        borderRadius: 4,
                        barThickness: 14,
                        maxBarThickness: 18
                    }
                ]
            },
            options: Object.assign({}, BASE, {
                plugins: { legend:{position:'bottom', labels:{padding:8, usePointStyle:true, font:{size:10}}} },
                scales: {
                    y: {beginAtZero:true, ticks:{callback:function(v){return '$'+v.toLocaleString();}, font:{size:10}}},
                    x: {ticks:{font:{size:10}}}
                }
            })
        });
    }

    /* ── Top Contributors List ── */
    var topEl = document.getElementById('fnpf-toplist');
    if(topEl){
        if(TOPC.length > 0){
            var h = '';
            TOPC.forEach(function(d, i){
                var n = ((d.first_name||'')+' '+(d.last_name||'')).trim();
                var total = (parseFloat(d.emp_c)||0)+(parseFloat(d.er_c)||0);
                var medal = i<3 ? ['🥇','🥈','🥉'][i]+' ' : '';
                h += '<div class="fnpf-list-row">'
                    + '<div style="flex:1"><div class="fnpf-list-name">'+medal+n+'</div>'
                    + '<div class="fnpf-list-sub">FNPF: '+(d.fnpf||'N/A')+' · Emp: $'+(parseFloat(d.emp_c)||0).toLocaleString(undefined,{minimumFractionDigits:2})+'</div></div>'
                    + '<div class="fnpf-list-amount">$'+total.toLocaleString(undefined,{minimumFractionDigits:2})+'</div></div>';
            });
            topEl.innerHTML = h;
        } else {
            topEl.innerHTML = '<div style="color:#9CA3AF;font-size:12px;text-align:center;padding:16px">No data</div>';
        }
    }

    /* ── Department Progress Bars ── */
    var pEl = document.getElementById('fnpf-deptprog');
    if(pEl && DEPT.length > 0){
        var maxA = Math.max.apply(null, DEPT.map(function(d){return d.employee+d.employer;}));
        var h2 = '';
        DEPT.forEach(function(d, i){
            var total = d.employee + d.employer;
            var pct = maxA > 0 ? Math.round((total/maxA)*100) : 0;
            h2 += '<div class="fnpf-progress-wrap">'
                + '<div class="fnpf-progress-label" title="'+d.name+'">'+d.name+'</div>'
                + '<div class="fnpf-progress-bar"><div class="fnpf-progress-fill" style="width:'+pct+'%;background:'+COLORS[i%COLORS.length]+'"></div></div>'
                + '<div class="fnpf-progress-val">$'+total.toLocaleString()+'</div></div>';
        });
        pEl.innerHTML = h2;
    }
});

/* ── Dashboard Toggle + localStorage ── */
function fnpfToggleDash(){
    var d=document.getElementById('fnpf-dashboard'), t=document.getElementById('fnpf-dash-toggle'), h=document.getElementById('fnpf-toggle-hint');
    if(d.classList.contains('hidden')){
        d.classList.remove('hidden'); d.style.maxHeight=d.scrollHeight+'px';
        t.classList.remove('collapsed'); h.textContent='(click to collapse)';
        localStorage.setItem('fnpf_dash','0');
    } else {
        d.classList.add('hidden'); t.classList.add('collapsed');
        h.textContent='(click to expand)'; localStorage.setItem('fnpf_dash','1');
    }
}
(function(){
    if(localStorage.getItem('fnpf_dash')==='1'){
        var d=document.getElementById('fnpf-dashboard'), t=document.getElementById('fnpf-dash-toggle'), h=document.getElementById('fnpf-toggle-hint');
        if(d){d.classList.add('hidden'); t.classList.add('collapsed'); h.textContent='(click to expand)';}
    }
})();
</script>

<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){});
</script>