<?php
// includes/master/system_totals_details.php

$tenant = urldecode($_REQUEST['tenant'] ?? '') ?: null;

// Include config.php based on tenant if available
if ($tenant) {
    if (file_exists('../../../' . $tenant . '/config.php')) {
        require_once('../../../' . $tenant . '/config.php');
    } elseif (file_exists('/config.php')) {
        require_once('/config.php');
    }
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($con) || !$con instanceof mysqli || $con->connect_error) {
    echo '<div class="alert alert-danger">Database connection error.</div>';
    exit;
}

$detailType      = $_GET['detail_type']       ?? '';
$clientId        = $_GET['client_id']         ?? 'all';
$reportStartDate = $_GET['report_start_date'] ?? '';
$reportEndDate   = $_GET['report_end_date']   ?? '';

$detailType      = $con->real_escape_string($detailType);
$clientId        = $con->real_escape_string($clientId);
$reportStartDate = $reportStartDate ? $con->real_escape_string($reportStartDate) : '';
$reportEndDate   = $reportEndDate   ? $con->real_escape_string($reportEndDate)   : '';

$startUnix = null;
$endUnix   = null;

if ($reportStartDate && $reportEndDate) {
    $tmpStart = strtotime($reportStartDate . ' 00:00:00');
    $tmpEnd   = strtotime($reportEndDate   . ' 23:59:59');
    if ($tmpStart !== false && $tmpEnd !== false) {
        $startUnix = $tmpStart;
        $endUnix   = $tmpEnd;
    }
}

// Client label for header
$clientLabel = 'All clients (global)';
if ($clientId !== 'all') {
    $stmt = $con->prepare("SELECT clientname FROM clientdetails WHERE clientnumber = ? LIMIT 1");
    $stmt->bind_param('s', $clientId);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        $clientLabel = $row['clientname'];
    } else {
        $clientLabel = 'Client ' . htmlspecialchars($clientId);
    }
    $stmt->close();
}

// Date label
$dateLabel = 'This period';
if ($reportStartDate && $reportEndDate) {
    $dateLabel = $reportStartDate . ' to ' . $reportEndDate;
} elseif ($reportStartDate || $reportEndDate) {
    $dateLabel = $reportStartDate ?: $reportEndDate;
}

$isGlobal = ($clientId === 'all');

$dataRows = [];
$title    = '';

/**
 * Decide a single status result for a report/job based on combined results string
 * and return [result, badge_html].
 */
function buildResultBadgeFromResults(?string $resultsCsv): array
{
    $resultsCsv = (string)$resultsCsv;
    $results    = array_filter(array_map('trim', explode(',', $resultsCsv)));

    // Severity ordering: lowest to highest
    $severityOrder = [
        ''        => 0,
        'PNA'     => 1,
        'PASS'    => 2,
        'OBS'     => 3,
        'DEFECTS' => 4,
        'URGENT'  => 5,
    ];

    $chosen = '';
    $max    = 0;

    foreach ($results as $r) {
        $rUpper = strtoupper($r);
        $weight = $severityOrder[$rUpper] ?? 0;
        if ($weight > $max) {
            $max    = $weight;
            $chosen = $rUpper;
        }
    }

    if ($chosen === '' && !empty($results)) {
        $chosen = strtoupper($results[0]);
    }

    $col         = 'secondary-color';
    $tag         = 'P2UD';
    $resultTitle = 'NULL';

    if ($chosen === 'DEFECTS') {
        $col = 'warning-color-dark';
        $tag = 'DEFECTS';
        $resultTitle = 'DEFECTS';
    } elseif ($chosen === 'URGENT') {
        $col = 'danger-color-dark';
        $tag = 'URGENT';
        $resultTitle = 'URGENT';
    } elseif ($chosen === 'PASS') {
        $col = 'success-color-dark';
        $tag = 'PASS';
        $resultTitle = 'PASS';
    } elseif ($chosen === 'OBS') {
        $col = 'special-color';
        $tag = 'OBS';
        $resultTitle = 'OBS';
    } elseif ($chosen === 'PNA') {
        $col = 'stylish-color-dark';
        $tag = 'PNA';
        $resultTitle = 'PNA';
    }

    $badgeHtml = sprintf(
        '<span class="badge %s" ' .
        'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" ' .
        'title="%s">%s</span>',
        htmlspecialchars($col, ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($resultTitle, ENT_QUOTES, 'UTF-8'),
        htmlspecialchars($tag, ENT_QUOTES, 'UTF-8')
    );

    return [$chosen, $badgeHtml];
}

switch ($detailType) {
    case 'items_due':
        $title = 'Items due this period';
        if ($startUnix !== null && $endUnix !== null) {
            if ($isGlobal) {
                $sql = "
                    SELECT
                        FROM_UNIXTIME(i.duedate, '%d-%m-%Y') AS duedate,
                        c.clientname,
                        c.clientnumber,
                        i.itemnumber,
                        i.`desc`
                    FROM itemdetails i
                    INNER JOIN clientdetails c ON i.clientnumber = c.clientnumber
                    WHERE i.statuslive = 1
                      AND c.statuslive = 1
                      AND i.duedate BETWEEN ? AND ?
                    ORDER BY i.duedate ASC, c.clientname ASC, i.itemnumber ASC
                ";
                $stmt = $con->prepare($sql);
                $stmt->bind_param('ii', $startUnix, $endUnix);
            } else {
                $sql = "
                    SELECT
                        FROM_UNIXTIME(i.duedate, '%d-%m-%Y') AS duedate,
                        i.itemnumber,
                        i.`desc`
                    FROM itemdetails i
                    INNER JOIN clientdetails c ON i.clientnumber = c.clientnumber
                    WHERE i.statuslive = 1
                      AND c.statuslive = 1
                      AND i.duedate BETWEEN ? AND ?
                      AND i.clientnumber = ?
                    ORDER BY i.duedate ASC, i.itemnumber ASC
                ";
                $stmt = $con->prepare($sql);
                $stmt->bind_param('iis', $startUnix, $endUnix, $clientId);
            }
            $stmt->execute();
            $res = $stmt->get_result();
            while ($row = $res->fetch_assoc()) {
                $dataRows[] = $row;
            }
            $stmt->close();
        }
        break;

    case 'jobs_completed':
        $title = 'Inspections completed (period)';
        if ($startUnix !== null && $endUnix !== null) {
            if ($isGlobal) {
                $sql = "
                    SELECT 
                        r.repnumber,
                        FROM_UNIXTIME(r.insdate, '%d-%m-%Y') AS insdate,
                        c.clientname,
                        c.clientnumber,
                        COUNT(*) AS item_count,
                        GROUP_CONCAT(DISTINCT r.result) AS results,
                        MIN(i.locnumber)  AS locnumber,
                        MIN(i.itemnumber) AS itemnumber,
                        MIN(i.`desc`)     AS itemdesc
                    FROM reportitems r
                    INNER JOIN clientdetails c ON r.clientnumber = c.clientnumber
                    INNER JOIN itemdetails  i ON r.itemnumber   = i.itemnumber
                    WHERE c.statuslive = 1
                      AND i.statuslive = 1
                      AND r.insdate BETWEEN ? AND ?
                    GROUP BY r.repnumber, r.insdate, c.clientname, c.clientnumber
                    ORDER BY r.insdate DESC, c.clientname ASC, r.repnumber ASC
                ";
                $stmt = $con->prepare($sql);
                $stmt->bind_param('ii', $startUnix, $endUnix);
            } else {
                $sql = "
                    SELECT 
                        r.repnumber,
                        FROM_UNIXTIME(r.insdate, '%d-%m-%Y') AS insdate,
                        r.clientnumber,
                        COUNT(*) AS item_count,
                        GROUP_CONCAT(DISTINCT r.result) AS results,
                        MIN(i.locnumber)  AS locnumber,
                        MIN(i.itemnumber) AS itemnumber,
                        MIN(i.`desc`)     AS itemdesc
                    FROM reportitems r
                    INNER JOIN clientdetails c ON r.clientnumber = c.clientnumber
                    INNER JOIN itemdetails  i ON r.itemnumber   = i.itemnumber
                    WHERE c.statuslive = 1
                      AND i.statuslive = 1
                      AND r.insdate BETWEEN ? AND ?
                      AND r.clientnumber = ?
                    GROUP BY r.repnumber, r.insdate, r.clientnumber
                    ORDER BY r.insdate DESC, r.repnumber ASC
                ";
                $stmt = $con->prepare($sql);
                $stmt->bind_param('iis', $startUnix, $endUnix, $clientId);
            }
            $stmt->execute();
            $res = $stmt->get_result();
            while ($row = $res->fetch_assoc()) {
                $dataRows[] = $row;
            }
            $stmt->close();
        }
        break;

    default:
        echo '<div class="alert alert-warning">Invalid detail type.</div>';
        exit;
}

?>
<div id="systemTotalsDetailPrintWrapper" style="width:100%; font-family: Arial, Helvetica, sans-serif; font-size: 11pt;">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h5 class="mb-1"><?= htmlspecialchars($title) ?></h5>
            <div style="font-size:10pt;">
                <strong>Client:</strong> <?= htmlspecialchars($clientLabel) ?><br>
                <strong>Period:</strong> <?= htmlspecialchars($dateLabel) ?>
            </div>
        </div>
        <div>
            <button type="button"
                    id="btnPrintSystemTotalsDetail"
                    class="btn btn-info btn-sm"
                    data-mdb-tooltip-init
                    data-mdb-placement="top"
                    data-mdb-trigger="hover"
                    title="Print this list">
                <i class="fad fa-print me-1"></i>Print
            </button>
        </div>
    </div>

    <?php if (empty($dataRows)): ?>
    <div class="alert alert-light border">
        No records found for the selected criteria.
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-sm table-striped table-hover mb-0">
            <thead>
                <?php if ($detailType === 'jobs_completed'): ?>
                <tr>
                    <th style="white-space:nowrap;">Inspection date</th>
                    <?php if ($isGlobal): ?>
                    <th>Client</th>
                    <?php endif; ?>
                    <th>Report</th>
                    <th>Item description</th>
                    <th>Status</th>

                </tr>
                <?php elseif ($detailType === 'items_due'): ?>
                <tr>
                    <th style="white-space:nowrap;">Due date</th>
                    <?php if ($isGlobal): ?>
                    <th>Client</th>
                    <?php endif; ?>
                    <th>Item number</th>
                    <th>Description</th>
                </tr>
                <?php endif; ?>
            </thead>
            <tbody>
                <?php foreach ($dataRows as $row): ?>
                <?php if ($detailType === 'jobs_completed'): ?>
                <?php
                            [$resultCode, $badgeHtml] = buildResultBadgeFromResults($row['results'] ?? '');
                            $clientnumber = $row['clientnumber'] ?? '';
                            $locnumber    = $row['locnumber']    ?? '';
                            $itemnumber   = $row['itemnumber']   ?? '';
                            $repnumber    = $row['repnumber']    ?? '';
                            $itemdesc     = $row['itemdesc']     ?? '';
                            $dataString   = $clientnumber . '|' . $locnumber . '|' . $itemnumber;
                            $previewUrl   = 'index.php?t=includes/master&p=items.php&view=view'
                                . '&repnumber=' . urlencode($repnumber)
                                . '&data=' . htmlspecialchars($dataString, ENT_QUOTES, 'UTF-8');
                        ?>
                <tr>
                    <td><?= htmlspecialchars($row['insdate']) ?></td>
                    <?php if ($isGlobal): ?>
                    <td>
                        <?php if (!empty($clientnumber)): ?>
                        <a href="index.php?t=includes/master&amp;p=client.php&amp;clientnumber=<?= htmlspecialchars($clientnumber) ?>&amp;view=asset">
                            <?= htmlspecialchars($row['clientname']) ?>
                        </a>
                        <?php else: ?>
                        <?= htmlspecialchars($row['clientname'] ?? '') ?>
                        <?php endif; ?>
                    </td>
                    <?php endif; ?>
                    <td>
                        <a href="<?= $previewUrl ?>"
                           data-mdb-tooltip-init
                           data-mdb-placement="top"
                           data-mdb-trigger="hover"
                           title="Preview report" target="_BLANK">
                            <?= htmlspecialchars($repnumber) ?>
                        </a>
                    </td>
                    <td><?= htmlspecialchars($itemdesc) ?></td>
                    <td><?= $badgeHtml ?></td>

                </tr>
                <?php elseif ($detailType === 'items_due'): ?>
                <tr>
                    <td><?= htmlspecialchars($row['duedate']) ?></td>
                    <?php if ($isGlobal): ?>
                    <td>
                        <?php if (!empty($row['clientnumber'])): ?>
                        <a href="index.php?t=includes/master&amp;p=client.php&amp;clientnumber=<?= htmlspecialchars($row['clientnumber']) ?>&amp;view=asset">
                            <?= htmlspecialchars($row['clientname']) ?>
                        </a>
                        <?php else: ?>
                        <?= htmlspecialchars($row['clientname'] ?? '') ?>
                        <?php endif; ?>
                    </td>
                    <?php endif; ?>
                    <td><?= htmlspecialchars($row['itemnumber']) ?></td>
                    <td><?= htmlspecialchars($row['desc']) ?></td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<script>
(function() {
    const btn = document.getElementById('btnPrintSystemTotalsDetail');
    if (!btn) return;

    if (typeof printContainer !== 'function') {
        btn.addEventListener('click', function() {
            console.error('printContainer is not defined. Ensure jsprint.js is loaded.');
        });
        return;
    }

    btn.addEventListener('click', function() {
        const headerHtml = '<div style="width:100%; text-align:left; font-size:14px;"><strong><?= addslashes($title) ?></strong></div>';
        const footerHtml = '<div style="width:100%; text-align:center; font-size:10px;">Generated ' +
            new Date().toLocaleString() + '</div>';

        printContainer('systemTotalsDetailPrintWrapper', {
            orientation: 'portrait',
            margin: 10,
            header: headerHtml,
            footer: footerHtml,
            styles: [
                ROOT_URL + '/resources/mdb/css/mdb.min.css',
                ROOT_URL + '/resources/mdb/plugins/css/all.min.css'
            ]
        });
    });
})();
</script>