<?php
session_start();

/* ─────────────────────────────────────────────
   COMMON FILTER
───────────────────────────────────────────── */
$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"));

/* ─────────────────────────────────────────────
   ACTIVE TAB
   FIX: was $_REQUEST (GET/POST/COOKIE) and unvalidated. Only two tabs
   exist (0, 1); an out-of-range value meant neither nav-link nor
   tab-pane got the active/show class, so the page rendered with no
   visible tab at all — same class of bug fixed in the sibling reports.
───────────────────────────────────────────── */
$red = isset($_GET['red']) ? intval($_GET['red']) : 0;
if ($red !== 1) { $red = 0; }

/* ─────────────────────────────────────────────
   SQL – TAB 0: monthly summary totals
───────────────────────────────────────────── */
$summary_sql = "
    SELECT
        SUM(std_hours_vac)    AS total_std_vac,
        SUM(std_hours_cnc)    AS total_std_cnc,
        SUM(std_hours_assbly) AS total_std_assbly,
        SUM(std_hours_pu)     AS total_std_pu,
        SUM(clock_hours_vac)  AS total_clock_vac,
        SUM(clock_hours_cnc)  AS total_clock_cnc,
        SUM(clock_hours_assbly) AS total_clock_assbly,
        SUM(clock_hours_pu)   AS total_clock_pu
    FROM daily_production_summary
    WHERE MONTH(record_date) = $month AND YEAR(record_date) = $year
";
$summary_result = mysqli_query($conn, $summary_sql);
$summary        = mysqli_fetch_assoc($summary_result);

$std_vac    = floatval($summary['total_std_vac']);
$std_cnc    = floatval($summary['total_std_cnc']);
$std_assbly = floatval($summary['total_std_assbly']);
$std_pu     = floatval($summary['total_std_pu']);

$clock_vac    = floatval($summary['total_clock_vac']);
$clock_cnc    = floatval($summary['total_clock_cnc']);
$clock_assbly = floatval($summary['total_clock_assbly']);
$clock_pu     = floatval($summary['total_clock_pu']);

/* Per-department productivity — legitimate to include Assembly's own
   clock hours here, since this is ASSY's own row, not the org total. */
$prod_vac    = $clock_vac    > 0 ? ($std_vac    / $clock_vac)    * 100 : 0;
$prod_cnc    = $clock_cnc    > 0 ? ($std_cnc    / $clock_cnc)    * 100 : 0;
$prod_assbly = $clock_assbly > 0 ? ($std_assbly / $clock_assbly) * 100 : 0;
$prod_pu     = $clock_pu     > 0 ? ($std_pu     / $clock_pu)     * 100 : 0;

/* ── TOTAL row ──
   FIX: total_clock previously summed clock_vac + clock_cnc +
   clock_assbly + clock_pu. Every other report in the app (FG
   Movement, Daily Progress) computes company-wide Labour
   Productivity as:
       STD Actual   = vac + cnc + pu + assbly   (Assembly IN)
       Clock Actual = vac + cnc + pu            (Assembly OUT)
   That asymmetry is deliberate there (Assembly's throughput counts,
   but its clock hours aren't part of the tracked labour-productivity
   denominator). Including clock_assbly here made this page's overall
   Productivity % diverge from the Labour Productivity % shown
   elsewhere for the same month. total_std already matched the
   established formula; only total_clock needed the fix. */
$total_std   = $std_vac + $std_cnc + $std_assbly + $std_pu;
$total_clock = $clock_vac + $clock_cnc + $clock_pu; // Assembly excluded — matches company-wide formula
$total_prod  = $total_clock > 0 ? ($total_std / $total_clock) * 100 : 0;

/* ─────────────────────────────────────────────
   SQL – TAB 1: daily machine breakdown
───────────────────────────────────────────── */
$daily_sql = "
    SELECT
        DAY(record_date)        AS day,
        DAYNAME(record_date)    AS day_name,
        clock_hours_vac,  clock_hours_cnc,  clock_hours_pu,  clock_hours_assbly,
        std_hours_vac,    std_hours_cnc,    std_hours_pu,    std_hours_assbly,
        vac_wip,          cnc_wip,          pu_wip
    FROM daily_production_summary
    WHERE MONTH(record_date) = $month AND YEAR(record_date) = $year
    ORDER BY record_date ASC
";
$daily_result = mysqli_query($conn, $daily_sql);
$daily_data   = [];
while ($row = mysqli_fetch_assoc($daily_result)) {
    $daily_data[$row['day']] = $row;
}

/* ─────────────────────────────────────────────
   HELPERS
───────────────────────────────────────────── */
function isWeekend($year, $month, $day) {
    return date('N', strtotime(sprintf('%04d-%02d-%02d', $year, $month, $day))) >= 6;
}
function fmtN($v, $dec = 1) { return number_format($v, $dec); }
function prodPct($std, $clock) {
    return $clock > 0 ? number_format(($std / $clock) * 100, 0) . '%' : '0';
}

/* Section definitions for Tab 1.
   NOTE: wip_div (200) is a fixed conversion divisor with no other
   reference elsewhere in the app to validate against — left as-is
   from the original, flagging as an unexplained magic number worth
   documenting (e.g. "£/hr equivalent" or similar) if you have the
   source for it. */
$sections = [
    'VAC'   => ['std' => 'std_hours_vac',   'clock' => 'clock_hours_vac',   'wip' => 'vac_wip',  'wip_div' => 200],
    'CNC'   => ['std' => 'std_hours_cnc',   'clock' => 'clock_hours_cnc',   'wip' => 'cnc_wip',  'wip_div' => 200],
    'ASSY'  => ['std' => 'std_hours_assbly','clock' => 'clock_hours_assbly','wip' => null,        'wip_div' => 0],
    'PU ML' => ['std' => 'std_hours_pu',    'clock' => 'clock_hours_pu',    'wip' => 'pu_wip',   'wip_div' => 200],
];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View STD Hours - <?= htmlspecialchars($month_name, ENT_QUOTES) ?></title>
<!--
    FIX: same missing-includes issue as the sibling report pages —
    Bootstrap classes and a $(document).ready() jQuery/Toastify call
    with none of Bootstrap CSS, jQuery, or Toastify's CSS/JS loaded.
-->
<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; }

/* ── shared ── */
.rpt-wrap            { width:100%;padding:20px;background:#fff;box-sizing:border-box; }
.rpt-wrap h2         { color:#333;margin-bottom:16px;font-size:22px;text-align:center; }

/* ── summary table (tab 0) ── */
.tbl-summary         { width:100%;border-collapse:collapse;margin-top:16px;max-width:700px; }
.tbl-summary th, .tbl-summary td { border:1px solid #ddd;padding:10px;text-align:center;font-size:14px; }
.tbl-summary th      { background:#4472C4;color:#fff;font-weight:bold; }
.tbl-summary td:first-child { text-align:left;font-weight:bold;background:#f8f9fa; }
.tbl-summary tr:hover { background:#f0f0f0; }
.total-row td        { background:#e8f4f8!important;border-top:2px solid #333;font-weight:bold; }

/* ── machine table (tab 1) ── */
.table-responsive    { overflow-x:auto;margin-top:16px; }
.tbl-machine         { width:100%;border-collapse:collapse;min-width:2000px; }
.tbl-machine th, .tbl-machine td { border:1px solid #ddd;padding:6px 8px;text-align:center;font-size:11px; }
.tbl-machine th      { background:#4472C4;color:#fff;font-weight:bold;position:sticky;top:0;z-index:10; }
.date-hdr            { font-weight:bold;font-size:10px; }
.day-hdr             { font-size:9px;background:#f0f0f0;color:#000!important; }
.dept-label          { background:#e8f0fe;font-weight:bold;text-align:left;padding-left:10px;font-size:12px; }
.row-label           { background:#fff;text-align:left;padding-left:20px;font-size:10px; }
.weekend             { background:#e8e8e8; }
.prod-cell           { background:#fff2cc; }
.no-data             { color:#999; }
</style>
</head>
<body>

<!-- ── HEADER ── -->
<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 STD Hours</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>
    window._activeTab = '<?= $red ?>';
    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');
        window.location.href = url.toString();
    }
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('#stdTab a').forEach(function(a, i) {
            a.addEventListener('shown.bs.tab', function () { window._activeTab = String(i); });
        });
    });
    </script>

    <!-- ── TAB SHELL ── -->
    <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="stdTab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link <?= $red == 0 ? 'active' : '' ?>" data-bs-toggle="pill" href="#tab-std-summary"><b>STD HOURS</b></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?= $red == 1 ? 'active' : '' ?>" data-bs-toggle="pill" href="#tab-std-machine"><b>STD HOURS MACHINE</b></a>
                    </li>
                </ul>
            </div>

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

            <?php /* ══════════════════════════════════════════
               TAB 0 – MONTHLY PRODUCTIVITY SUMMARY
            ══════════════════════════════════════════ */ ?>
            <div class="tab-pane fade <?= $red == 0 ? 'active show' : '' ?>" id="tab-std-summary">
            <div class="rpt-wrap">
                <h2>Monthly Productivity Summary – <?= strtoupper($month_name) ?></h2>
                <table class="tbl-summary">
                    <thead>
                        <tr>
                            <th>Section</th>
                            <th>STD Hours</th>
                            <th>Clock Hours</th>
                            <th>Productivity</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $rows = [
                            'VAC'   => [$std_vac,    $clock_vac,    $prod_vac],
                            'CNC'   => [$std_cnc,    $clock_cnc,    $prod_cnc],
                            'ASSY'  => [$std_assbly, $clock_assbly, $prod_assbly],
                            'PU ML' => [$std_pu,     $clock_pu,     $prod_pu],
                        ];
                        foreach ($rows as $label => $vals): ?>
                        <tr>
                            <td><?= $label ?></td>
                            <td><?= fmtN($vals[0]) ?></td>
                            <td><?= fmtN($vals[1]) ?></td>
                            <td><?= fmtN($vals[2], 0) ?>%</td>
                        </tr>
                        <?php endforeach; ?>
                        <tr class="total-row">
                            <td>TOTAL</td>
                            <td><?= fmtN($total_std) ?></td>
                            <td><?= fmtN($total_clock) ?></td>
                            <td><?= fmtN($total_prod, 0) ?>%</td>
                        </tr>
                    </tbody>
                </table>
                <p style="font-size:11px;color:#888;max-width:700px;margin-top:8px;">
                    * Total Clock Hours excludes Assembly (matches the Labour Productivity
                    figure on the FG Movement and Daily Progress reports). Assembly's own
                    row above still shows its full clock hours for department-level detail.
                </p>
            </div>
            </div><!-- /tab-std-summary -->


            <?php /* ══════════════════════════════════════════
               TAB 1 – DAILY MACHINE PRODUCTIVITY
            ══════════════════════════════════════════ */ ?>
            <div class="tab-pane fade <?= $red == 1 ? 'active show' : '' ?>" id="tab-std-machine">
            <div class="rpt-wrap">
                <h2>Productivity Report – <?= strtoupper($month_name) ?></h2>
                <div class="table-responsive">
                <table class="tbl-machine">
                    <thead>
                        <!-- Date row -->
                        <tr>
                            <th colspan="2"></th>
                            <?php for ($d = 1; $d <= $days_in_month; $d++):
                                $ds = sprintf('%04d-%02d-%02d', $year, $month, $d);
                            ?>
                                <th class="date-hdr"><?= str_pad($d,2,'0',STR_PAD_LEFT).'-'.date('M', strtotime($ds)) ?></th>
                            <?php endfor; ?>
                        </tr>
                        <!-- Day name row -->
                        <tr>
                            <th colspan="2"></th>
                            <?php for ($d = 1; $d <= $days_in_month; $d++):
                                $ds = sprintf('%04d-%02d-%02d', $year, $month, $d);
                            ?>
                                <th class="day-hdr"><?= date('l', strtotime($ds)) ?></th>
                            <?php endfor; ?>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($sections as $sect_name => $cols):
                        $std_key   = $cols['std'];
                        $clock_key = $cols['clock'];
                        $wip_key   = $cols['wip'];
                        $wip_div   = $cols['wip_div'];
                        $has_wip   = !is_null($wip_key);
                        $has_dt    = ($sect_name === 'PU ML'); // Downtime row only for PU ML
                    ?>

                        <!-- Department header -->
                        <tr>
                            <td colspan="<?= $days_in_month + 2 ?>" class="dept-label"><?= $sect_name ?></td>
                        </tr>

                        <!-- Std Hours Req (empty placeholder) -->
                        <tr>
                            <td colspan="2" class="row-label">Std Hours Req</td>
                            <?php for ($d = 1; $d <= $days_in_month; $d++): ?>
                                <td class="<?= isWeekend($year,$month,$d) ? 'weekend' : '' ?>"></td>
                            <?php endfor; ?>
                        </tr>

                        <!-- Std Hours Actual -->
                        <tr>
                            <td colspan="2" class="row-label">Std Hours Actual</td>
                            <?php for ($d = 1; $d <= $days_in_month; $d++):
                                $wknd = isWeekend($year,$month,$d);
                                $p    = $daily_data[$d] ?? null;
                                $v    = $p ? floatval($p[$std_key]) : 0;
                            ?>
                                <td class="<?= $wknd ? 'weekend' : '' ?>"><?= fmtN($v) ?></td>
                            <?php endfor; ?>
                        </tr>

                        <!-- Clock Hours -->
                        <tr>
                            <td colspan="2" class="row-label">Clock Hours</td>
                            <?php for ($d = 1; $d <= $days_in_month; $d++):
                                $wknd = isWeekend($year,$month,$d);
                                $p    = $daily_data[$d] ?? null;
                                $v    = $p ? floatval($p[$clock_key]) : 0;
                            ?>
                                <td class="<?= $wknd ? 'weekend' : '' ?>"><?= fmtN($v) ?></td>
                            <?php endfor; ?>
                        </tr>

                        <?php if ($has_wip): ?>
                        <!-- Std Hours Stock (WIP / divisor) -->
                        <tr>
                            <td colspan="2" class="row-label">Std Hours Stock</td>
                            <?php for ($d = 1; $d <= $days_in_month; $d++):
                                $wknd = isWeekend($year,$month,$d);
                                $p    = $daily_data[$d] ?? null;
                                $wip  = $p ? floatval($p[$wip_key]) : 0;
                                $v    = $wip_div > 0 ? $wip / $wip_div : 0;
                            ?>
                                <td class="<?= $wknd ? 'weekend' : '' ?>"><?= $v > 0 ? fmtN($v, 0) : '0' ?></td>
                            <?php endfor; ?>
                        </tr>
                        <?php endif; ?>

                        <?php if ($has_dt): ?>
                        <!-- Downtime (PU ML only, empty placeholder) -->
                        <tr>
                            <td colspan="2" class="row-label">Downtime</td>
                            <?php for ($d = 1; $d <= $days_in_month; $d++): ?>
                                <td class="<?= isWeekend($year,$month,$d) ? 'weekend' : '' ?>"></td>
                            <?php endfor; ?>
                        </tr>
                        <?php endif; ?>

                        <!-- Productivity -->
                        <tr>
                            <td colspan="2" class="row-label">Productivity actual</td>
                            <?php for ($d = 1; $d <= $days_in_month; $d++):
                                $wknd  = isWeekend($year,$month,$d);
                                $p     = $daily_data[$d] ?? null;
                                $std   = $p ? floatval($p[$std_key])   : 0;
                                $clock = $p ? floatval($p[$clock_key]) : 0;
                                $cls   = $wknd ? 'weekend prod-cell' : 'prod-cell';
                            ?>
                                <td class="<?= $cls ?>"><?= prodPct($std, $clock) ?></td>
                            <?php endfor; ?>
                        </tr>

                    <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            </div>
            </div><!-- /tab-std-machine -->

            </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): ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var ids = ['tab-std-summary','tab-std-machine'];
    var el  = document.querySelector('#stdTab a[href="#' + (ids[<?= $red ?>] || ids[0]) + '"]');
    if (el) { new bootstrap.Tab(el).show(); }
});
</script>
<?php endif; ?>
</body>
</html>