<?php
session_start();

/* ─────────────────────────────────────────────
   COMMON FILTER  (month / year)
───────────────────────────────────────────── */
$month = isset($_GET['month']) ? intval($_GET['month']) : date('n');
$year  = isset($_GET['year'])  ? intval($_GET['year'])  : date('Y');
if ($month < 1 || $month > 12) { $month = date('n'); }

$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$month_name    = date('F Y', strtotime("$year-$month-01"));

/* ─────────────────────────────────────────────
   SELECTED DATE FOR WIP SUMMARY
   Default = yesterday (clamped to selected month)
───────────────────────────────────────────── */
$current_month = date('n');
$current_year  = date('Y');

/* MTD cutoff: for the current month, "elapsed" stops at today so that
   summary totals compare actual-to-date against target-to-date rather
   than the whole month's target (which would make Achievement Rate
   look artificially low before the month is over). Past/future months
   use the full month, since there is no "today" within them. */
$is_current_month = ($month == $current_month && $year == $current_year);
$elapsed_day       = $is_current_month ? intval(date('j')) : $days_in_month;

if (isset($_GET['wip_day']) && intval($_GET['wip_day']) > 0) {
    $wip_day = intval($_GET['wip_day']);
} else {
    if ($month == $current_month && $year == $current_year) {
        $wip_day = date('j', strtotime('-1 day')); // yesterday
    } else {
        $wip_day = $days_in_month; // last day of past/future month
    }
}
$wip_day = max(1, min($wip_day, $days_in_month));

/* ─────────────────────────────────────────────
   ACTIVE TAB FROM ?red=N
   FIX: was $_REQUEST (GET/POST/COOKIE - wider attack surface than
   needed) and unvalidated. An out-of-range value (e.g. ?red=99) meant
   none of the tab_active[0..6] slots matched, so no tab ended up
   marked active/show and the page rendered with nothing visible.
───────────────────────────────────────────── */
$red = isset($_GET['red']) ? intval($_GET['red']) : 0;
if ($red < 0 || $red > 6) { $red = 0; }
$tab_active  = array_fill(0, 7, '');
$pane_active = array_fill(0, 7, '');
$tab_active[$red]  = 'active';
$pane_active[$red] = 'active show';

/* ─────────────────────────────────────────────
   SQL QUERIES
───────────────────────────────────────────── */

/* --- daily_production_summary --- */
$prod_sql = "
    SELECT
        DAY(record_date)     AS day,
        DAYNAME(record_date) AS day_name,
        fg,
        fg_difference,
        rm,
        vac_wip,
        cnc_wip,
        pu_wip,
        std_hours_vac,
        std_hours_cnc,
        std_hours_pu,
        std_hours_assbly,
        clock_hours_vac,
        clock_hours_cnc,
        clock_hours_pu
    FROM daily_production_summary
    WHERE MONTH(record_date) = $month AND YEAR(record_date) = $year
    ORDER BY record_date ASC
";
$prod_result = mysqli_query($conn, $prod_sql);
$prod_data   = [];
while ($row = mysqli_fetch_assoc($prod_result)) {
    $prod_data[$row['day']] = $row;
}

/* --- sales --- */
$sales_sql = "
    SELECT
        DAY(pp.req_date)                                   AS day,
        SUM(pp.req_qty * IFNULL(im.standard_cost_ebq, 0)) AS total_sales
    FROM production_planning pp
    LEFT JOIN item_management im ON im.id = pp.part_id
    WHERE MONTH(pp.req_date) = $month AND YEAR(pp.req_date) = $year
    GROUP BY DAY(pp.req_date)
    ORDER BY pp.req_date ASC
";
$sales_result = mysqli_query($conn, $sales_sql);
$sales_data   = [];
while ($row = mysqli_fetch_assoc($sales_result)) {
    $sales_data[$row['day']] = floatval($row['total_sales']);
}

/* ─────────────────────────────────────────────
   WIP SUMMARY
   1. Snapshot on the selected date
   2. Month-opening snapshot (first day with data)
───────────────────────────────────────────── */
$sel          = $prod_data[$wip_day] ?? null;
$wip_sel_vac  = $sel ? floatval($sel['vac_wip']) : 0;
$wip_sel_cnc  = $sel ? floatval($sel['cnc_wip']) : 0;
$wip_sel_pu   = $sel ? floatval($sel['pu_wip'])  : 0;
$wip_sel_tot  = $wip_sel_vac + $wip_sel_cnc + $wip_sel_pu;

$wip_open_vac = 0; $wip_open_cnc = 0; $wip_open_pu = 0; $wip_open_day = null;
for ($d = 1; $d <= $days_in_month; $d++) {
    $r = $prod_data[$d] ?? null;
    if ($r && (floatval($r['vac_wip']) + floatval($r['cnc_wip']) + floatval($r['pu_wip'])) > 0) {
        $wip_open_vac = floatval($r['vac_wip']);
        $wip_open_cnc = floatval($r['cnc_wip']);
        $wip_open_pu  = floatval($r['pu_wip']);
        $wip_open_day = $d;
        break;
    }
}
$wip_open_tot = $wip_open_vac + $wip_open_cnc + $wip_open_pu;

/* ─────────────────────────────────────────────
   CONSTANTS & KPI TARGETS
───────────────────────────────────────────── */
$STOCKTAKE_TARGET   = 615000;
$PROD_TOTAL_TARGET  = 0;
$SALES_DAILY_TARGET = 0;
$FG_DAILY_TARGET    = 0;
$STD_HOURS_TARGET   = 0;
$CLOCK_HOURS_TARGET = 0;

$month_key = $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT);

$sql = "
    SELECT sales, fg_movement, rev_per_std_hours,
           working_days, no_of_directs, no_of_tpl_directs
    FROM monthly_kpi WHERE month_key = '$month_key' LIMIT 1
";
$result = mysqli_query($conn, $sql);
if ($result && mysqli_num_rows($result) > 0) {
    $row               = mysqli_fetch_assoc($result);
    $sales             = (float)$row['sales'];
    $fg_movement       = (float)$row['fg_movement'];
    $rev_per_std_hours = (float)$row['rev_per_std_hours'];
    $working_days      = (float)$row['working_days'];
    $no_of_directs = (float)$row['no_of_directs'];

    if ($working_days > 0) {
        $PROD_TOTAL_TARGET  = ($sales + $fg_movement) / $working_days;
        $SALES_DAILY_TARGET = $sales / $working_days;
        $FG_DAILY_TARGET    = $fg_movement / $working_days;
    }
    if ($rev_per_std_hours > 0 && $working_days > 0) {
        $STD_HOURS_TARGET = (($sales + $fg_movement) / $rev_per_std_hours) / $working_days;
    }
    if ($working_days > 0 && $no_of_directs > 0) {
        $B22 = $working_days * 9.5 * $no_of_directs;
        $CLOCK_HOURS_TARGET = ($B22 - 0.03 * $B22 - 0.013 * $B22) / $working_days;
    }
}

/* ─────────────────────────────────────────────
   HELPERS
───────────────────────────────────────────── */
function fmt_gbp($v, $dash_if_zero = true) {
    if ($dash_if_zero && $v == 0) return '<span class="no-data">-</span>';
    return '£&nbsp;' . number_format($v, 2);
}
function fmt_num($v, $decimals = 1) { return number_format($v, $decimals); }
function variance_class($v)         { return $v >= 0 ? 'pos-var' : 'neg-var'; }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Daily Progress - <?= htmlspecialchars($month_name, ENT_QUOTES) ?></title>
<!--
    FIX: this page used Bootstrap tab/card classes and a $(document).ready()
    jQuery call for Toastify, but never loaded Bootstrap CSS, jQuery, or
    Toastify's CSS/JS anywhere. Result: unstyled tabs/cards, and the toast
    script throwing "$ is not defined" so info messages never appeared.
    Added the same includes the sibling report page uses, and rewired the
    toast trigger to vanilla JS (matching the tab-switch script further
    down) so jQuery isn't required at all.
-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
em { color: red; }
.card.card-purple .card-header { background-color: #9c4893; }
.status-box   { display:inline-block;padding:5px 10px;border-radius:5px;color:#fff;font-size:13px;font-weight:bold;margin-right:5px; }
.Complete     { background-color:green; }
.inprogress   { background-color:#9c4893; }
.Incomplete   { background-color:#e31414; }
.progress-icon        { display:inline-block;width:10px;height:10px;border-radius:50%;margin-left:5px; }
.progress-icon.red    { background-color:red; }
.progress-icon.yellow { background-color:#9c4893; }
.progress-icon.green  { background-color:green; }

/* ── shared table ── */
.rpt-wrap         { width:100%;padding:20px;background:#fff;box-sizing:border-box; }
.rpt-wrap h2      { color:#333;margin-bottom:16px;font-size:22px; }
.table-responsive { overflow-x:auto;margin-top:16px; }
table             { width:100%;border-collapse:collapse;min-width:800px; }
th, td            { border:1px solid #ccc;padding:8px;text-align:center;font-size:13px; }
th                { background:#4CAF50;color:#fff;font-weight:bold;position:sticky;top:0;z-index:10; }
tr:nth-child(even){ background:#f9f9f9; }
tr:hover          { background:#f0f0f0; }
.weekend          { background:#e0e0e0; }
.no-data          { color:#999; }
.date-col         { text-align:left;font-weight:600;background:#f8f9fa; }
.day-col          { text-align:left; }
.currency         { text-align:right; }
.pos-var          { background:#c8e6c9;color:#2e7d32;font-weight:bold; }
.neg-var          { background:#ffcdd2;color:#c62828;font-weight:bold; }
.positive         { color:#008000;font-weight:bold; }
.negative         { color:#FF0000;font-weight:bold; }
.over-target      { background:#ffe6e6; }
.under-target     { background:#e6ffe6; }
.th-blue th       { background:#4472C4; }
.th-green th      { background:#4CAF50; }
.summary-box      { margin-top:16px;padding:14px;background:#f8f9fa;border-radius:6px; }
.summary-box h3   { margin:0 0 10px;font-size:16px;color:#333; }
.summary-box p    { margin:4px 0;font-size:13px; }
.summary-box .mtd-note { font-size:11px;color:#888;margin-top:8px; }
.target-col       { background:#d9d9d9; }
.actual-col       { background:#fff; }

/* ── WIP summary panels ── */
.wip-panels {
    display:flex;
    gap:16px;
    flex-wrap:wrap;
    margin:4px 0 18px 0;
}
.wip-panel {
    flex:1 1 320px;
    border:1px solid #ccc;
    border-radius:8px;
    overflow:hidden;
    box-shadow:0 1px 4px rgba(0,0,0,.08);
}
.wip-panel-hdr {
    padding:10px 14px;
    font-weight:700;
    font-size:13px;
    color:#fff;
    display:flex;
    justify-content:space-between;
    align-items:center;
}
.wip-panel-hdr.blue { background:#4472C4; }
.wip-panel-hdr.teal { background:#1a7a6e; }
.wip-panel table    { min-width:unset;margin:0;border:none;box-shadow:none; }
.wip-panel table th { background:#f0f4ff;color:#333;font-size:12px;padding:7px 14px;position:static; }
.wip-panel table td { font-size:13px;padding:7px 14px;border-color:#e8e8e8; }
.wip-panel .tot-row td { background:#e8f0ff;font-weight:700;border-top:2px solid #4472C4; }
.wip-panel .tot-row.teal td { background:#e0f5f0;border-top-color:#1a7a6e; }
.wip-panel table th:last-child,
.wip-panel table td:last-child { text-align:right; }
.wip-panel table th:first-child,
.wip-panel table td:first-child { text-align:left; }

/* ── date picker bar ── */
.wip-date-bar {
    display:flex;align-items:center;gap:10px;flex-wrap:wrap;
    margin-bottom:14px;
    background:#f8f9fa;padding:10px 14px;border-radius:6px;
}
.wip-date-bar label  { font-weight:600;font-size:13px;margin:0; }
.wip-date-bar select { padding:5px 10px;border:1px solid #ccc;border-radius:4px;font-size:13px; }
.wip-date-bar button {
    padding:5px 14px;background:#4472C4;color:#fff;
    border:none;border-radius:4px;cursor:pointer;font-size:13px;
}
.wip-date-bar .hint  { font-size:11px;color:#888; }

/* ── inputs table footer total row ── */
tfoot tr td {
    background:#fff3cd !important;
    font-weight:700;
    border-top:2px solid #999;
}
</style>
</head>
<body>

<section class="content-header">
<?php if (isset($_SESSION['info_message'])): ?>
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        Toastify({
            text: <?= json_encode($_SESSION['info_message']) ?>,
            duration: 2000,
            close: true,
            gravity: 'top',
            position: 'right',
            backgroundColor: '#28a745',
            style: { borderBottom: '3px solid white' }
        }).showToast();
    });
    </script>
    <?php unset($_SESSION['info_message']); ?>
<?php endif; ?>
    <div class="container-fluid">
        <div class="row"><div class="col-sm-8">
            <h1 style="float:left;margin-top:0;padding-bottom:0;">View Daily Progress</h1>
        </div></div>
    </div>
</section>

<section>
<div class="container-fluid" style="padding:16px;">

    <!-- ── COMMON FILTER ── -->
    <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;background:#f8f9fa;padding:14px;border-radius:6px;margin-bottom:16px;">
        <label for="f_month" style="font-weight:600;margin:0;">Month:</label>
        <select id="f_month" style="padding:5px 10px;border:1px solid #ccc;border-radius:4px;">
            <?php for ($m = 1; $m <= 12; $m++): ?>
                <option value="<?= $m ?>" <?= $m == $month ? 'selected' : '' ?>>
                    <?= date('F', mktime(0,0,0,$m,1)) ?>
                </option>
            <?php endfor; ?>
        </select>
        <label for="f_year" style="font-weight:600;margin:0;">Year:</label>
        <select id="f_year" style="padding:5px 10px;border:1px solid #ccc;border-radius:4px;">
            <?php for ($y = date('Y') - 2; $y <= date('Y') + 2; $y++): ?>
                <option value="<?= $y ?>" <?= $y == $year ? 'selected' : '' ?>><?= $y ?></option>
            <?php endfor; ?>
        </select>
        <button onclick="applyFilter()" style="padding:6px 16px;background:#007bff;color:#fff;border:none;border-radius:4px;cursor:pointer;">View</button>
        <span style="font-size:13px;color:#555;">Showing: <strong><?= htmlspecialchars($month_name, ENT_QUOTES) ?></strong></span>
    </div>

<script>
function applyFilter() {
    var url = new URL(window.location.href);
    url.searchParams.set('month', document.getElementById('f_month').value);
    url.searchParams.set('year',  document.getElementById('f_year').value);
    url.searchParams.set('red',   window._activeTab || '0');
    url.searchParams.delete('wip_day'); // reset so default (yesterday) kicks in
    window.location.href = url.toString();
}
function applyWipDay() {
    var url = new URL(window.location.href);
    url.searchParams.set('wip_day', document.getElementById('wip_day_sel').value);
    url.searchParams.set('red', '0');
    window.location.href = url.toString();
}
window._activeTab = '<?= $red ?>';
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('#dpTab a').forEach(function(a, i) {
        a.addEventListener('shown.bs.tab', function () { window._activeTab = String(i); });
    });
});
</script>

    <div class="col-md-12">
        <div class="card card-purple card-tabs">
            <div class="card-header p-0 pt-1">
                <ul class="nav nav-tabs" id="dpTab" role="tablist">
                    <?php
                    $tabs = [
                        ['id'=>'tab-inputs',  'label'=>'DAILY INPUTS'],
                        ['id'=>'tab-prodtot', 'label'=>'PRODUCTION TOTAL'],
                        ['id'=>'tab-sales',   'label'=>'SALES'],
                        ['id'=>'tab-fg',      'label'=>'FG STOCK'],
                        ['id'=>'tab-wip',     'label'=>'WIP'],
                        ['id'=>'tab-std',     'label'=>'STD HOURS'],
                        ['id'=>'tab-clock',   'label'=>'CLOCK HOURS'],
                    ];
                    foreach ($tabs as $i => $t): ?>
                    <li class="nav-item">
                        <a class="nav-link <?= $tab_active[$i] ?>"
                           data-bs-toggle="pill"
                           href="#<?= $t['id'] ?>">
                            <b><?= $t['label'] ?></b>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>

            <div class="card-body">
            <div class="tab-content">

            <!-- ══════════════════════════════════════════
                 TAB 0 – DAILY INPUTS
            ══════════════════════════════════════════ -->
            <div class="tab-pane fade <?= $pane_active[0] ?>" id="tab-inputs">
            <div class="rpt-wrap">
                <h2>Production Summary – <?= $month_name ?></h2>

                <!-- ── WIP date picker ── -->
                <div class="wip-date-bar">
                    <label for="wip_day_sel">WIP Snapshot Date:</label>
                    <select id="wip_day_sel">
                        <?php for ($d = 1; $d <= $days_in_month; $d++):
                            $lbl = sprintf('%02d %s %d', $d, date('M', strtotime("$year-$month-01")), $year);
                        ?>
                            <option value="<?= $d ?>" <?= $d == $wip_day ? 'selected' : '' ?>>
                                <?= $lbl ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                    <button onclick="applyWipDay()">Apply</button>
                    <span class="hint">Defaults to yesterday</span>
                </div>

                <!-- ── WIP PANELS ── -->
                <div class="wip-panels">

                    <!-- Panel A: Selected-date snapshot -->
                    <div class="wip-panel">
                        <div class="wip-panel-hdr blue">
                            <span>WIP Snapshot &mdash;
                                <?= sprintf('%02d %s %d', $wip_day,
                                    date('M', strtotime("$year-$month-01")), $year) ?>
                            </span>
                            <?php if ($wip_sel_tot == 0): ?>
                                <span style="font-size:11px;opacity:.8;">No data</span>
                            <?php endif; ?>
                        </div>
                        <table>
                            <thead>
                                <tr><th>WIP Type</th><th>Value</th></tr>
                            </thead>
                            <tbody>
                                <tr><td>VAC WIP</td><td><?= fmt_gbp($wip_sel_vac) ?></td></tr>
                                <tr><td>CNC WIP</td><td><?= fmt_gbp($wip_sel_cnc) ?></td></tr>
                                <tr><td>PU WIP</td><td><?= fmt_gbp($wip_sel_pu) ?></td></tr>
                                <tr class="tot-row">
                                    <td>Total WIP</td>
                                    <td><?= fmt_gbp($wip_sel_tot, false) ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Panel B: Month-opening snapshot -->
                    <div class="wip-panel">
                        <div class="wip-panel-hdr teal">
                            <span>Month Opening WIP &mdash;
                                <?php if ($wip_open_day):
                                    echo sprintf('%02d %s %d', $wip_open_day,
                                        date('M', strtotime("$year-$month-01")), $year);
                                else:
                                    echo 'No data this month';
                                endif; ?>
                            </span>
                        </div>
                        <table>
                            <thead>
                                <tr><th>WIP Type</th><th>Opening Value</th></tr>
                            </thead>
                            <tbody>
                                <tr><td>VAC WIP</td><td><?= fmt_gbp($wip_open_vac) ?></td></tr>
                                <tr><td>CNC WIP</td><td><?= fmt_gbp($wip_open_cnc) ?></td></tr>
                                <tr><td>PU WIP</td><td><?= fmt_gbp($wip_open_pu) ?></td></tr>
                                <tr class="tot-row teal">
                                    <td>Total WIP</td>
                                    <td><?= fmt_gbp($wip_open_tot, false) ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                </div><!-- /wip-panels -->

                <!-- ── DAILY INPUTS TABLE ── -->
                <div class="table-responsive">
                <table class="th-green">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Sales</th>
                            <th>FG</th>
                            <th>RM</th>
                            <th>VAC WIP</th>
                            <th>CNC WIP</th>
                            <th>PU WIP</th>
                            <th>Total WIP</th>
                            <th>Total Stock Value</th>
                            <th>Stocktake Target</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    $sum_sales = $sum_fg = $sum_rm = 0;
                    $sum_vac   = $sum_cnc = $sum_pu = $sum_wip = $sum_stock = 0;

                    for ($day = 1; $day <= $days_in_month; $day++):
                        $p       = $prod_data[$day] ?? null;
                        $sales   = $sales_data[$day] ?? 0;
                        $rm      = $p ? floatval($p['rm'])      : 0;
                        $vac_wip = $p ? floatval($p['vac_wip']) : 0;
                        $cnc_wip = $p ? floatval($p['cnc_wip']) : 0;
                        $pu_wip  = $p ? floatval($p['pu_wip'])  : 0;
                        $fg      = $p ? floatval($p['fg'])      : 0;
                        $day_wip = $vac_wip + $cnc_wip + $pu_wip;
                        $total   = $fg + $rm + $day_wip;
                        $row_cls = $total > 0 ? ($total > $STOCKTAKE_TARGET ? 'over-target' : 'under-target') : '';
                        $dt      = $day.'-'.date('M', strtotime("$year-$month-01"));

                        /* accumulate totals for rows that have any stock data */
                        if ($total > 0 || $sales > 0) {
                            $sum_sales += $sales;
                            $sum_fg    += $fg;
                            $sum_rm    += $rm;
                            $sum_vac   += $vac_wip;
                            $sum_cnc   += $cnc_wip;
                            $sum_pu    += $pu_wip;
                            $sum_wip   += $day_wip;
                            $sum_stock += $total;
                        }
                    ?>
                        <tr class="<?= $row_cls ?>">
                            <td class="date-col"><?= $dt ?></td>
                            <td><?= fmt_gbp($sales) ?></td>
                            <td><?= fmt_gbp($fg) ?></td>
                            <td><?= fmt_gbp($rm) ?></td>
                            <td><?= fmt_gbp($vac_wip) ?></td>
                            <td><?= fmt_gbp($cnc_wip) ?></td>
                            <td><?= fmt_gbp($pu_wip) ?></td>
                            <td><strong><?= fmt_gbp($day_wip) ?></strong></td>
                            <td><strong><?= fmt_gbp($total) ?></strong></td>
                            <td>£&nbsp;<?= number_format($STOCKTAKE_TARGET, 2) ?></td>
                        </tr>
                    <?php endfor; ?>
                    </tbody>

                    <!-- ── MONTH TOTALS ROW ── -->
                    <tfoot>
                        <tr>
                            <td style="text-align:left;">Month Total</td>
                            <td><?= fmt_gbp($sum_sales, false) ?></td>
                            <td><?= fmt_gbp($sum_fg, false) ?></td>
                            <td><?= fmt_gbp($sum_rm, false) ?></td>
                            <td><?= fmt_gbp($sum_vac, false) ?></td>
                            <td><?= fmt_gbp($sum_cnc, false) ?></td>
                            <td><?= fmt_gbp($sum_pu, false) ?></td>
                            <td><?= fmt_gbp($sum_wip, false) ?></td>
                            <td><?= fmt_gbp($sum_stock, false) ?></td>
                            <td style="color:#999;">—</td>
                        </tr>
                    </tfoot>
                </table>
                </div>
            </div>
            </div><!-- /tab-inputs -->


            <!-- ══════════════════════════════════════════
                 TAB 1 – PRODUCTION TOTAL
            ══════════════════════════════════════════ -->
            <div class="tab-pane fade <?= $pane_active[1] ?>" id="tab-prodtot">
            <div class="rpt-wrap">
                <h2>TPL Production Total</h2>
                <?php $cumv_target = 0; $cumv_actual = 0; $mtd_target = 0; $mtd_actual = 0; ?>
                <div class="table-responsive">
                <table class="th-green">
                    <thead>
                        <tr>
                            <th rowspan="2">Date</th><th rowspan="2">Day</th>
                            <th colspan="2">TARGET</th><th colspan="2">ACTUAL</th>
                            <th rowspan="2">Actual vs Target</th>
                        </tr>
                        <tr>
                            <th>Daily Target</th><th>Cumv Target</th>
                            <th>Daily Actual</th><th>Cumv Actual</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php for ($day = 1; $day <= $days_in_month; $day++):
                        $ts       = strtotime("$year-$month-$day");
                        $day_name = date('l', $ts);
                        $is_wknd  = in_array($day_name, ['Friday','Saturday','Sunday']);
                        $dt       = sprintf('%02d-%s', $day, date('M', $ts));
                        $p        = $prod_data[$day] ?? null;
                        $fg_diff  = $p ? floatval($p['fg_difference']) : 0;
                        $sales    = $sales_data[$day] ?? 0;
                        $daily_act = $sales + $fg_diff;
                        $daily_tgt = $is_wknd ? 0 : $PROD_TOTAL_TARGET;
                        $cumv_target += $daily_tgt;
                        $cumv_actual += $daily_act;
                        /* Snapshot the cumulative totals as of "today" (elapsed_day) for
                           the summary box below, before the loop keeps adding future days. */
                        if ($day == $elapsed_day) { $mtd_target = $cumv_target; $mtd_actual = $cumv_actual; }
                        $var = $cumv_actual - $cumv_target;
                    ?>
                        <tr>
                            <td class="date-col"><?= $dt ?></td>
                            <td class="day-col"><?= $day_name ?></td>
                            <td class="currency"><?= $daily_tgt > 0 ? fmt_gbp($daily_tgt, false) : '<span class="no-data">-</span>' ?></td>
                            <td class="currency">£&nbsp;<?= number_format($cumv_target, 2) ?></td>
                            <td class="currency"><?= $daily_act > 0 ? fmt_gbp($daily_act, false) : '<span class="no-data">-</span>' ?></td>
                            <td class="currency">£&nbsp;<?= number_format($cumv_actual, 2) ?></td>
                            <td class="currency <?= variance_class($var) ?>">£&nbsp;<?= number_format($var, 2) ?></td>
                        </tr>
                    <?php endfor; ?>
                    </tbody>
                </table>
                </div>
                <div class="summary-box">
                    <h3>Summary (Month-to-Date) – <?= $month_name ?></h3>
                    <p><strong>Target to Date:</strong> £<?= number_format($mtd_target, 2) ?></p>
                    <p><strong>Actual to Date:</strong> £<?= number_format($mtd_actual, 2) ?></p>
                    <p><strong>Variance:</strong>
                        <span class="<?= variance_class($mtd_actual - $mtd_target) ?>" style="padding:3px 8px;border-radius:3px;">
                            £<?= number_format($mtd_actual - $mtd_target, 2) ?>
                        </span>
                    </p>
                    <p><strong>Achievement Rate:</strong>
                        <?= $mtd_target > 0 ? number_format(($mtd_actual / $mtd_target) * 100, 2) : '0.00' ?>%
                    </p>
                    <?php if ($is_current_month): ?>
                        <p class="mtd-note">Based on target/actual through today (<?= date('d M Y') ?>). The table above continues to the end of the month to show the full trajectory.</p>
                    <?php else: ?>
                        <p class="mtd-note">Full-month totals (this is a past or future month).</p>
                    <?php endif; ?>
                </div>
            </div>
            </div><!-- /tab-prodtot -->


            <!-- ══════════════════════════════════════════
                 TAB 2 – SALES
            ══════════════════════════════════════════ -->
            <div class="tab-pane fade <?= $pane_active[2] ?>" id="tab-sales">
            <div class="rpt-wrap">
                <h2>TPL Sales</h2>
                <?php $cumv_target = 0; $cumv_actual = 0; $mtd_target = 0; $mtd_actual = 0; ?>
                <div class="table-responsive">
                <table class="th-green">
                    <thead>
                        <tr>
                            <th rowspan="2">Date</th><th rowspan="2">Day</th>
                            <th colspan="2">TARGET</th><th colspan="2">ACTUAL</th>
                        </tr>
                        <tr>
                            <th>Daily Target</th><th>Cumv Target</th>
                            <th>Daily Actual</th><th>Cumv Actual</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php for ($day = 1; $day <= $days_in_month; $day++):
                        $ts       = strtotime("$year-$month-$day");
                        $day_name = date('l', $ts);
                        $is_wknd  = in_array($day_name, ['Saturday','Sunday']);
                        $dt       = sprintf('%02d-%s', $day, date('M', $ts));
                        $daily_act = $sales_data[$day] ?? 0;
                        $daily_tgt = $is_wknd ? 0 : $SALES_DAILY_TARGET;
                        $cumv_target += $daily_tgt;
                        $cumv_actual += $daily_act;
                        if ($day == $elapsed_day) { $mtd_target = $cumv_target; $mtd_actual = $cumv_actual; }
                    ?>
                        <tr class="<?= $is_wknd ? 'weekend' : '' ?>">
                            <td class="date-col"><?= $dt ?></td>
                            <td class="day-col"><?= $day_name ?></td>
                            <td class="currency"><?= $daily_tgt > 0 ? '£'.number_format($daily_tgt,2) : '<span class="no-data">-</span>' ?></td>
                            <td class="currency">£&nbsp;<?= number_format($cumv_target, 2) ?></td>
                            <td class="currency"><?= $daily_act > 0 ? '£'.number_format($daily_act,2) : '<span class="no-data">-</span>' ?></td>
                            <td class="currency">£&nbsp;<?= number_format($cumv_actual, 2) ?></td>
                        </tr>
                    <?php endfor; ?>
                    </tbody>
                </table>
                </div>
                <div class="summary-box">
                    <h3>Summary (Month-to-Date) – <?= $month_name ?></h3>
                    <p><strong>Target to Date:</strong> £<?= number_format($mtd_target, 2) ?></p>
                    <p><strong>Actual Sales to Date:</strong> £<?= number_format($mtd_actual, 2) ?></p>
                    <p><strong>Variance:</strong> £<?= number_format($mtd_actual - $mtd_target, 2) ?></p>
                    <p><strong>Achievement Rate:</strong>
                        <?= $mtd_target > 0 ? number_format(($mtd_actual / $mtd_target) * 100, 2) : '0.00' ?>%
                    </p>
                    <?php if ($is_current_month): ?>
                        <p class="mtd-note">Based on target/actual through today (<?= date('d M Y') ?>). The table above continues to the end of the month to show the full trajectory.</p>
                    <?php else: ?>
                        <p class="mtd-note">Full-month totals (this is a past or future month).</p>
                    <?php endif; ?>
                </div>
            </div>
            </div><!-- /tab-sales -->


            <!-- ══════════════════════════════════════════
                 TAB 3 – FG STOCK
            ══════════════════════════════════════════ -->
            <div class="tab-pane fade <?= $pane_active[3] ?>" id="tab-fg">
            <div class="rpt-wrap">
                <h2>FG Stock Report – <?= strtoupper($month_name) ?></h2>
                <?php $cumv_target = 0; $cumv_diff = 0; ?>
                <div class="table-responsive">
                <table class="th-blue">
                    <thead>
                        <tr>
                            <th>Date</th><th>Day</th>
                            <th>Daily Target</th><th>Cumv Target</th>
                            <th>Daily Snapshot</th><th>Daily +/-</th><th>Cumv +/-</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php for ($day = 1; $day <= $days_in_month; $day++):
                        $date_str = sprintf('%04d-%02d-%02d', $year, $month, $day);
                        $day_name = date('l', strtotime($date_str));
                        $is_wknd  = in_array($day_name, ['Saturday','Sunday']);
                        $dt       = str_pad($day,2,'0',STR_PAD_LEFT).'-'.date('M', strtotime($date_str));
                        $p        = $prod_data[$day] ?? null;
                        $snap     = $p ? floatval($p['fg'])           : 0;
                        $diff     = $p ? floatval($p['fg_difference']) : 0;
                        if (!$is_wknd) { $cumv_target += $FG_DAILY_TARGET; }
                        $cumv_diff += $diff;
                    ?>
                        <tr class="<?= $is_wknd ? 'weekend' : '' ?>">
                            <td class="date-col"><?= $dt ?></td>
                            <td><?= $day_name ?></td>
                            <td><?= $is_wknd ? '<span class="no-data">-</span>' : '£&nbsp;'.number_format($FG_DAILY_TARGET,2) ?></td>
                            <td>£&nbsp;<?= number_format($cumv_target, 2) ?></td>
                            <td><?= $snap > 0 ? '£&nbsp;'.number_format($snap,2) : '<span class="no-data">-</span>' ?></td>
                            <td><?php if ($diff != 0):
                                    $cls=$diff>0?'positive':'negative'; $sgn=$diff>0?'':'-';
                                    echo '<span class="'.$cls.'">£&nbsp;'.$sgn.number_format(abs($diff),2).'</span>';
                                else: echo '<span class="no-data">-</span>'; endif; ?></td>
                            <td><?php if ($cumv_diff != 0):
                                    $cls=$cumv_diff>0?'positive':'negative'; $sgn=$cumv_diff>0?'':'-';
                                    echo '<span class="'.$cls.'">£&nbsp;'.$sgn.number_format(abs($cumv_diff),2).'</span>';
                                else: echo '<span class="no-data">-</span>'; endif; ?></td>
                        </tr>
                    <?php endfor; ?>
                    </tbody>
                </table>
                </div>
            </div>
            </div><!-- /tab-fg -->


            <!-- ══════════════════════════════════════════
                 TAB 4 – WIP
            ══════════════════════════════════════════ -->
            <div class="tab-pane fade <?= $pane_active[4] ?>" id="tab-wip">
            <div class="rpt-wrap">
                <h2>WIP Report – <?= strtoupper($month_name) ?></h2>
                <?php $prev_total = 0; ?>
                <div class="table-responsive">
                <table class="th-blue">
                    <thead>
                        <tr><th>Date</th><th>Day</th><th>Daily Snapshot</th><th>Daily +/-</th></tr>
                    </thead>
                    <tbody>
                    <?php for ($day = 1; $day <= $days_in_month; $day++):
                        $date_str = sprintf('%04d-%02d-%02d', $year, $month, $day);
                        $day_name = date('l', strtotime($date_str));
                        $is_wknd  = in_array($day_name, ['Saturday','Sunday']);
                        $dt       = str_pad($day,2,'0',STR_PAD_LEFT).'-'.date('M', strtotime($date_str));
                        $p        = $prod_data[$day] ?? null;
                        $vac      = $p ? floatval($p['vac_wip']) : 0;
                        $cnc      = $p ? floatval($p['cnc_wip']) : 0;
                        $pu       = $p ? floatval($p['pu_wip'])  : 0;
                        $snap     = $vac + $cnc + $pu;
                        $diff     = ($snap > 0 && $prev_total > 0) ? $snap - $prev_total : 0;
                        if ($snap > 0) { $prev_total = $snap; }
                    ?>
                        <tr class="<?= $is_wknd ? 'weekend' : '' ?>">
                            <td class="date-col"><?= $dt ?></td>
                            <td><?= $day_name ?></td>
                            <td><?= $snap > 0 ? '£&nbsp;'.number_format($snap,2) : '<span class="no-data">-</span>' ?></td>
                            <td><?php if ($diff != 0):
                                    $cls=$diff>0?'positive':'negative'; $sgn=$diff>0?'':'-';
                                    echo '<span class="'.$cls.'">£&nbsp;'.$sgn.number_format(abs($diff),2).'</span>';
                                else: echo '<span class="no-data">-</span>'; endif; ?></td>
                        </tr>
                    <?php endfor; ?>
                    </tbody>
                </table>
                </div>
            </div>
            </div><!-- /tab-wip -->


            <!-- ══════════════════════════════════════════
                 TAB 5 – STD HOURS
            ══════════════════════════════════════════ -->
            <div class="tab-pane fade <?= $pane_active[5] ?>" id="tab-std">
            <div class="rpt-wrap">
                <h2>STD Hours Report – <?= strtoupper($month_name) ?></h2>
                <?php $cumv_target = 0; $cumv_actual = 0; ?>
                <div class="table-responsive">
                <table class="th-blue">
                    <thead>
                        <tr>
                            <th>Date</th><th>Daily Target</th><th>Cumv Target</th>
                            <th>Daily Actual</th><th>Cumv Actual</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php for ($day = 1; $day <= $days_in_month; $day++):
                        $date_str = sprintf('%04d-%02d-%02d', $year, $month, $day);
                        $day_name = date('l', strtotime($date_str));
                        $is_wknd  = in_array($day_name, ['Saturday','Sunday']);
                        $dt       = str_pad($day,2,'0',STR_PAD_LEFT).'-'.date('M', strtotime($date_str));
                        $p        = $prod_data[$day] ?? null;
                        $daily_act = $p ? floatval($p['std_hours_vac']) + floatval($p['std_hours_cnc'])
                                        + floatval($p['std_hours_pu'])  + floatval($p['std_hours_assbly']) : 0;
                        if (!$is_wknd)      { $cumv_target += $STD_HOURS_TARGET; }
                        if ($daily_act > 0) { $cumv_actual += $daily_act; }
                    ?>
                        <tr class="<?= $is_wknd ? 'weekend' : '' ?>">
                            <td class="date-col"><?= $dt ?></td>
                            <td class="target-col"><?= $is_wknd ? '0.0' : fmt_num($STD_HOURS_TARGET) ?></td>
                            <td class="target-col"><?= fmt_num($cumv_target) ?></td>
                            <td class="actual-col"><?= fmt_num($daily_act) ?></td>
                            <td class="actual-col"><?= fmt_num($cumv_actual) ?></td>
                        </tr>
                    <?php endfor; ?>
                    </tbody>
                </table>
                </div>
            </div>
            </div><!-- /tab-std -->


            <!-- ══════════════════════════════════════════
                 TAB 6 – CLOCK HOURS
            ══════════════════════════════════════════ -->
            <div class="tab-pane fade <?= $pane_active[6] ?>" id="tab-clock">
            <div class="rpt-wrap">
                <h2>Clock Hours Report – <?= strtoupper($month_name) ?></h2>
                <?php $cumv_target = 0; $cumv_actual = 0; ?>
                <div class="table-responsive">
                <table class="th-blue">
                    <thead>
                        <tr>
                            <th>Date</th><th>Daily Target</th><th>Cumv Target</th>
                            <th>Daily Actual</th><th>Cumv Actual</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php for ($day = 1; $day <= $days_in_month; $day++):
                        $date_str = sprintf('%04d-%02d-%02d', $year, $month, $day);
                        $day_name = date('l', strtotime($date_str));
                        $is_wknd  = in_array($day_name, ['Saturday','Sunday','Friday']);
                        $dt       = str_pad($day,2,'0',STR_PAD_LEFT).'-'.date('M', strtotime($date_str));
                        $p        = $prod_data[$day] ?? null;
                        $daily_act = $p ? floatval($p['clock_hours_vac'])
                                        + floatval($p['clock_hours_cnc'])
                                        + floatval($p['clock_hours_pu']) : 0;
                        if (!$is_wknd)      { $cumv_target += $CLOCK_HOURS_TARGET; }
                        if ($daily_act > 0) { $cumv_actual += $daily_act; }
                    ?>
                        <tr class="<?= $is_wknd ? 'weekend' : '' ?>">
                            <td class="date-col"><?= $dt ?></td>
                            <td class="target-col"><?= $is_wknd ? '0.0' : fmt_num($CLOCK_HOURS_TARGET) ?></td>
                            <td class="target-col"><?= fmt_num($cumv_target) ?></td>
                            <td class="actual-col"><?= $daily_act > 0 ? number_format($daily_act,0) : '0' ?></td>
                            <td class="actual-col"><?= number_format($cumv_actual,0) ?></td>
                        </tr>
                    <?php endfor; ?>
                    </tbody>
                </table>
                </div>
            </div>
            </div><!-- /tab-clock -->

            </div><!-- /.tab-content -->
            </div><!-- /.card-body -->
        </div><!-- /.card -->
    </div><!-- /.col -->
</div><!-- /.container-fluid -->
</section>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php if ($red > 0):
    $tab_ids = ['tab-inputs','tab-prodtot','tab-sales','tab-fg','tab-wip','tab-std','tab-clock'];
    $target  = $tab_ids[$red] ?? 'tab-inputs';
?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var el = document.querySelector('#dpTab a[href="#<?= $target ?>"]');
    if (el) { new bootstrap.Tab(el).show(); }
});
</script>
<?php endif; ?>
</body>
</html>