<?php
/* Labour Cost Report - Modernized with Dashboard */
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
ini_set('display_errors', '1');
$PageSecurity = 0;

include('includes/session.inc');
$Title = _('Labour Cost Report');

// --- Loading modal: output header + modal HTML first, flush to browser ---
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

$userid = $_SESSION['UserID'];
$allowedUsers = array('admin', 'jprasad', 'sharukh');
$isAllowed = in_array($userid, $allowedUsers);

// Process form submission
$reportData = array();
$hasReport = false;
$fromLabel = '';
$toLabel = '';

if ($isAllowed && isset($_POST['quote'])) {
    $fromDate = escapeshellarg($_POST['fromdate']);
    $toDate   = escapeshellarg($_POST['todate']);

    // Get period labels for display
    $sqlLabel = "SELECT id, end_date FROM calendar_management WHERE id IN ('" . DB_escape_string(isset($_POST['fromdate']) ? $_POST['fromdate'] : '') . "', '" . DB_escape_string(isset($_POST['todate']) ? $_POST['todate'] : '') . "')";
    $labelResult = DB_query($sqlLabel, $db);
    while ($lr = DB_fetch_array($labelResult)) {
        if ($lr['id'] == $_POST['fromdate']) $fromLabel = $lr['end_date'];
        if ($lr['id'] == $_POST['todate']) $toLabel = $lr['end_date'];
    }

    $nodeScript = '/home/erp/www/wormalderp/nodejsapp/alllabourcost1.js';
    $jsonFile   = '/home/erp/www/wormalderp/nodejsapp/allcost1.json';

    $cmd = "node {$nodeScript} {$fromDate} {$toDate}";
    $output = shell_exec($cmd . " 2>&1");

    if (file_exists($jsonFile)) {
        $jsonData = file_get_contents($jsonFile);
        $reportData = json_decode($jsonData, true);
        if (!is_array($reportData)) $reportData = array();
        $hasReport = true;
    }
}

// Compute dashboard metrics from report data
$totalCost = 0;
$totalFnpf = 0;
$totalTpaf = 0;
$grandTotal = 0;
$labourItems = array();
$totalRow = null;

if ($hasReport && !empty($reportData)) {
    foreach ($reportData as $row) {
        if (isset($row['labourcode']) && $row['labourcode'] === 'TOTAL') {
            $totalRow = $row;
        } else {
            $labourItems[] = $row;
            $totalCost  += isset($row['cost']) ? floatval($row['cost']) : 0;
            $totalFnpf  += isset($row['fnpfcost']) ? floatval($row['fnpfcost']) : 0;
            $totalTpaf  += isset($row['tpafcost']) ? floatval($row['tpafcost']) : 0;
            $grandTotal += isset($row['totalcost']) ? floatval($row['totalcost']) : 0;
        }
    }
    // Use TOTAL row values if available
    if ($totalRow) {
        $totalCost  = floatval($totalRow['cost']);
        $totalFnpf  = floatval($totalRow['fnpfcost']);
        $totalTpaf  = floatval($totalRow['tpafcost']);
        $grandTotal = floatval($totalRow['totalcost']);
    }
}

// Sort labour items by cost descending for charts
$chartItems = $labourItems;
usort($chartItems, function($a, $b) {
    return floatval($b['totalcost']) - floatval($a['totalcost']);
});
$topN = array_slice($chartItems, 0, 10);
?>

<!-- Dashboard Styles -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
/* ===== LABOUR COST REPORT - DASHBOARD STYLES ===== */
.lcr-wrapper {
    font-family: 'Poppins', sans-serif;
    padding: 0 15px 30px 15px;
    max-width: 1400px;
    margin: 0 auto;
}

/* --- Gradient Banner --- */
.lcr-banner {
    background: linear-gradient(135deg, #2AABB3 0%, #1E8F96 50%, #187278 100%);
    border-radius: 12px;
    padding: 28px 32px 24px 32px;
    margin-bottom: 24px;
    color: #fff;
    position: relative;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(42, 171, 179, 0.25);
}
.lcr-banner::after {
    content: '';
    position: absolute;
    top: -40px; right: -40px;
    width: 180px; height: 180px;
    background: rgba(255,255,255,0.06);
    border-radius: 50%;
}
.lcr-banner h1 {
    margin: 0 0 4px 0;
    font-size: 24px;
    font-weight: 600;
    color: #fff;
}
.lcr-banner .lcr-breadcrumb {
    font-size: 13px;
    opacity: 0.85;
}
.lcr-banner .lcr-breadcrumb a {
    color: #fff;
    text-decoration: none;
    opacity: 0.8;
}
.lcr-banner .lcr-breadcrumb a:hover { opacity: 1; }
.lcr-banner .lcr-period-info {
    margin-top: 10px;
    font-size: 14px;
    opacity: 0.9;
    display: flex;
    align-items: center;
    gap: 8px;
}
.lcr-banner .lcr-period-info i { font-size: 16px; }

/* --- Toggle Button --- */
.lcr-dash-toggle {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #fff;
    border: 1px solid #E5E7EB;
    border-radius: 8px;
    padding: 8px 16px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    font-weight: 500;
    color: #1E8F96;
    cursor: pointer;
    margin-bottom: 16px;
    transition: all 0.2s;
}
.lcr-dash-toggle:hover {
    background: #E6F7F8;
    border-color: #2AABB3;
}
.lcr-dash-toggle i {
    transition: transform 0.3s;
}
.lcr-dash-toggle.collapsed i {
    transform: rotate(-90deg);
}

/* --- Dashboard Container --- */
.lcr-dashboard {
    transition: max-height 0.4s ease, opacity 0.3s ease;
    overflow: hidden;
}
.lcr-dashboard.collapsed {
    max-height: 0 !important;
    opacity: 0;
    margin-bottom: 0;
}

/* --- KPI Cards --- */
.lcr-kpi-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
}
@media (max-width: 1024px) {
    .lcr-kpi-grid { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 600px) {
    .lcr-kpi-grid { grid-template-columns: 1fr; }
}
.lcr-kpi-card {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    border-left: 4px solid #2AABB3;
    box-shadow: 0 1px 4px rgba(0,0,0,0.06);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: transform 0.2s, box-shadow 0.2s;
}
.lcr-kpi-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.lcr-kpi-card.fnpf { border-left-color: #1890FF; }
.lcr-kpi-card.tpaf { border-left-color: #FAAD14; }
.lcr-kpi-card.grand { border-left-color: #52C41A; }
.lcr-kpi-icon {
    width: 48px; height: 48px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
}
.lcr-kpi-icon.cost { background: #E6F7F8; color: #2AABB3; }
.lcr-kpi-icon.fnpf { background: #E6F0FF; color: #1890FF; }
.lcr-kpi-icon.tpaf { background: #FFF8E6; color: #FAAD14; }
.lcr-kpi-icon.grand { background: #E6FFE6; color: #52C41A; }
.lcr-kpi-content { flex: 1; min-width: 0; }
.lcr-kpi-label {
    font-size: 12px;
    color: #6B7280;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 500;
    margin-bottom: 4px;
}
.lcr-kpi-value {
    font-size: 22px;
    font-weight: 700;
    color: #1F2937;
    line-height: 1.2;
}
.lcr-kpi-sub {
    font-size: 11px;
    color: #9CA3AF;
    margin-top: 2px;
}

/* --- Chart Cards --- */
.lcr-chart-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 20px;
}
@media (max-width: 900px) {
    .lcr-chart-grid { grid-template-columns: 1fr; }
}
.lcr-chart-card {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.lcr-chart-card h3 {
    font-size: 15px;
    font-weight: 600;
    color: #1F2937;
    margin: 0 0 12px 0;
    display: flex;
    align-items: center;
    gap: 8px;
}
.lcr-chart-card h3 i {
    color: #2AABB3;
    font-size: 16px;
}
.lcr-chart-container {
    position: relative;
    height: 280px;
    max-height: 280px;
    overflow: hidden;
}

/* --- Insights Row --- */
.lcr-insights-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 20px;
}
@media (max-width: 900px) {
    .lcr-insights-grid { grid-template-columns: 1fr; }
}
.lcr-insight-card {
    background: #fff;
    border-radius: 10px;
    padding: 18px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.lcr-insight-card h4 {
    font-size: 13px;
    font-weight: 600;
    color: #1F2937;
    margin: 0 0 12px 0;
    display: flex;
    align-items: center;
    gap: 6px;
}
.lcr-insight-card h4 i { color: #2AABB3; }
.lcr-insight-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 0;
    border-bottom: 1px solid #F3F4F6;
    font-size: 13px;
}
.lcr-insight-item:last-child { border-bottom: none; }
.lcr-insight-item .label {
    color: #4B5563;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 60%;
}
.lcr-insight-item .value {
    font-weight: 600;
    color: #1F2937;
}
.lcr-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}
.lcr-badge.high { background: #FEE2E2; color: #DC2626; }
.lcr-badge.med  { background: #FEF3C7; color: #D97706; }
.lcr-badge.low  { background: #D1FAE5; color: #059669; }

/* --- Form Styling --- */
.lcr-form-card {
    background: #fff;
    border-radius: 10px;
    padding: 28px 32px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.06);
    max-width: 640px;
    margin: 0 auto;
}
.lcr-form-card h3 {
    font-size: 17px;
    font-weight: 600;
    color: #1F2937;
    margin: 0 0 20px 0;
    display: flex;
    align-items: center;
    gap: 8px;
}
.lcr-form-card h3 i { color: #2AABB3; }
.lcr-form-group {
    margin-bottom: 18px;
}
.lcr-form-group label {
    display: block;
    font-size: 13px;
    font-weight: 500;
    color: #374151;
    margin-bottom: 6px;
}
.lcr-form-group select {
    width: 100%;
    padding: 10px 14px;
    border: 1px solid #D1D5DB;
    border-radius: 8px;
    font-family: 'Poppins', sans-serif;
    font-size: 14px;
    color: #1F2937;
    background: #fff;
    transition: border-color 0.2s, box-shadow 0.2s;
    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;
}
.lcr-form-group select:focus {
    outline: none;
    border-color: #2AABB3;
    box-shadow: 0 0 0 3px rgba(42, 171, 179, 0.15);
}
.lcr-form-submit {
    background: linear-gradient(135deg, #2AABB3, #1E8F96);
    color: #fff;
    border: none;
    border-radius: 8px;
    padding: 12px 32px;
    font-family: 'Poppins', sans-serif;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}
.lcr-form-submit:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(42, 171, 179, 0.3);
}
.lcr-back-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #fff;
    border: 1px solid #D1D5DB;
    border-radius: 8px;
    padding: 8px 18px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    font-weight: 500;
    color: #4B5563;
    cursor: pointer;
    text-decoration: none;
    margin-bottom: 16px;
    transition: all 0.2s;
}
.lcr-back-btn:hover {
    background: #F9FAFB;
    border-color: #9CA3AF;
    color: #1F2937;
}

/* --- DataTable Overrides --- */
.lcr-table-card {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.lcr-table-card h3 {
    font-size: 15px;
    font-weight: 600;
    color: #1F2937;
    margin: 0 0 16px 0;
    display: flex;
    align-items: center;
    gap: 8px;
}
.lcr-table-card h3 i { color: #2AABB3; }

/* DataTable styling overrides */
.lcr-table-card table.dataTable thead th {
    background: #F8FAFB;
    color: #374151;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 12px 14px;
    border-bottom: 2px solid #E5E7EB;
}
.lcr-table-card table.dataTable tbody td {
    font-size: 13px;
    color: #1F2937;
    padding: 10px 14px;
    border-bottom: 1px solid #F3F4F6;
}
.lcr-table-card table.dataTable tbody tr:hover {
    background: #E6F7F8 !important;
}
.lcr-table-card table.dataTable tbody tr.total-row {
    background: #F0FDF4 !important;
    font-weight: 700;
}
.lcr-table-card table.dataTable tbody tr.total-row td {
    border-top: 2px solid #52C41A;
    color: #166534;
}
.lcr-table-card .dataTables_wrapper .dataTables_filter input {
    border: 1px solid #D1D5DB;
    border-radius: 6px;
    padding: 6px 12px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
}
.lcr-table-card .dataTables_wrapper .dataTables_filter input:focus {
    outline: none;
    border-color: #2AABB3;
    box-shadow: 0 0 0 2px rgba(42, 171, 179, 0.15);
}
.lcr-table-card .dt-buttons .dt-button {
    background: linear-gradient(135deg, #2AABB3, #1E8F96) !important;
    color: #fff !important;
    border: none !important;
    border-radius: 6px !important;
    padding: 6px 16px !important;
    font-family: 'Poppins', sans-serif !important;
    font-size: 12px !important;
    font-weight: 500 !important;
    margin-right: 6px !important;
    transition: transform 0.2s, box-shadow 0.2s;
}
.lcr-table-card .dt-buttons .dt-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(42, 171, 179, 0.3);
}

/* Cost bar in table */
.lcr-cost-bar-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
}
.lcr-cost-bar {
    height: 6px;
    border-radius: 3px;
    background: #E5E7EB;
    flex: 1;
    max-width: 80px;
}
.lcr-cost-bar-fill {
    height: 100%;
    border-radius: 3px;
    background: linear-gradient(90deg, #2AABB3, #1E8F96);
}

/* --- Loading Modal --- */
.lcr-loading-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(0,0,0,0.4);
    z-index: 9999;
    justify-content: center;
    align-items: center;
}
.lcr-loading-overlay.active { display: flex; }
.lcr-loading-box {
    background: #fff;
    border-radius: 12px;
    padding: 36px 48px;
    text-align: center;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
}
.lcr-spinner {
    width: 48px; height: 48px;
    border: 4px solid #E5E7EB;
    border-top-color: #2AABB3;
    border-radius: 50%;
    animation: lcr-spin 0.8s linear infinite;
    margin: 0 auto 16px auto;
}
@keyframes lcr-spin { to { transform: rotate(360deg); } }
.lcr-loading-box p {
    font-family: 'Poppins', sans-serif;
    font-size: 14px;
    color: #4B5563;
    margin: 0;
}
.lcr-loading-box .lcr-timer {
    font-size: 12px;
    color: #9CA3AF;
    margin-top: 8px;
}

/* Progress bar mini */
.lcr-progress-wrap {
    width: 100%;
    height: 4px;
    background: #E5E7EB;
    border-radius: 2px;
    overflow: hidden;
}
.lcr-progress-bar {
    height: 100%;
    border-radius: 2px;
    background: linear-gradient(90deg, #2AABB3, #52C41A);
    transition: width 0.3s;
}
</style>

<?php if (!$isAllowed): ?>
<div class="lcr-wrapper">
    <div class="lcr-banner">
        <h1><i class="fas fa-hard-hat"></i> Labour Cost Report</h1>
        <div class="lcr-breadcrumb">
            <a href="index.php">Home</a> &nbsp;/&nbsp; Labour Cost Report
        </div>
    </div>
    <div class="lcr-form-card" style="text-align:center; padding: 48px;">
        <i class="fas fa-lock" style="font-size:48px; color:#D1D5DB; margin-bottom:16px;"></i>
        <p style="font-size:16px; color:#6B7280;">Under Maintenance. Check back later.</p>
    </div>
</div>

<?php elseif (!$hasReport): ?>
<!-- ===== FORM VIEW ===== -->
<div class="lcr-wrapper">
    <div class="lcr-banner">
        <h1><i class="fas fa-hard-hat" style="margin-right:4px;"></i> Labour Cost Report</h1>
        <div class="lcr-breadcrumb">
            <a href="index.php">Home</a> &nbsp;/&nbsp; Labour Cost Report
        </div>
    </div>

    <div class="lcr-form-card">
        <h3><i class="fas fa-calendar-alt"></i> Select Report Period</h3>
        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>" id="lcrForm">
            <input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />

            <div class="lcr-form-group">
                <label><i class="fas fa-play" style="color:#52C41A; margin-right:4px;"></i> From Weekending Period</label>
                <select name="fromdate" required>
                    <?php
                    $SQL = "SELECT id, end_date FROM calendar_management ORDER BY id DESC";
                    $result = DB_query($SQL, $db);
                    while ($myrow = DB_fetch_array($result)) {
                        echo '<option value="' . $myrow['id'] . '">'
                             . $myrow['id'] . ' - ' . $myrow['end_date']
                             . '</option>';
                    }
                    ?>
                </select>
            </div>

            <div class="lcr-form-group">
                <label><i class="fas fa-stop" style="color:#FF4D4F; margin-right:4px;"></i> To Weekending Period</label>
                <select name="todate" required>
                    <?php
                    $result = DB_query($SQL, $db);
                    while ($myrow = DB_fetch_array($result)) {
                        echo '<option value="' . $myrow['id'] . '">'
                             . $myrow['id'] . ' - ' . $myrow['end_date']
                             . '</option>';
                    }
                    ?>
                </select>
            </div>

            <button type="submit" name="quote" value="Show Report" class="lcr-form-submit" onclick="showLoadingModal()">
                <i class="fas fa-chart-bar"></i> Generate Report
            </button>
        </form>
    </div>
</div>

<!-- Loading Modal -->
<div class="lcr-loading-overlay" id="lcrLoadingModal">
    <div class="lcr-loading-box">
        <div class="lcr-spinner"></div>
        <p>Generating Labour Cost Report...</p>
        <div class="lcr-timer" id="lcrTimer">0s elapsed</div>
    </div>
</div>

<script>
function showLoadingModal() {
    var modal = document.getElementById('lcrLoadingModal');
    modal.classList.add('active');
    var start = Date.now();
    var timerEl = document.getElementById('lcrTimer');
    setInterval(function() {
        var elapsed = Math.floor((Date.now() - start) / 1000);
        timerEl.textContent = elapsed + 's elapsed';
    }, 1000);
}
</script>

<?php else: ?>
<!-- ===== REPORT VIEW WITH DASHBOARD ===== -->
<div class="lcr-wrapper">
    <!-- Banner -->
    <div class="lcr-banner">
        <h1><i class="fas fa-hard-hat" style="margin-right:4px;"></i> Labour Cost Report</h1>
        <div class="lcr-breadcrumb">
            <a href="index.php">Home</a> &nbsp;/&nbsp; <a href="LabourCostReport.php">Labour Cost Report</a> &nbsp;/&nbsp; Results
        </div>
        <?php if ($fromLabel || $toLabel): ?>
        <div class="lcr-period-info">
            <i class="fas fa-calendar-alt"></i>
            Period: <?php echo htmlspecialchars($fromLabel); ?> &mdash; <?php echo htmlspecialchars($toLabel); ?>
            &nbsp;&bull;&nbsp; <?php echo count($labourItems); ?> labour codes
        </div>
        <?php endif; ?>
    </div>

    <!-- Back Button -->
    <a href="LabourCostReport.php" class="lcr-back-btn">
        <i class="fas fa-arrow-left"></i> New Report
    </a>

    <!-- Dashboard Toggle -->
    <button class="lcr-dash-toggle" id="lcrDashToggle" onclick="toggleLcrDashboard()">
        <i class="fas fa-chevron-down"></i>
        <span>Dashboard</span>
    </button>

    <!-- Dashboard Container -->
    <div class="lcr-dashboard" id="lcrDashboard">

        <!-- KPI Cards -->
        <div class="lcr-kpi-grid">
            <div class="lcr-kpi-card">
                <div class="lcr-kpi-icon cost"><i class="fas fa-dollar-sign"></i></div>
                <div class="lcr-kpi-content">
                    <div class="lcr-kpi-label">Base Labour Cost</div>
                    <div class="lcr-kpi-value">$<?php echo number_format($totalCost, 2); ?></div>
                    <div class="lcr-kpi-sub">Gross wages</div>
                </div>
            </div>
            <div class="lcr-kpi-card fnpf">
                <div class="lcr-kpi-icon fnpf"><i class="fas fa-piggy-bank"></i></div>
                <div class="lcr-kpi-content">
                    <div class="lcr-kpi-label">FNPF (Employer)</div>
                    <div class="lcr-kpi-value">$<?php echo number_format($totalFnpf, 2); ?></div>
                    <div class="lcr-kpi-sub"><?php echo $totalCost > 0 ? number_format(($totalFnpf / $totalCost) * 100, 1) : '0.0'; ?>% of base cost</div>
                </div>
            </div>
            <div class="lcr-kpi-card tpaf">
                <div class="lcr-kpi-icon tpaf"><i class="fas fa-shield-alt"></i></div>
                <div class="lcr-kpi-content">
                    <div class="lcr-kpi-label">TPAF Cost</div>
                    <div class="lcr-kpi-value">$<?php echo number_format($totalTpaf, 2); ?></div>
                    <div class="lcr-kpi-sub"><?php echo $totalCost > 0 ? number_format(($totalTpaf / $totalCost) * 100, 2) : '0.00'; ?>% of base cost</div>
                </div>
            </div>
            <div class="lcr-kpi-card grand">
                <div class="lcr-kpi-icon grand"><i class="fas fa-calculator"></i></div>
                <div class="lcr-kpi-content">
                    <div class="lcr-kpi-label">Grand Total</div>
                    <div class="lcr-kpi-value">$<?php echo number_format($grandTotal, 2); ?></div>
                    <div class="lcr-kpi-sub">Cost + FNPF + TPAF</div>
                </div>
            </div>
        </div>

        <!-- Charts Row -->
        <div class="lcr-chart-grid">
            <div class="lcr-chart-card">
                <h3><i class="fas fa-chart-bar"></i> Top <?php echo min(count($chartItems), 10); ?> Labour Codes by Total Cost</h3>
                <div class="lcr-chart-container">
                    <canvas id="lcrBarChart"></canvas>
                </div>
            </div>
            <div class="lcr-chart-card">
                <h3><i class="fas fa-chart-pie"></i> Cost Breakdown</h3>
                <div class="lcr-chart-container">
                    <canvas id="lcrDoughnutChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Insights Row -->
        <div class="lcr-insights-grid">
            <!-- Top 5 Costliest -->
            <div class="lcr-insight-card">
                <h4><i class="fas fa-fire"></i> Top 5 Costliest Codes</h4>
                <?php
                $top5 = array_slice($chartItems, 0, 5);
                foreach ($top5 as $idx => $item) {
                    $pct = $grandTotal > 0 ? ($item['totalcost'] / $grandTotal) * 100 : 0;
                    $badgeClass = $pct > 20 ? 'high' : ($pct > 10 ? 'med' : 'low');
                    echo '<div class="lcr-insight-item">';
                    echo '  <span class="label">' . htmlspecialchars($item['labourcode']) . '</span>';
                    echo '  <span class="value">$' . number_format($item['totalcost'], 2) . ' <span class="lcr-badge ' . $badgeClass . '">' . number_format($pct, 1) . '%</span></span>';
                    echo '</div>';
                }
                if (empty($top5)) echo '<p style="color:#9CA3AF; font-size:13px;">No data</p>';
                ?>
            </div>

            <!-- Cost Distribution -->
            <div class="lcr-insight-card">
                <h4><i class="fas fa-layer-group"></i> Cost Distribution</h4>
                <?php
                $costPct = $grandTotal > 0 ? ($totalCost / $grandTotal) * 100 : 0;
                $fnpfPct = $grandTotal > 0 ? ($totalFnpf / $grandTotal) * 100 : 0;
                $tpafPct = $grandTotal > 0 ? ($totalTpaf / $grandTotal) * 100 : 0;
                ?>
                <div class="lcr-insight-item">
                    <span class="label">Base Cost</span>
                    <span class="value"><?php echo number_format($costPct, 1); ?>%</span>
                </div>
                <div style="margin-bottom:8px;">
                    <div class="lcr-progress-wrap"><div class="lcr-progress-bar" style="width:<?php echo $costPct; ?>%; background: linear-gradient(90deg, #2AABB3, #1E8F96);"></div></div>
                </div>
                <div class="lcr-insight-item">
                    <span class="label">FNPF Employer</span>
                    <span class="value"><?php echo number_format($fnpfPct, 1); ?>%</span>
                </div>
                <div style="margin-bottom:8px;">
                    <div class="lcr-progress-wrap"><div class="lcr-progress-bar" style="width:<?php echo min($fnpfPct * 5, 100); ?>%; background: linear-gradient(90deg, #1890FF, #096DD9);"></div></div>
                </div>
                <div class="lcr-insight-item">
                    <span class="label">TPAF</span>
                    <span class="value"><?php echo number_format($tpafPct, 1); ?>%</span>
                </div>
                <div>
                    <div class="lcr-progress-wrap"><div class="lcr-progress-bar" style="width:<?php echo min($tpafPct * 20, 100); ?>%; background: linear-gradient(90deg, #FAAD14, #D48806);"></div></div>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="lcr-insight-card">
                <h4><i class="fas fa-info-circle"></i> Quick Stats</h4>
                <div class="lcr-insight-item">
                    <span class="label">Total Labour Codes</span>
                    <span class="value"><?php echo count($labourItems); ?></span>
                </div>
                <div class="lcr-insight-item">
                    <span class="label">Avg Cost per Code</span>
                    <span class="value">$<?php echo count($labourItems) > 0 ? number_format($grandTotal / count($labourItems), 2) : '0.00'; ?></span>
                </div>
                <?php
                // Find highest and lowest
                $highest = isset($chartItems[0]) ? $chartItems[0] : null;
                $lowest = count($chartItems) > 0 ? $chartItems[count($chartItems) - 1] : null;
                ?>
                <div class="lcr-insight-item">
                    <span class="label">Highest Code</span>
                    <span class="value"><?php echo $highest ? htmlspecialchars($highest['labourcode']) : '-'; ?></span>
                </div>
                <div class="lcr-insight-item">
                    <span class="label">Lowest Code</span>
                    <span class="value"><?php echo $lowest ? htmlspecialchars($lowest['labourcode']) : '-'; ?></span>
                </div>
                <?php
                // Concentration: what % do top 3 codes represent?
                $top3Sum = 0;
                for ($i = 0; $i < min(3, count($chartItems)); $i++) {
                    $top3Sum += floatval($chartItems[$i]['totalcost']);
                }
                $top3Pct = $grandTotal > 0 ? ($top3Sum / $grandTotal) * 100 : 0;
                ?>
                <div class="lcr-insight-item">
                    <span class="label">Top 3 Concentration</span>
                    <span class="value"><span class="lcr-badge <?php echo $top3Pct > 60 ? 'high' : ($top3Pct > 40 ? 'med' : 'low'); ?>"><?php echo number_format($top3Pct, 1); ?>%</span></span>
                </div>
            </div>
        </div>
    </div><!-- end dashboard -->

    <!-- Data Table -->
    <div class="lcr-table-card">
        <h3><i class="fas fa-table"></i> Labour Cost Detail</h3>
        <div class="table-responsive">
            <table id="reportTable" class="display nowrap" style="width:100%">
                <thead>
                    <tr>
                        <th>Labour Code</th>
                        <th>Description</th>
                        <th>Base Cost ($)</th>
                        <th>FNPF ($)</th>
                        <th>TPAF ($)</th>
                        <th>Total ($)</th>
                        <th>% of Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if (!empty($labourItems)) {
                        foreach ($labourItems as $row) {
                            $pct = $grandTotal > 0 ? (floatval($row['totalcost']) / $grandTotal) * 100 : 0;
                            echo '<tr>';
                            echo '<td><strong>' . htmlspecialchars($row['labourcode']) . '</strong></td>';
                            echo '<td>' . htmlspecialchars($row['description']) . '</td>';
                            echo '<td style="text-align:right;">' . number_format($row['cost'], 2) . '</td>';
                            echo '<td style="text-align:right;">' . number_format($row['fnpfcost'], 2) . '</td>';
                            echo '<td style="text-align:right;">' . number_format($row['tpafcost'], 2) . '</td>';
                            echo '<td style="text-align:right; font-weight:600;">' . number_format($row['totalcost'], 2) . '</td>';
                            echo '<td>';
                            echo '  <div class="lcr-cost-bar-wrap">';
                            echo '    <span style="font-size:12px; min-width:42px;">' . number_format($pct, 1) . '%</span>';
                            echo '    <div class="lcr-cost-bar"><div class="lcr-cost-bar-fill" style="width:' . min($pct * 2, 100) . '%;"></div></div>';
                            echo '  </div>';
                            echo '</td>';
                            echo '</tr>';
                        }
                    }
                    // TOTAL row
                    if ($totalRow) {
                        echo '<tr class="total-row">';
                        echo '<td><strong>TOTAL</strong></td>';
                        echo '<td></td>';
                        echo '<td style="text-align:right;">' . number_format($totalRow['cost'], 2) . '</td>';
                        echo '<td style="text-align:right;">' . number_format($totalRow['fnpfcost'], 2) . '</td>';
                        echo '<td style="text-align:right;">' . number_format($totalRow['tpafcost'], 2) . '</td>';
                        echo '<td style="text-align:right;">' . number_format($totalRow['totalcost'], 2) . '</td>';
                        echo '<td>100%</td>';
                        echo '</tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>

</div><!-- end wrapper -->

<!-- jQuery + DataTables + Buttons + Chart.js -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<script>
// ===== Dashboard Toggle with localStorage =====
function toggleLcrDashboard() {
    var dash = document.getElementById('lcrDashboard');
    var btn = document.getElementById('lcrDashToggle');
    var isCollapsed = dash.classList.toggle('collapsed');
    btn.classList.toggle('collapsed', isCollapsed);
    try { localStorage.setItem('lcr_dash_collapsed', isCollapsed ? '1' : '0'); } catch(e) {}
}
(function() {
    try {
        if (localStorage.getItem('lcr_dash_collapsed') === '1') {
            document.getElementById('lcrDashboard').classList.add('collapsed');
            document.getElementById('lcrDashToggle').classList.add('collapsed');
        }
    } catch(e) {}
})();

// ===== DataTable =====
$(document).ready(function() {
    $('#reportTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'excelHtml5', title: 'Labour_Cost_Report', className: 'dt-button' },
            { extend: 'pdfHtml5', title: 'Labour Cost Report', className: 'dt-button' },
            { extend: 'print', title: 'Labour Cost Report', className: 'dt-button' }
        ],
        scrollX: true,
        pageLength: 50,
        order: [[5, 'desc']],
        columnDefs: [
            { targets: [2,3,4,5], className: 'dt-body-right' }
        ],
        createdRow: function(row, data) {
            if (data[0] && data[0].indexOf('TOTAL') !== -1) {
                $(row).addClass('total-row');
            }
        }
    });
});

// ===== Chart.js Charts =====
<?php
// Prepare chart data
$barLabels = array();
$barCosts = array();
$barFnpf = array();
$barTpaf = array();
foreach ($topN as $item) {
    $barLabels[] = $item['labourcode'];
    $barCosts[] = round(floatval($item['cost']), 2);
    $barFnpf[] = round(floatval($item['fnpfcost']), 2);
    $barTpaf[] = round(floatval($item['tpafcost']), 2);
}
?>

// Bar Chart - Top 10 (Horizontal)
(function() {
    var ctx = document.getElementById('lcrBarChart');
    if (!ctx) return;
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($barLabels); ?>,
            datasets: [
                {
                    label: 'Base Cost',
                    data: <?php echo json_encode($barCosts); ?>,
                    backgroundColor: 'rgba(42, 171, 179, 0.85)',
                    borderRadius: 3,
                    barThickness: 14
                },
                {
                    label: 'FNPF',
                    data: <?php echo json_encode($barFnpf); ?>,
                    backgroundColor: 'rgba(24, 144, 255, 0.75)',
                    borderRadius: 3,
                    barThickness: 14
                },
                {
                    label: 'TPAF',
                    data: <?php echo json_encode($barTpaf); ?>,
                    backgroundColor: 'rgba(250, 173, 20, 0.75)',
                    borderRadius: 3,
                    barThickness: 14
                }
            ]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top', labels: { font: { family: 'Poppins', size: 11 }, usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, padding: 12 } },
                tooltip: {
                    callbacks: {
                        label: function(ctx) { return ctx.dataset.label + ': $' + ctx.parsed.x.toLocaleString(undefined, {minimumFractionDigits:2}); }
                    }
                }
            },
            scales: {
                y: { stacked: true, grid: { display: false }, ticks: { font: { family: 'Poppins', size: 11 }, autoSkip: false } },
                x: { stacked: true, grid: { color: '#F3F4F6' }, ticks: { font: { family: 'Poppins', size: 10 }, callback: function(v) { return '$' + (v >= 1000 ? (v/1000).toFixed(0) + 'k' : v); } } }
            }
        }
    });
})();

// Doughnut Chart - Cost Breakdown
(function() {
    var ctx = document.getElementById('lcrDoughnutChart');
    if (!ctx) return;
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['Base Cost', 'FNPF (Employer)', 'TPAF'],
            datasets: [{
                data: [<?php echo round($totalCost, 2); ?>, <?php echo round($totalFnpf, 2); ?>, <?php echo round($totalTpaf, 2); ?>],
                backgroundColor: ['#2AABB3', '#1890FF', '#FAAD14'],
                borderWidth: 0,
                hoverOffset: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '60%',
            plugins: {
                legend: { position: 'bottom', labels: { font: { family: 'Poppins', size: 12 }, usePointStyle: true, pointStyle: 'circle', padding: 16 } },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            var total = ctx.dataset.data.reduce(function(a,b) { return a+b; }, 0);
                            var pct = total > 0 ? ((ctx.parsed / total) * 100).toFixed(1) : '0.0';
                            return ctx.label + ': $' + ctx.parsed.toLocaleString(undefined, {minimumFractionDigits:2}) + ' (' + pct + '%)';
                        }
                    }
                }
            }
        }
    });
})();
</script>

<?php endif; ?>

<?php
echo '</div>';
?>
</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>
</body>
</html>
<?php
include('includes/MainMenuLinksArray.php');
?>
