<?php
/* PaidEmployeeTimesheetReport.php - Modernized with Dashboard + Ant Design Styling */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity = 0;
ob_start();
include('includes/session.inc');
$Title = _('Paid Timesheet Report');
include('includes/newheader.php');

include('includes/SQL_CommonFunctions.inc');
include('includes/GetPaymentMethods.php');
include('includes/GetPrice.inc');
?>

<!-- ===== LOADING MODAL ===== -->
<div id="loadingModal" style="display:flex; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(255,255,255,0.95); z-index:99999; justify-content:center; align-items:center; flex-direction:column;">
    <div style="text-align:center;">
        <div style="width:48px; height:48px; border:4px solid #E6F7F8; border-top:4px solid #2AABB3; border-radius:50%; animation:spin 1s linear infinite; margin:0 auto 16px;"></div>
        <div style="font-family:'Poppins',sans-serif; font-size:15px; color:#1F2937; font-weight:500;">Loading Paid Timesheet Report...</div>
        <div id="loadTimer" style="font-family:'Poppins',sans-serif; font-size:12px; color:#6B7280; margin-top:6px;">0.0s</div>
    </div>
</div>
<style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style>
<script>
var _lt=Date.now();
var _li=setInterval(function(){var e=(Date.now()-_lt)/1000;document.getElementById('loadTimer').textContent=e.toFixed(1)+'s';},100);
</script>

<?php ob_flush(); flush(); ?>

<!-- ===== FONTS, CHART.JS, DATATABLES ===== -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.16/b-1.5.1/b-flash-1.5.1/b-html5-1.5.1/b-print-1.5.1/datatables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>

<style>
/* ===== BRAND TOKENS ===== */
:root {
    --primary: #2AABB3;
    --primary-dark: #1E8F96;
    --primary-darker: #187278;
    --primary-light: #E6F7F8;
    --success: #52C41A;
    --warning: #FAAD14;
    --danger: #FF4D4F;
    --info: #1890FF;
    --purple: #722ED1;
    --orange: #FA8C16;
    --border: #E5E7EB;
    --text: #1F2937;
    --text-secondary: #6B7280;
    --bg-card: #FFFFFF;
    --shadow-subtle: 0 1px 3px rgba(0,0,0,0.08);
    --shadow-card: 0 2px 8px rgba(0,0,0,0.06);
    --radius: 10px;
    --font: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
}

/* ===== GRADIENT BANNER ===== */
.ptr-banner {
    background: linear-gradient(135deg, var(--primary-darker) 0%, var(--primary) 50%, #34C3CB 100%);
    border-radius: var(--radius);
    padding: 28px 32px;
    margin: 0 0 0 0;
    color: #fff;
    position: relative;
    overflow: hidden;
}
.ptr-banner::before {
    content: '';
    position: absolute;
    top: -40%;
    right: -5%;
    width: 250px;
    height: 250px;
    background: radial-gradient(circle, rgba(255,255,255,0.12) 0%, transparent 70%);
    border-radius: 50%;
}
.ptr-banner h1 {
    font-family: var(--font);
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 4px 0;
    color: #fff;
}
.ptr-banner .subtitle { font-family: var(--font); font-size: 13px; opacity: 0.9; }
.ptr-breadcrumbs {
    font-family: var(--font);
    font-size: 12px;
    opacity: 0.8;
    margin-bottom: 8px;
}
.ptr-breadcrumbs a { color: rgba(255,255,255,0.85); text-decoration: none; }
.ptr-breadcrumbs a:hover { color: #fff; }

/* ===== DASHBOARD TOGGLE ===== */
.dash-toggle {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 16px;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    margin: 16px 0;
    cursor: pointer;
    font-family: var(--font);
    font-size: 13px;
    font-weight: 600;
    color: var(--primary-dark);
    transition: all 0.2s;
    user-select: none;
}
.dash-toggle:hover { background: var(--primary-light); }
.dash-toggle .arrow { transition: transform 0.3s; display: inline-block; }
.dash-toggle .arrow.collapsed { transform: rotate(-90deg); }

/* ===== DASHBOARD AREA ===== */
.dash-area {
    transition: max-height 0.4s ease, opacity 0.3s ease;
    overflow: hidden;
    max-height: 3000px;
    opacity: 1;
}
.dash-area.collapsed { max-height: 0 !important; opacity: 0; }

/* ===== GRID LAYOUTS ===== */
.dash-grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 20px; }
.dash-grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 20px; }
.dash-grid-2 { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; margin-bottom: 20px; }
@media (max-width: 1200px) { .dash-grid-4 { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 768px) {
    .dash-grid-4, .dash-grid-3 { grid-template-columns: 1fr; }
    .dash-grid-2 { grid-template-columns: 1fr; }
}

/* ===== KPI CARDS ===== */
.kpi-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-left: 4px solid var(--primary);
    border-radius: var(--radius);
    padding: 18px 20px;
    box-shadow: var(--shadow-subtle);
    display: flex;
    align-items: center;
    gap: 14px;
    transition: box-shadow 0.2s, transform 0.2s;
}
.kpi-card:hover { box-shadow: var(--shadow-card); transform: translateY(-1px); }
.kpi-card.success { border-left-color: var(--success); }
.kpi-card.warning { border-left-color: var(--warning); }
.kpi-card.danger { border-left-color: var(--danger); }
.kpi-card.info { border-left-color: var(--info); }
.kpi-card.purple { border-left-color: var(--purple); }
.kpi-card.orange { border-left-color: var(--orange); }
.kpi-icon {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
}
.kpi-icon.primary { background: var(--primary-light); color: var(--primary-dark); }
.kpi-icon.success { background: #F6FFED; color: var(--success); }
.kpi-icon.warning { background: #FFFBE6; color: var(--warning); }
.kpi-icon.danger { background: #FFF2F0; color: var(--danger); }
.kpi-icon.info { background: #E6F7FF; color: var(--info); }
.kpi-icon.purple { background: #F9F0FF; color: var(--purple); }
.kpi-icon.orange { background: #FFF7E6; color: var(--orange); }
.kpi-value {
    font-family: var(--font);
    font-size: 22px;
    font-weight: 700;
    color: var(--text);
    line-height: 1.1;
}
.kpi-label {
    font-family: var(--font);
    font-size: 11px;
    font-weight: 500;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-top: 2px;
}

/* ===== PANEL CARDS ===== */
.panel-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    box-shadow: var(--shadow-subtle);
    overflow: hidden;
}
.panel-header {
    padding: 14px 18px;
    border-bottom: 1px solid var(--border);
    font-family: var(--font);
    font-size: 13px;
    font-weight: 600;
    color: var(--text);
    display: flex;
    align-items: center;
    gap: 8px;
}
.panel-body { padding: 16px 18px; }
.panel-body canvas { max-height: 260px; }

/* ===== ALERT ROW ===== */
.alert-row {
    display: flex;
    align-items: center;
    padding: 10px 14px;
    border-bottom: 1px solid #F3F4F6;
    font-family: var(--font);
    font-size: 12.5px;
    color: var(--text);
    gap: 10px;
    transition: background 0.15s;
}
.alert-row:hover { background: #F9FAFB; }
.alert-row:last-child { border-bottom: none; }
.alert-badge {
    font-size: 11px;
    font-weight: 600;
    padding: 2px 8px;
    border-radius: 10px;
    margin-left: auto;
    white-space: nowrap;
}
.badge-teal { background: var(--primary-light); color: var(--primary-dark); }
.badge-green { background: #F6FFED; color: #389E0D; }
.badge-blue { background: #E6F7FF; color: #096DD9; }

/* ===== PROGRESS BAR ===== */
.progress-bar-wrap {
    width: 100%;
    height: 8px;
    background: #F3F4F6;
    border-radius: 4px;
    overflow: hidden;
    margin: 4px 0;
}
.progress-bar-fill {
    height: 100%;
    border-radius: 4px;
    transition: width 0.6s ease;
}

/* ===== MODERN FORM STYLING ===== */
.ptr-form-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    box-shadow: var(--shadow-subtle);
    padding: 28px 32px;
    margin: 16px 0;
}
.ptr-form-card .form-title {
    font-family: var(--font);
    font-size: 16px;
    font-weight: 600;
    color: var(--text);
    margin: 0 0 20px 0;
    padding-bottom: 12px;
    border-bottom: 2px solid var(--primary-light);
    display: flex;
    align-items: center;
    gap: 10px;
}
.ptr-form-card .form-title i { color: var(--primary); }
.ptr-form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}
@media (max-width: 900px) { .ptr-form-grid { grid-template-columns: 1fr; } }
.ptr-form-group label {
    display: block;
    font-family: var(--font);
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 6px;
}
.ptr-form-group select {
    width: 100%;
    padding: 10px 14px;
    border: 1px solid var(--border);
    border-radius: 8px;
    font-family: var(--font);
    font-size: 13px;
    color: var(--text);
    background: #fff;
    transition: border-color 0.2s, box-shadow 0.2s;
    appearance: none;
    -webkit-appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236B7280' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 12px center;
    cursor: pointer;
}
.ptr-form-group select:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(42,171,179,0.15);
}
.ptr-submit-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 11px 28px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: #fff;
    border: none;
    border-radius: 8px;
    font-family: var(--font);
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 2px 6px rgba(42,171,179,0.3);
}
.ptr-submit-btn:hover {
    background: linear-gradient(135deg, var(--primary-dark), var(--primary-darker));
    box-shadow: 0 4px 12px rgba(42,171,179,0.4);
    transform: translateY(-1px);
}
.ptr-back-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 9px 20px;
    background: #fff;
    color: var(--primary-dark);
    border: 1px solid var(--border);
    border-radius: 8px;
    font-family: var(--font);
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.2s;
    margin-bottom: 16px;
}
.ptr-back-btn:hover { background: var(--primary-light); border-color: var(--primary); }

/* ===== REPORT SUMMARY HEADER ===== */
.report-summary-header {
    background: linear-gradient(135deg, #F0FAFB, #E6F7F8);
    border: 1px solid #D1F0F2;
    border-radius: var(--radius);
    padding: 18px 24px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
}
.report-summary-header .rsh-title {
    font-family: var(--font);
    font-size: 15px;
    font-weight: 600;
    color: var(--primary-darker);
}
.report-summary-header .rsh-detail {
    font-family: var(--font);
    font-size: 12px;
    color: var(--text-secondary);
}

/* ===== DATATABLES OVERRIDE ===== */
#projectreport_wrapper { font-family: var(--font) !important; }
#projectreport thead th {
    background: linear-gradient(180deg, var(--primary), var(--primary-dark)) !important;
    color: #fff !important;
    font-family: var(--font) !important;
    font-size: 11px !important;
    font-weight: 600 !important;
    text-transform: uppercase !important;
    letter-spacing: 0.3px !important;
    padding: 10px 8px !important;
    border-right: 1px solid rgba(255,255,255,0.15) !important;
    white-space: nowrap !important;
}
#projectreport thead th:last-child { border-right: none !important; }
#projectreport tbody td {
    font-family: var(--font) !important;
    font-size: 12px !important;
    padding: 9px 8px !important;
    border-bottom: 1px solid var(--border) !important;
    color: var(--text) !important;
    white-space: nowrap !important;
}
#projectreport tbody tr:hover { background: var(--primary-light) !important; }
#projectreport tbody tr:nth-child(even) { background: #FAFBFC !important; }
#projectreport tbody tr:nth-child(even):hover { background: var(--primary-light) !important; }
.dt-buttons .dt-button {
    background: var(--primary) !important;
    border: 1px solid var(--primary-dark) !important;
    color: #fff !important;
    font-family: var(--font) !important;
    font-size: 12px !important;
    font-weight: 500 !important;
    border-radius: 6px !important;
    padding: 6px 14px !important;
    margin-right: 6px !important;
    transition: all 0.2s !important;
}
.dt-buttons .dt-button:hover {
    background: var(--primary-dark) !important;
    border-color: var(--primary-darker) !important;
}
.dataTables_filter input {
    border: 1px solid var(--border) !important;
    border-radius: 8px !important;
    padding: 6px 12px !important;
    font-family: var(--font) !important;
}
.dataTables_filter input:focus {
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 3px rgba(42,171,179,0.15) !important;
    outline: none !important;
}
.dataTables_info, .dataTables_length { font-family: var(--font) !important; font-size: 12px !important; }
.dataTables_paginate .paginate_button { border-radius: 6px !important; font-family: var(--font) !important; }
.dataTables_paginate .paginate_button.current {
    background: var(--primary) !important;
    border-color: var(--primary) !important;
    color: #fff !important;
}
table.dataTable { border-radius: var(--radius) !important; overflow: hidden !important; border-collapse: separate !important; border-spacing: 0 !important; }
</style>

<!-- ===== BANNER ===== -->
<div class="ptr-banner">
    <div class="ptr-breadcrumbs">
        <a href="index.php"><i class="fa fa-home"></i> Home</a> &nbsp;/&nbsp;
        <a href="#">Payroll</a> &nbsp;/&nbsp;
        <span>Paid Timesheet Report</span>
    </div>
    <h1><i class="fa fa-file-text-o" style="margin-right:8px;"></i>Paid Employee Timesheet Report</h1>
    <div class="subtitle">Detailed payrun breakdown by employee &mdash; Normal, Overtime, Allowances, Deductions & Net Pay</div>
</div>

<!-- ===== YTD DASHBOARD TOGGLE ===== -->
<div class="dash-toggle" id="dashToggle" onclick="toggleDash()">
    <span class="arrow" id="dashArrow">&#9660;</span>
    <i class="fa fa-tachometer"></i> Year-to-Date Payrun Overview &mdash; <?php echo date('Y'); ?>
</div>

<!-- ===== COLLAPSIBLE YTD DASHBOARD ===== -->
<div class="dash-area" id="dashArea">
    <div class="dash-grid-4" id="ytdKPIs">
        <div class="kpi-card">
            <div class="kpi-icon primary"><i class="fa fa-users"></i></div>
            <div><div class="kpi-value" id="ytdEmps">--</div><div class="kpi-label">Paid Employees</div></div>
        </div>
        <div class="kpi-card success">
            <div class="kpi-icon success"><i class="fa fa-money"></i></div>
            <div><div class="kpi-value" id="ytdGross">--</div><div class="kpi-label">Total Gross</div></div>
        </div>
        <div class="kpi-card info">
            <div class="kpi-icon info"><i class="fa fa-credit-card"></i></div>
            <div><div class="kpi-value" id="ytdNet">--</div><div class="kpi-label">Total Net Pay</div></div>
        </div>
        <div class="kpi-card warning">
            <div class="kpi-icon warning"><i class="fa fa-minus-circle"></i></div>
            <div><div class="kpi-value" id="ytdDeductions">--</div><div class="kpi-label">Total Deductions</div></div>
        </div>
    </div>
    <div class="dash-grid-4">
        <div class="kpi-card purple">
            <div class="kpi-icon purple"><i class="fa fa-institution"></i></div>
            <div><div class="kpi-value" id="ytdFNPF">--</div><div class="kpi-label">Employee FNPF</div></div>
        </div>
        <div class="kpi-card orange">
            <div class="kpi-icon orange"><i class="fa fa-clock-o"></i></div>
            <div><div class="kpi-value" id="ytdHours">--</div><div class="kpi-label">Normal Hours</div></div>
        </div>
        <div class="kpi-card">
            <div class="kpi-icon primary"><i class="fa fa-list-ol"></i></div>
            <div><div class="kpi-value" id="ytdRecords">--</div><div class="kpi-label">Pay Records</div></div>
        </div>
        <div class="kpi-card danger">
            <div class="kpi-icon danger"><i class="fa fa-percent"></i></div>
            <div><div class="kpi-value" id="ytdDedRate">--</div><div class="kpi-label">Deduction Rate</div></div>
        </div>
    </div>
    <div class="dash-grid-2">
        <div class="panel-card">
            <div class="panel-header"><i class="fa fa-line-chart" style="color:var(--primary);"></i> Monthly Gross vs Net Pay</div>
            <div class="panel-body"><canvas id="ytdMonthlyChart"></canvas></div>
        </div>
        <div class="panel-card">
            <div class="panel-header"><i class="fa fa-building" style="color:var(--purple);"></i> Top Departments by Gross</div>
            <div class="panel-body" id="ytdDeptList" style="padding:0;"></div>
        </div>
    </div>
</div>

<?php
// ===== FORM OR REPORT =====
if (isset($_POST['quote'])) {
    $dateraw = $_POST['fromdate'];
    $starttime = date("Y-m-d", strtotime($dateraw));
    $dateraw1 = $_POST['todate'];
    $endtime = date("Y-m-d", strtotime($dateraw1));
    $dept = $_POST['department'];
?>

<!-- ===== REPORT RESULTS ===== -->
<a href="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>" class="ptr-back-btn">
    <i class="fa fa-arrow-left"></i> Back to Filter
</a>

<div class="report-summary-header">
    <div>
        <div class="rsh-title"><i class="fa fa-table" style="color:var(--primary);margin-right:6px;"></i>Paid Payrun Report Results</div>
        <div class="rsh-detail">Period: ID <?php echo htmlspecialchars($dateraw); ?> &rarr; ID <?php echo htmlspecialchars($dateraw1); ?> &nbsp;|&nbsp; Department: <?php echo htmlspecialchars($dept); ?></div>
    </div>
</div>

<!-- ===== REPORT SUMMARY KPIs (loaded via AJAX) ===== -->
<div id="reportSummaryArea" style="display:none;">
    <div class="dash-grid-4" id="rptKPIs">
        <div class="kpi-card">
            <div class="kpi-icon primary"><i class="fa fa-users"></i></div>
            <div><div class="kpi-value" id="rptEmps">--</div><div class="kpi-label">Employees</div></div>
        </div>
        <div class="kpi-card success">
            <div class="kpi-icon success"><i class="fa fa-money"></i></div>
            <div><div class="kpi-value" id="rptGross">--</div><div class="kpi-label">Total Gross</div></div>
        </div>
        <div class="kpi-card info">
            <div class="kpi-icon info"><i class="fa fa-credit-card"></i></div>
            <div><div class="kpi-value" id="rptNet">--</div><div class="kpi-label">Net Pay</div></div>
        </div>
        <div class="kpi-card danger">
            <div class="kpi-icon danger"><i class="fa fa-minus-circle"></i></div>
            <div><div class="kpi-value" id="rptDeductions">--</div><div class="kpi-label">Deductions + FNPF</div></div>
        </div>
    </div>
    <div class="dash-grid-2" style="margin-bottom:20px;">
        <div class="panel-card">
            <div class="panel-header"><i class="fa fa-pie-chart" style="color:var(--primary);"></i> Pay Composition</div>
            <div class="panel-body"><canvas id="rptCompChart"></canvas></div>
        </div>
        <div class="panel-card">
            <div class="panel-header"><i class="fa fa-trophy" style="color:var(--warning);"></i> Top 5 Earners (This Report)</div>
            <div class="panel-body" id="rptTopList" style="padding:0;"></div>
        </div>
    </div>
</div>

<script>
// Load report summary
(function(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET','PaidEmployeeTimesheetReportAPI.php?action=report_summary&fromdate=<?php echo urlencode($dateraw); ?>&todate=<?php echo urlencode($dateraw1); ?>&department=<?php echo urlencode($dept); ?>',true);
    xhr.onload = function(){
        if(xhr.status===200){
            try {
                var d = JSON.parse(xhr.responseText);
                renderReportSummary(d);
                document.getElementById('reportSummaryArea').style.display = 'block';
            } catch(e){ console.error('Report summary parse error',e); }
        }
    };
    xhr.send();

    var colors = ['#2AABB3','#52C41A','#FAAD14','#FF4D4F','#1890FF','#722ED1','#13C2C2','#EB2F96','#FA8C16','#A0D911','#597EF7','#F5222D','#36CFC9'];

    function fmt(n){ return Number(n).toLocaleString(undefined,{minimumFractionDigits:0,maximumFractionDigits:0}); }
    function fmtD(n){ return Number(n).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2}); }

    function renderReportSummary(d){
        document.getElementById('rptEmps').textContent = fmt(d.total_employees || 0);
        document.getElementById('rptGross').textContent = '$' + fmtD(d.total_gross || 0);
        document.getElementById('rptNet').textContent = '$' + fmtD(d.total_net_pay || 0);
        var totalDed = (d.total_fixed_ded || 0) + (d.total_emp_fnpf || 0);
        document.getElementById('rptDeductions').textContent = '$' + fmtD(totalDed);

        // Pay composition doughnut
        if(d.pay_composition && d.pay_composition.length > 0){
            new Chart(document.getElementById('rptCompChart'), {
                type: 'doughnut',
                data: {
                    labels: d.pay_composition.map(function(p){ return p.category; }),
                    datasets: [{
                        data: d.pay_composition.map(function(p){ return p.amount; }),
                        backgroundColor: colors.slice(0, d.pay_composition.length),
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    cutout: '50%',
                    plugins: { legend: { position:'right', labels: { font:{family:'Poppins',size:11}, padding:8, boxWidth:12 } } }
                }
            });
        }

        // Top earners
        var html = '';
        if(d.top_earners && d.top_earners.length > 0){
            var maxG = d.top_earners[0].gross || 1;
            d.top_earners.forEach(function(emp, i){
                var pct = (emp.gross / maxG * 100).toFixed(0);
                html += '<div class="alert-row" style="flex-wrap:wrap;">'
                    + '<span style="font-weight:700;color:var(--primary-dark);width:22px;text-align:center;">'+(i+1)+'</span>'
                    + '<span style="flex:1;min-width:100px;font-weight:500;">'+emp.name+'</span>'
                    + '<span class="alert-badge badge-teal">$'+fmtD(emp.gross)+'</span>'
                    + '<span style="font-size:11px;color:#9CA3AF;margin-left:6px;">Net $'+fmtD(emp.net)+'</span>'
                    + '<div style="width:100%;padding-left:28px;margin-top:2px;">'
                    + '<div class="progress-bar-wrap"><div class="progress-bar-fill" style="width:'+pct+'%;background:'+colors[i%colors.length]+';"></div></div>'
                    + '</div></div>';
            });
        } else {
            html = '<div class="alert-row" style="justify-content:center;color:#9CA3AF;"><i class="fa fa-info-circle"></i>&nbsp;No data</div>';
        }
        document.getElementById('rptTopList').innerHTML = html;
    }
})();
</script>

<?php
// ===== REPORT TABLE (100% ORIGINAL QUERY & OUTPUT) =====
echo '<div class="table-responsive" style="margin-top:8px;"><table id="projectreport" class="table">';

echo '<thead><tr class="info">
        <th>' . _('Employee ID') . '</th>
        <th>' . _('Full Name') . '</th>
        <th>' . _('Normal Hours') . '</th>
        <th>' . _('Normal Pay') . '</th>
        <th>' . _('Time & Half Hours') . '</th>
        <th>' . _('Time & Half Amount') . '</th>
        <th>' . _('Double Hours') . '</th>
        <th>' . _('Double Pay') . '</th>
        <th>' . _('Premium') . '</th>
        <th>' . _('Stay Away') . '</th>
        <th>' . _('Call Out Allowances') . '</th>
        <th>' . _('Leave Allowances') . '</th>
        <th>' . _('Sick Leave') . '</th>
        <th>' . _('Annual Leave') . '</th>
        <th>' . _('Maternity Leave') . '</th>
        <th>' . _('Other Allowances FNPF') . '</th>
        <th>' . _('Other Allowances Non FNPF') . '</th>
        <th>' . _('Meal Allowances') . '</th>
        <th>' . _('Total Gross Amount') . '</th>
        <th>' . _('Employee FNPF Contribution') . '</th>
        <th>' . _('Fixed Deductions') . '</th>
        <th>' . _('Net Pay') . '</th>
    </tr></thead><tbody>';

$querypayrun = "SELECT 
                   payrun_details.employeeid,
                   payrun_details.full_name,
                   SUM(payrun_details.normal_hours) as normalhours,
                   SUM(payrun_details.normal_pay) as normalpay,
                   SUM(payrun_details.timehalf_hours) as timehalfhours,
                   SUM(payrun_details.timehalf_amount) as timehalfamount,
                   SUM(payrun_details.double_hours) as doublepay,
                   SUM(payrun_details.double_amount) as doubleamount,
                   SUM(payrun_details.premium) as premiumtotal,
                   SUM(payrun_details.stay_away) as stayaway,
                   SUM(payrun_details.call_out_allowances) as calloutallowances,
                   SUM(payrun_details.leave_allowances) as leaveallowances,
                   SUM(payrun_details.leave_allowances) as sickleave,
                   SUM(payrun_details.annual_leave) as annualleave,
                   SUM(payrun_details.maternity_leave) as maternityleave,
                   SUM(payrun_details.other_allowances_fnpf) as otherallowancesfnpf,
                   SUM(payrun_details.other_allowances_nonfnpf) as otherallowancesnonfnpf,
                   SUM(payrun_details.meal_allowance) as mealallowance,
                   SUM(payrun_details.totalgross_amount) as totalgrossamount,
                   SUM(payrun_details.employee_fnpf) as employeefnpf,
                   SUM(payrun_details.fixed_deductions) as fixeddeductions,
                   SUM(payrun_details.net_pay) as net_pay
              FROM payrun_details
              WHERE payrun_details.id BETWEEN '" . $_POST['fromdate'] . "' AND '" . $_POST['todate'] . "'
              AND payrun_details.department = '" . $_POST['department'] . "'
              GROUP BY payrun_details.employeeid";

$resultpayrun = DB_query($querypayrun);

while ($myrowpayrun = DB_fetch_array($resultpayrun)) {
    echo '<tr>
            <td>' . $myrowpayrun['employeeid'] . '</td>
            <td>' . $myrowpayrun['full_name'] . '</td>
            <td>' . $myrowpayrun['normalhours'] . '</td>
            <td>' . $myrowpayrun['normalpay'] . '</td>
            <td>' . $myrowpayrun['timehalfhours'] . '</td>
            <td>' . $myrowpayrun['timehalfamount'] . '</td>
            <td>' . $myrowpayrun['doublepay'] . '</td>
            <td>' . $myrowpayrun['doubleamount'] . '</td>
            <td>' . $myrowpayrun['premiumtotal'] . '</td>
            <td>' . $myrowpayrun['stayaway'] . '</td>
            <td>' . $myrowpayrun['calloutallowances'] . '</td>
            <td>' . $myrowpayrun['leaveallowances'] . '</td>
            <td>' . $myrowpayrun['sickleave'] . '</td>
            <td>' . $myrowpayrun['annualleave'] . '</td>
            <td>' . $myrowpayrun['maternityleave'] . '</td>
            <td>' . $myrowpayrun['otherallowancesfnpf'] . '</td>
            <td>' . $myrowpayrun['otherallowancesnonfnpf'] . '</td>
            <td>' . $myrowpayrun['mealallowance'] . '</td>
            <td style="font-weight:700;color:var(--primary-dark);">' . $myrowpayrun['totalgrossamount'] . '</td>
            <td>' . $myrowpayrun['employeefnpf'] . '</td>
            <td>' . $myrowpayrun['fixeddeductions'] . '</td>
            <td style="font-weight:700;color:var(--success);">' . $myrowpayrun['net_pay'] . '</td>
          </tr>';
}

echo '</tbody></table></div>';

} else {
    // ===== MODERN FORM =====
    echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '">';
    echo '<div class="ptr-form-card">';
    echo '<div class="form-title"><i class="fa fa-filter"></i> Paid Payrun Timesheet Report</div>';
    echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
    echo '<div class="ptr-form-grid">';

    // From Period
    echo '<div class="ptr-form-group">';
    echo '<label><i class="fa fa-calendar" style="margin-right:4px;"></i> From Weekending Period</label>';
    echo '<select name="fromdate" required>';
    $SQL = "SELECT * FROM calendar_management";
    $result = DB_query($SQL);
    while ($myrow = DB_fetch_array($result)) {
        echo '<option value="' . $myrow['id'] . '">' . $myrow['id'] . ' - ' . $myrow['end_date'] . '</option>';
    }
    echo '</select></div>';

    // To Period
    echo '<div class="ptr-form-group">';
    echo '<label><i class="fa fa-calendar-check-o" style="margin-right:4px;"></i> To Weekending Period</label>';
    echo '<select name="todate" required>';
    $SQL = "SELECT * FROM calendar_management";
    $result = DB_query($SQL);
    while ($myrow = DB_fetch_array($result)) {
        echo '<option value="' . $myrow['id'] . '">' . $myrow['id'] . ' - ' . $myrow['end_date'] . '</option>';
    }
    echo '</select></div>';

    // Department
    echo '<div class="ptr-form-group">';
    echo '<label><i class="fa fa-building-o" style="margin-right:4px;"></i> Department</label>';
    echo '<select name="department" required>';
    $SQL = "SELECT * FROM department";
    $result = DB_query($SQL);
    while ($myrow = DB_fetch_array($result)) {
        echo '<option value="' . $myrow['departmentid'] . '">' . $myrow['departmentname'] . ' - ' . $myrow['departmentid'] . '</option>';
    }
    echo '</select></div>';

    echo '</div>'; // /ptr-form-grid

    echo '<input type="submit" name="quote" value="Show Report" class="ptr-submit-btn" />';
    echo '</div>'; // /ptr-form-card
    echo '</form>';
}

echo '</div>';
?>

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

<!--end:: Widgets/Stats-->
<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>
<script src="angular/angular.min.js"></script>

<!-- ===== YTD DASHBOARD JAVASCRIPT ===== -->
<script>
(function(){
    // Toggle
    var dashState = localStorage.getItem('ptrDashCollapsed');
    var dashArea = document.getElementById('dashArea');
    var dashArrow = document.getElementById('dashArrow');

    function toggleDash(){
        var collapsed = !dashArea.classList.contains('collapsed');
        if(collapsed){
            dashArea.classList.add('collapsed');
            dashArrow.classList.add('collapsed');
            localStorage.setItem('ptrDashCollapsed','1');
        } else {
            dashArea.classList.remove('collapsed');
            dashArrow.classList.remove('collapsed');
            localStorage.setItem('ptrDashCollapsed','0');
        }
    }
    window.toggleDash = toggleDash;

    if(dashState === '1'){
        dashArea.classList.add('collapsed');
        dashArrow.classList.add('collapsed');
    }

    var colors = ['#2AABB3','#52C41A','#FAAD14','#FF4D4F','#1890FF','#722ED1','#13C2C2','#EB2F96'];

    function fmt(n){ return Number(n).toLocaleString(undefined,{minimumFractionDigits:0,maximumFractionDigits:0}); }
    function fmtD(n){ return Number(n).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2}); }

    // Load YTD
    var xhr = new XMLHttpRequest();
    xhr.open('GET','PaidEmployeeTimesheetReportAPI.php?action=ytd_dashboard',true);
    xhr.onload = function(){
        if(xhr.status===200){
            try {
                var d = JSON.parse(xhr.responseText);
                renderYTD(d);
            } catch(e){ console.error('YTD parse error',e); }
        }
        var m = document.getElementById('loadingModal');
        if(m){ m.style.opacity='0'; setTimeout(function(){ m.style.display='none'; },300); }
        clearInterval(_li);
    };
    xhr.onerror = function(){
        var m = document.getElementById('loadingModal');
        if(m){ m.style.display='none'; }
        clearInterval(_li);
    };
    xhr.send();

    function renderYTD(d){
        document.getElementById('ytdEmps').textContent = fmt(d.total_employees || 0);
        document.getElementById('ytdGross').textContent = '$' + fmtD(d.total_gross || 0);
        document.getElementById('ytdNet').textContent = '$' + fmtD(d.total_net || 0);
        document.getElementById('ytdDeductions').textContent = '$' + fmtD(d.total_deductions || 0);
        document.getElementById('ytdFNPF').textContent = '$' + fmtD(d.total_fnpf || 0);
        document.getElementById('ytdHours').textContent = fmt(d.total_normal_hours || 0);
        document.getElementById('ytdRecords').textContent = fmt(d.total_records || 0);

        var dedRate = (d.total_gross > 0) ? (((d.total_deductions + d.total_fnpf) / d.total_gross) * 100).toFixed(1) : '0.0';
        document.getElementById('ytdDedRate').textContent = dedRate + '%';

        // Monthly chart
        if(d.monthly_trend){
            var labels = d.monthly_trend.map(function(m){ return m.month; });
            new Chart(document.getElementById('ytdMonthlyChart'), {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Gross ($)',
                        data: d.monthly_trend.map(function(m){ return m.gross; }),
                        backgroundColor: '#2AABB333',
                        borderColor: '#2AABB3',
                        borderWidth: 2,
                        borderRadius: 6,
                        yAxisID: 'y'
                    },{
                        label: 'Net Pay ($)',
                        data: d.monthly_trend.map(function(m){ return m.net; }),
                        type: 'line',
                        borderColor: '#52C41A',
                        backgroundColor: '#52C41A33',
                        pointBackgroundColor: '#52C41A',
                        pointRadius: 4,
                        tension: 0.3,
                        yAxisID: 'y'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: { legend: { position:'bottom', labels: { font:{family:'Poppins',size:11} } } },
                    scales: {
                        y: { beginAtZero:true, grid:{color:'#F3F4F6'}, ticks:{font:{family:'Poppins',size:11}} },
                        x: { grid:{display:false}, ticks:{font:{family:'Poppins',size:11}} }
                    }
                }
            });
        }

        // Department list
        var html = '';
        if(d.top_departments && d.top_departments.length > 0){
            var maxG = d.top_departments[0].gross || 1;
            d.top_departments.forEach(function(dep, i){
                var pct = (dep.gross / maxG * 100).toFixed(0);
                html += '<div class="alert-row" style="flex-wrap:wrap;">'
                    + '<span style="font-weight:700;color:var(--primary-dark);width:22px;text-align:center;">'+(i+1)+'</span>'
                    + '<span style="flex:1;min-width:100px;font-weight:500;">'+dep.name+'</span>'
                    + '<span class="alert-badge badge-teal">$'+fmtD(dep.gross)+'</span>'
                    + '<span style="font-size:11px;color:#9CA3AF;margin-left:6px;">'+dep.emps+' emps</span>'
                    + '<div style="width:100%;padding-left:28px;margin-top:2px;">'
                    + '<div class="progress-bar-wrap"><div class="progress-bar-fill" style="width:'+pct+'%;background:'+colors[i%colors.length]+';"></div></div>'
                    + '</div></div>';
            });
        }
        if(!html) html = '<div class="alert-row" style="justify-content:center;color:#9CA3AF;"><i class="fa fa-info-circle"></i>&nbsp;No data</div>';
        document.getElementById('ytdDeptList').innerHTML = html;
    }
})();
</script>

<!-- ===== DATATABLES INIT (ORIGINAL) ===== -->
<script>
$(document).ready(function() {
    $('#projectreport').DataTable({
        dom: 'Bfrtip',
        scrollX: true,
        buttons: [
            {
                extend: 'pdfHtml5',
                orientation: 'landscape',
                pageSize: 'A3',
                customize: function(doc) {
                    doc.defaultStyle.fontSize = 8;
                }
            },
            { extend: 'excelHtml5' },
            { extend: 'copyHtml5' }
        ]
    });
});
</script>

</body>
</html>

<?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'];
}

function GetRptLinks($GroupID) {
    global $db, $RootPath, $ReportList;
    require_once('reportwriter/languages/en_US/reports.php');
    require_once('reportwriter/admin/defaults.php');
    $GroupID=$ReportList[$GroupID];
    $Title= array(_('Custom Reports'), _('Standard Reports and Forms'));
    $sql= "SELECT id, reporttype, defaultreport, groupname, reportname FROM reports ORDER BY groupname, reportname";
    $Result=DB_query($sql,'','',false,true);
    $ReportList = '';
    while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;
    $RptLinks = '';
    for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers"><b>' . $Title[$Def] . '</b></li>';
        $NoEntries = true;
        if ($ReportList) {
            foreach ($ReportList as $Report) {
                if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p></li>';
                    $NoEntries = false;
                }
            }
            $NoForms = true;
            foreach ($ReportList as $Report) {
                $Group=explode(':',$Report['groupname']);
                if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>' . $FormGroups[$Report['groupname']] . '</a></li>';
                    $NoForms = false;
                    $NoEntries = false;
                }
            }
        }
        if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
    }
    return $RptLinks;
}
?>