<?php
// breakdown_report.php
?>
<div class="container-fluid" style="background-color:#f4f6f9; min-height:100vh; padding:20px;">

<style>
.bd-page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #ffffff;
    border-radius: 6px;
    padding: 16px 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    margin-bottom: 18px;
}
.bd-page-header h3 { margin:0; font-size:1.25rem; font-weight:700; color:#2c3e50; }
.bd-page-header .subtitle { font-size:0.82rem; color:#7f8c8d; margin-top:2px; }

.bd-summary-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    flex-wrap: wrap;
    gap: 10px;
}
.bd-summary-bar h5 { margin:0; font-size:0.95rem; font-weight:700; color:#2c3e50; }
.bd-summary-month { display:flex; align-items:center; gap:6px; }
.bd-summary-month input[type="month"] { font-size:0.85rem; padding:5px 10px; border:1px solid #dee2e6; border-radius:4px; height:34px; }
.bd-summary-month button { height:34px; width:34px; border:1px solid #dee2e6; background:#ffffff; border-radius:4px; cursor:pointer; color:#2c3e50; }
.bd-summary-month button:hover { background:#f0f7ff; }

.bd-summary-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 12px;
    margin-bottom: 18px;
}
.bd-summary-card {
    background:#ffffff;
    border-radius:6px;
    box-shadow:0 2px 8px rgba(0,0,0,0.08);
    padding:14px 16px;
    border-left:4px solid #bdc3c7;
    position:relative;
}
.bd-summary-card.vac    { border-left-color:#1abc9c; }
.bd-summary-card.assm   { border-left-color:#f39c12; }
.bd-summary-card.cnc    { border-left-color:#3498db; }
.bd-summary-card.pu     { border-left-color:#9b59b6; }
.bd-summary-card.assypu { border-left-color:#e74c3c; }
.bd-summary-card.rw     { border-left-color:#9c4893; }
.bd-summary-card .card-type { font-size:0.75rem; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#7f8c8d; }
.bd-summary-card .card-total { font-size:1.5rem; font-weight:800; color:#2c3e50; margin-top:4px; line-height:1.1; }
.bd-summary-card .card-meta { font-size:0.75rem; color:#95a5a6; margin-top:4px; }
.bd-summary-card .card-meta .ongoing-flag { color:#f39c12; font-weight:600; }
.bd-summary-card.is-loading .card-total { color:#c8ced3; }

.bd-filters {
    background: #ffffff;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    padding: 14px 18px;
    margin-bottom: 18px;
}
.bd-filters .filter-row { display:flex; flex-wrap:wrap; gap:10px; align-items:flex-end; }
.bd-filters .filter-group { display:flex; flex-direction:column; gap:4px; flex:1; min-width:140px; }
.bd-filters label { font-size:0.75rem; font-weight:600; color:#7f8c8d; text-transform:uppercase; letter-spacing:.4px; }
.bd-filters .form-control,
.bd-filters .form-select { font-size:0.85rem; padding:6px 10px; border:1px solid #dee2e6; border-radius:4px; height:34px; }
.bd-filters .btn { height:34px; padding:0 16px; font-size:0.85rem; border-radius:4px; font-weight:600; display:flex; align-items:center; gap:6px; }

.bd-table-card { background:#ffffff; border-radius:6px; box-shadow:0 2px 8px rgba(0,0,0,0.08); overflow:hidden; }
.bd-table-toolbar { padding:12px 18px; border-bottom:1px solid #dee2e6; display:flex; align-items:center; justify-content:space-between; }
.bd-table-toolbar .result-count { font-size:0.82rem; color:#7f8c8d; }
.bd-table-wrap { overflow-x:auto; }

table.bd-table { width:100%; border-collapse:collapse; font-size:0.84rem; }
table.bd-table thead th { background:#f8f9fa; color:#2c3e50; font-weight:700; padding:10px 14px; border-bottom:2px solid #dee2e6; white-space:nowrap; font-size:0.78rem; text-transform:uppercase; letter-spacing:.4px; }
table.bd-table tbody tr { border-bottom:1px solid #f0f0f0; transition:background .15s; }
table.bd-table tbody tr:hover { background:#f0f7ff; }
table.bd-table tbody td { padding:9px 14px; vertical-align:middle; color:#333333; }
table.bd-table tbody td.no-data { text-align:center; color:#7f8c8d; font-style:italic; padding:40px; }

.machine-type-pill { display:inline-block; padding:2px 8px; border-radius:4px; font-size:0.72rem; font-weight:700; background:#eaf3fb; color:#3498db; }
.machine-type-pill.vac    { background:#e8f8f5; color:#1abc9c; }
.machine-type-pill.assm   { background:#fef9e7; color:#f39c12; }
.machine-type-pill.cnc    { background:#eaf3fb; color:#3498db; }
.machine-type-pill.pu     { background:#f5eef8; color:#9b59b6; }
.machine-type-pill.assypu { background:#fdecea; color:#e74c3c; }
.machine-type-pill.rw     { background:#f5eef8; color:#9c4893; }

.bd-pagination { display:flex; align-items:center; justify-content:space-between; padding:12px 18px; border-top:1px solid #dee2e6; flex-wrap:wrap; gap:8px; }
.bd-pagination .page-info { font-size:0.82rem; color:#7f8c8d; }
.bd-pagination .page-btns { display:flex; gap:4px; }
.bd-pagination .page-btns button { min-width:32px; height:32px; padding:0 8px; border:1px solid #dee2e6; background:#ffffff; border-radius:4px; font-size:0.82rem; cursor:pointer; color:#2c3e50; font-weight:500; transition:all .15s; }
.bd-pagination .page-btns button:hover:not(:disabled) { background:#3498db; color:#ffffff; border-color:#3498db; }
.bd-pagination .page-btns button.active { background:#3498db; color:#ffffff; border-color:#3498db; }
.bd-pagination .page-btns button:disabled { opacity:0.4; cursor:not-allowed; }
.bd-loading { text-align:center; padding:50px; color:#7f8c8d; }
</style>

<div class="bd-page-header">
    <div>
        <h3><i class="fas fa-tools me-2"></i>Machine Breakdown Report</h3>
        <div class="subtitle"><?php echo date('l, F j, Y'); ?></div>
    </div>
</div>

<div class="bd-summary-bar">
    <h5><i class="fas fa-chart-pie me-1"></i>Downtime by Machine Type</h5>
    <div class="bd-summary-month">
        <button type="button" id="bd-summary-prev" title="Previous month"><i class="fas fa-chevron-left"></i></button>
        <input type="month" id="bd-summary-month-input">
        <button type="button" id="bd-summary-next" title="Next month"><i class="fas fa-chevron-right"></i></button>
    </div>
</div>
<div class="bd-summary-cards" id="bd-summary-cards">
    <!-- Cards injected by JS -->
</div>

<div class="bd-filters">
    <div class="filter-row">
        <div class="filter-group" style="min-width:160px;">
            <label>Machine Type</label>
            <select class="form-select" id="filter-machine-type" onchange="onMachineTypeChange()">
                <option value="">All Types</option>
                <option value="1">VAC</option>
                <option value="2">ASSM</option>
                <option value="3">CNC</option>
                <option value="4">PU</option>
                <option value="5">ASSYPU</option>
                <option value="6">Replica Wood</option>
            </select>
        </div>
        <div class="filter-group" style="min-width:180px;">
            <label id="filter-machine-label">Machine</label>
            <select class="form-select" id="filter-machine">
                <option value="">All Machines</option>
            </select>
        </div>
        <div class="filter-group" style="min-width:140px;">
            <label>Date From</label>
            <input type="date" class="form-control" id="filter-date-from">
        </div>
        <div class="filter-group" style="min-width:140px;">
            <label>Date To</label>
            <input type="date" class="form-control" id="filter-date-to">
        </div>
        <div style="display:flex; gap:6px; align-items:flex-end;">
            <button class="btn btn-primary" onclick="applyBdFilters()"><i class="fas fa-search"></i> Search</button>
            <button class="btn btn-outline-secondary" onclick="resetBdFilters()"><i class="fas fa-undo"></i> Reset</button>
        </div>
    </div>
</div>

<div class="bd-table-card">
    <div class="bd-table-toolbar">
        <span class="result-count" id="bd-result-count">Loading…</span>
        <span style="font-size:0.8rem; color:#7f8c8d;">20 per page</span>
    </div>
    <div class="bd-table-wrap">
        <table class="bd-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Date &amp; Time</th>
                    <th>Machine Type</th>
                    <th>Machine</th>
                    <th>Engineer</th>
                    <th>Breakdown Reason</th>
                    <th class="hide">Logged Duration</th>
                    <th>Actual Duration</th>
                </tr>
            </thead>
            <tbody id="bd-table-body">
                <tr><td class="no-data" colspan="8">
                    <div class="bd-loading">
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="mt-2">Loading breakdown data…</p>
                    </div>
                </td></tr>
            </tbody>
        </table>
    </div>
    <div class="bd-pagination" id="bd-pagination" style="display:none;">
        <div class="page-info" id="bd-page-info"></div>
        <div class="page-btns" id="bd-page-btns"></div>
    </div>
</div>

<script>
let bdCurrentPage = 1;
let bdTotalPages  = 1;
let bdTotalRows   = 0;

// 6: 'rw' must stay lowercase/single-word — it's reused directly as a CSS
// class name below (bd-summary-card rw / machine-type-pill rw).
const MACHINE_TYPE_KEYS = { 1: 'vac', 2: 'assm', 3: 'cnc', 4: 'pu', 5: 'assypu', 6: 'rw' };

$(document).ready(function () {
    // Default the month picker to the current month
    const now = new Date();
    const defaultMonth = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
    $('#bd-summary-month-input').val(defaultMonth);

    loadMachineDropdown();
    loadBreakdownReport(1);
    loadBreakdownSummary(defaultMonth);

    $('#bd-summary-month-input').on('change', function () {
        loadBreakdownSummary($(this).val());
    });
    $('#bd-summary-prev').on('click', function () { shiftSummaryMonth(-1); });
    $('#bd-summary-next').on('click', function () { shiftSummaryMonth(1); });
});

function shiftSummaryMonth(delta) {
    const val = $('#bd-summary-month-input').val();
    if (!val) return;
    const [y, m] = val.split('-').map(Number);
    const d = new Date(y, m - 1 + delta, 1);
    const newVal = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0');
    $('#bd-summary-month-input').val(newVal);
    loadBreakdownSummary(newVal);
}

function loadBreakdownSummary(month) {
    $('#bd-summary-cards').addClass('is-loading');
    $.ajax({
        url: site_url + '/modules/machine_breakdown/index.php?page=ajax_actions&action=get_breakdown_summary',
        method: 'GET',
        data: { month: month },
        dataType: 'json',
        success: function (res) {
            if (!res.success) {
                $('#bd-summary-cards').html(`<div style="color:#7f8c8d; font-size:0.85rem;">${res.message || 'Failed to load summary.'}</div>`);
                return;
            }
            renderSummaryCards(res.data);
        },
        error: function () {
            $('#bd-summary-cards').html(`<div style="color:#e74c3c; font-size:0.85rem;">Failed to load monthly summary.</div>`);
        }
    });
}

function renderSummaryCards(rows) {
    let html = '';
    rows.forEach(function (r) {
        const typeKey = MACHINE_TYPE_KEYS[r.machine_type_id] || '';
        const ongoingBadge = r.ongoing_count > 0
            ? `<span class="ongoing-flag">${r.ongoing_count} ongoing</span>`
            : '';
        html += `
        <div class="bd-summary-card ${typeKey}">
            <div class="card-type">${escHtml(r.machine_type_label)}</div>
            <div class="card-total">${escHtml(r.total_formatted)}</div>
            <div class="card-meta">${r.breakdown_count} breakdown${r.breakdown_count === 1 ? '' : 's'} ${ongoingBadge}</div>
        </div>`;
    });
    $('#bd-summary-cards').removeClass('is-loading').html(html);
}

function loadMachineDropdown() {
    const typeId = $('#filter-machine-type').val();
    // Replica Wood's "machines" are actually Lines/Colours — relabel the
    // filter so it doesn't say "Machine" for something that isn't one.
    $('#filter-machine-label').text(typeId === '6' ? 'Line' : 'Machine');

    $.ajax({
        url: site_url + '/modules/machine_breakdown/index.php?page=ajax_actions&action=get_breakdown_machines',
        method: 'GET',
        data: { machine_type: typeId },
        dataType: 'json',
        success: function (res) {
            const $sel = $('#filter-machine');
            const prev = $sel.val();
            $sel.empty().append(`<option value="">All ${typeId === '6' ? 'Lines' : 'Machines'}</option>`);
            if (res.success) {
                res.data.forEach(function (m) {
                    $sel.append(`<option value="${m.id}">${m.resource_code}</option>`);
                });
            }
            $sel.val(prev);
        }
    });
}

function onMachineTypeChange() {
    loadMachineDropdown();
    loadBreakdownReport(1);
}

function loadBreakdownReport(page) {
    bdCurrentPage = page;
    $('#bd-table-body').html(`
        <tr><td class="no-data" colspan="8">
            <div class="bd-loading">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2">Loading…</p>
            </div>
        </td></tr>`);
    $('#bd-result-count').text('Loading…');
    $('#bd-pagination').hide();

    $.ajax({
        url: site_url + '/modules/machine_breakdown/index.php?page=ajax_actions&action=get_breakdown_report',
        method: 'GET',
        data: {
            pg:           page,
            machine_type: $('#filter-machine-type').val(),
            machine_id:   $('#filter-machine').val(),
            date_from:    $('#filter-date-from').val(),
            date_to:      $('#filter-date-to').val()
        },
        dataType: 'json',
        success: function (res) {
            if (!res.success) {
                $('#bd-table-body').html(`<tr><td class="no-data" colspan="8">${res.message || 'Failed to load data.'}</td></tr>`);
                return;
            }
            bdTotalPages = res.pages;
            bdTotalRows  = res.total;
            renderTable(res.data, page, res.per_page);
            renderPagination(page, res.pages, res.total, res.per_page);
        },
        error: function (xhr) {
            $('#bd-table-body').html(`<tr><td class="no-data" colspan="8">Error: ${xhr.responseText.substring(0,300)}</td></tr>`);
        }
    });
}

function renderTable(rows, page, perPage) {
    $('#bd-result-count').text(
        bdTotalRows === 0
            ? 'No results found'
            : `Showing ${((page-1)*perPage)+1}–${Math.min(page*perPage, bdTotalRows)} of ${bdTotalRows} breakdowns`
    );

    if (!rows.length) {
        $('#bd-table-body').html(`<tr><td class="no-data" colspan="8"><i class="fas fa-search me-2" style="opacity:.4;"></i>No breakdowns found.</td></tr>`);
        return;
    }

    let html = '';
    rows.forEach(function (r, idx) {
        const rowNum      = ((page-1)*perPage) + idx + 1;
        const typeKey     = (r.machine_type_label || '').toLowerCase();
        const machineType = r.machine_type_label || '—';
        const machineName = r.machine_name       || `Machine #${r.machine_id}`;
        const reason      = r.reason_text        || (r.breakdown_reason ? `Reason #${r.breakdown_reason}` : '—');
        const engineer    = r.engineer_name      || '—';
        const isOngoing   = String(r.is_ongoing) === '1';

        html += `
        <tr>
            <td style="color:#7f8c8d;font-size:0.78rem;">${rowNum}</td>
            <td style="font-weight:600;font-size:0.84rem;">${escHtml(r.created_at_formatted)}</td>
            <td><span class="machine-type-pill ${escHtml(typeKey)}">${escHtml(machineType)}</span></td>
            <td style="font-weight:600;">${escHtml(machineName)}</td>
            <td>${escHtml(engineer)}</td>
            <td>${escHtml(reason)}</td>
            <td class="hide" style="font-weight:600;">${escHtml(r.duration_formatted)}</td>
            <td style="font-weight:600;${isOngoing ? 'color:#f39c12;' : ''}">${escHtml(r.actual_duration_formatted)}</td>
        </tr>`;
    });

    $('#bd-table-body').html(html);
}

function renderPagination(page, totalPages, totalRows, perPage) {
    if (totalPages <= 1) { $('#bd-pagination').hide(); return; }
    $('#bd-pagination').show();
    $('#bd-page-info').text(`Page ${page} of ${totalPages} (${totalRows} records)`);

    let btns = `<button onclick="loadBreakdownReport(${page-1})" ${page===1?'disabled':''}>&#8249;</button>`;
    const sp = Math.max(1, page-2);
    const ep = Math.min(totalPages, page+2);
    if (sp > 1) { btns += `<button onclick="loadBreakdownReport(1)">1</button>`; if (sp>2) btns += `<button disabled>…</button>`; }
    for (let p = sp; p <= ep; p++) btns += `<button class="${p===page?'active':''}" onclick="loadBreakdownReport(${p})">${p}</button>`;
    if (ep < totalPages) { if (ep<totalPages-1) btns += `<button disabled>…</button>`; btns += `<button onclick="loadBreakdownReport(${totalPages})">${totalPages}</button>`; }
    btns += `<button onclick="loadBreakdownReport(${page+1})" ${page===totalPages?'disabled':''}>&#8250;</button>`;
    $('#bd-page-btns').html(btns);
}

function applyBdFilters() { loadBreakdownReport(1); }
function resetBdFilters() {
    $('#filter-machine-type, #filter-machine').val('');
    $('#filter-date-from, #filter-date-to').val('');
    loadMachineDropdown();
    loadBreakdownReport(1);
}

function escHtml(str) {
    if (str === null || str === undefined) return '—';
    return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>
</div>