Files
controls-web/reports/milldata.php
2026-02-17 12:44:37 -06:00

707 lines
21 KiB
PHP

<?php // phpcs:ignoreFile
require __DIR__ . '/../session.php';
require __DIR__ . '/../userAccess.php';
require __DIR__ . '/../includes/millnames.php';
// ============================================================================
// Database Configuration
// ============================================================================
$config = [
'server' => '192.168.0.16',
'database' => 'lasucaai',
'username' => 'lasucaai',
'password' => 'is413#dfslw',
];
// ============================================================================
// Database Connection
// ============================================================================
function getMillDataConnection($config) {
$connectionOptions = [
"Database" => $config['database'],
"Uid" => $config['username'],
"PWD" => $config['password'],
"TrustServerCertificate" => true,
"Encrypt" => false,
];
$conn = sqlsrv_connect($config['server'], $connectionOptions);
if ($conn === false) {
return null;
}
return $conn;
}
// ============================================================================
// Data Queries
// ============================================================================
function getMillReports($conn) {
$sql = "SELECT ReportId, SourceFileName, MillName, ReportTitle,
BeginningDate, EndingDate, CropDays, ProcessedAt
FROM dbo.MillDataReports
ORDER BY ProcessedAt DESC";
$stmt = sqlsrv_query($conn, $sql);
$reports = [];
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$reports[] = $row;
}
return $reports;
}
function getMillSourceFiles($conn) {
$sql = "SELECT DISTINCT SourceFileName,
MIN(BeginningDate) as BeginningDate,
MAX(EndingDate) as EndingDate,
MAX(ProcessedAt) as ProcessedAt
FROM dbo.MillDataReports
GROUP BY SourceFileName
ORDER BY MAX(ProcessedAt) DESC";
$stmt = sqlsrv_query($conn, $sql);
$files = [];
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$files[] = $row;
}
return $files;
}
function getMillsForSourceFile($conn, $sourceFileName) {
$sql = "SELECT ReportId, MillName
FROM dbo.MillDataReports
WHERE SourceFileName = ?
ORDER BY MillName";
$stmt = sqlsrv_query($conn, $sql, [$sourceFileName]);
if ($stmt === false) {
return [];
}
$mills = [];
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$mills[] = $row;
}
return $mills;
}
function getMillMetrics($conn, $reportId, $search = '', $category = '') {
$params = [$reportId];
$sql = "SELECT MetricId, ItemNumber, MetricName, RunValue, RunValueNumeric,
ToDateValue, ToDateValueNumeric, Unit, Category
FROM dbo.MillDataMetrics
WHERE ReportId = ?";
if (!empty($search)) {
$sql .= " AND MetricName LIKE ?";
$params[] = '%' . $search . '%';
}
if (!empty($category)) {
$sql .= " AND Category = ?";
$params[] = $category;
}
$sql .= " ORDER BY MetricId";
$stmt = sqlsrv_query($conn, $sql, $params);
$metrics = [];
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$metrics[] = $row;
}
return $metrics;
}
function getMillCategories($conn) {
$sql = "SELECT DISTINCT Category FROM dbo.MillDataMetrics WHERE Category IS NOT NULL ORDER BY Category";
$stmt = sqlsrv_query($conn, $sql);
$categories = [];
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$categories[] = $row['Category'];
}
return $categories;
}
function getMillReportStats($conn) {
$sql = "SELECT
COUNT(DISTINCT r.ReportId) as TotalReports,
COUNT(m.MetricId) as TotalMetrics,
MIN(r.BeginningDate) as EarliestDate,
MAX(r.EndingDate) as LatestDate
FROM dbo.MillDataReports r
LEFT JOIN dbo.MillDataMetrics m ON r.ReportId = m.ReportId";
$stmt = sqlsrv_query($conn, $sql);
return sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
}
function formatMillDate($date) {
if ($date instanceof DateTime) {
return $date->format('m/d/Y');
}
return $date ?? '-';
}
// ============================================================================
// Main Logic
// ============================================================================
$conn = getMillDataConnection($config);
$connectionError = $conn === null;
$reports = [];
$sourceFiles = [];
$millsForFile = [];
$categories = [];
$stats = ['TotalReports' => 0, 'TotalMetrics' => 0];
$metrics = [];
$selectedReport = null;
$selectedFile = '';
$selectedFileInfo = null;
$millNameLookup = [];
if (!$connectionError) {
// Load mill name mappings
$millNameLookup = getMillNames($conn);
$selectedFile = isset($_GET['file']) ? trim($_GET['file']) : '';
$selectedReportId = isset($_GET['report']) ? intval($_GET['report']) : 0;
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';
$selectedCategory = isset($_GET['category']) ? trim($_GET['category']) : '';
$reports = getMillReports($conn);
$sourceFiles = getMillSourceFiles($conn);
$categories = getMillCategories($conn);
$stats = getMillReportStats($conn);
// Default to first file if none selected
if (empty($selectedFile) && !empty($sourceFiles)) {
$selectedFile = $sourceFiles[0]['SourceFileName'];
}
// Get mills for selected file
$millsForFile = !empty($selectedFile) ? getMillsForSourceFile($conn, $selectedFile) : [];
// Default to first mill if no report selected
if ($selectedReportId === 0 && !empty($millsForFile)) {
$selectedReportId = $millsForFile[0]['ReportId'];
}
// Validate report belongs to selected file
$validReport = false;
foreach ($millsForFile as $m) {
if ($m['ReportId'] == $selectedReportId) {
$validReport = true;
break;
}
}
if (!$validReport && !empty($millsForFile)) {
$selectedReportId = $millsForFile[0]['ReportId'];
}
$metrics = $selectedReportId ? getMillMetrics($conn, $selectedReportId, $searchTerm, $selectedCategory) : [];
// Find selected report details
foreach ($reports as $r) {
if ($r['ReportId'] == $selectedReportId) {
$selectedReport = $r;
break;
}
}
// Find selected file details
foreach ($sourceFiles as $f) {
if ($f['SourceFileName'] == $selectedFile) {
$selectedFileInfo = $f;
break;
}
}
sqlsrv_close($conn);
} else {
$selectedReportId = 0;
$searchTerm = '';
$selectedCategory = '';
}
// ============================================================================
// Page Layout
// ============================================================================
$pageTitle = 'Mill Data Viewer';
$pageSubtitle = 'Sugar Mill Production Report Data';
$pageDescription = 'View extracted mill production data from daily reports.';
$layoutWithoutSidebar = true;
$layoutReturnUrl = '../overview.php';
$layoutReturnLabel = 'Back to overview';
$assetBasePath = '../';
require __DIR__ . '/../includes/layout/header.php';
?>
<style>
.milldata-stats {
display: flex;
flex-wrap: wrap;
gap: 1rem;
margin-bottom: 1.5rem;
align-items: center;
}
.milldata-stat {
background: var(--surface);
padding: 1rem;
border-radius: 8px;
text-align: center;
border: 1px solid var(--border);
min-width: 100px;
}
.milldata-stat .value {
font-size: 1.5rem;
font-weight: 600;
color: var(--accent);
}
.milldata-stat .label {
font-size: 0.8rem;
color: var(--text-muted);
}
.compare-mills-btn {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.6rem 1rem;
background: var(--accent);
color: white;
text-decoration: none;
border-radius: 6px;
font-size: 0.85rem;
font-weight: 500;
transition: background 0.2s, transform 0.1s;
margin-left: auto;
}
.compare-mills-btn:hover {
background: var(--accent-hover, #1976d2);
transform: translateY(-1px);
}
.milldata-layout {
display: grid;
grid-template-columns: 280px 1fr;
gap: 1.5rem;
}
@media (max-width: 900px) {
.milldata-layout {
grid-template-columns: 1fr;
}
}
.milldata-sidebar {
background: var(--surface);
border-radius: 8px;
padding: 1rem;
border: 1px solid var(--border);
height: fit-content;
max-height: 500px;
overflow-y: auto;
}
.milldata-sidebar h2 {
font-size: 0.85rem;
color: var(--text-muted);
margin-bottom: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.report-list {
list-style: none;
padding: 0;
margin: 0;
}
.report-list li {
margin-bottom: 0.5rem;
}
.report-list a {
display: block;
padding: 0.6rem 0.75rem;
background: var(--surface-alt);
border-radius: 6px;
text-decoration: none;
color: var(--text);
transition: all 0.2s;
border-left: 3px solid transparent;
font-size: 0.9rem;
}
.report-list a:hover {
background: var(--hover);
border-left-color: var(--accent);
}
.report-list a.active {
background: var(--hover);
border-left-color: var(--accent);
font-weight: 500;
}
.report-list .date {
font-size: 0.75rem;
color: var(--text-muted);
}
.milldata-main {
background: var(--surface);
border-radius: 8px;
padding: 1.25rem;
border: 1px solid var(--border);
}
.milldata-report-header {
margin-bottom: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--border);
}
.milldata-report-header h2 {
color: var(--accent);
margin-bottom: 0.5rem;
font-size: 1.1rem;
}
.report-meta {
display: flex;
gap: 1.25rem;
flex-wrap: wrap;
font-size: 0.85rem;
color: var(--text-muted);
}
.milldata-filters {
display: flex;
gap: 0.75rem;
margin-bottom: 1rem;
flex-wrap: wrap;
}
.milldata-filters input,
.milldata-filters select {
padding: 0.5rem 0.75rem;
border: 1px solid var(--border);
border-radius: 6px;
font-size: 0.85rem;
background: var(--surface);
color: var(--text);
}
.milldata-filters input {
flex: 1;
min-width: 180px;
}
.milldata-filters button {
padding: 0.5rem 1rem;
background: var(--accent);
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 0.85rem;
}
.milldata-filters button:hover {
opacity: 0.9;
}
.milldata-filters .clear-link {
padding: 0.5rem;
color: var(--text-muted);
text-decoration: none;
font-size: 0.85rem;
}
.results-count {
font-size: 0.8rem;
color: var(--text-muted);
margin-bottom: 0.75rem;
}
.milldata-table-wrapper {
border: 1px solid var(--border);
border-radius: 6px;
overflow: hidden;
}
.milldata-table-header {
background: var(--surface-alt);
}
.milldata-table-header table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
font-size: 0.85rem;
table-layout: fixed;
}
.milldata-table-header th {
background: var(--surface-alt);
padding: 0.75rem 0.6rem;
text-align: center;
font-weight: 600;
color: var(--text-muted);
border-bottom: 2px solid var(--border);
}
.milldata-table-header th:nth-child(1) { width: 60px; text-align: left; }
.milldata-table-header th:nth-child(2) { text-align: left; }
.milldata-table-header th:nth-child(3) { width: 100px; }
.milldata-table-header th:nth-child(4) { width: 100px; }
.milldata-table-header th:nth-child(5) { width: 120px; }
.milldata-table-container {
max-height: 450px;
overflow-y: auto;
}
.milldata-table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
font-size: 0.85rem;
table-layout: fixed;
}
.milldata-table td:nth-child(1) { width: 60px; }
.milldata-table td:nth-child(3) { width: 100px; }
.milldata-table td:nth-child(4) { width: 100px; }
.milldata-table td:nth-child(5) { width: 120px; }
.milldata-table td {
padding: 0.6rem;
border-bottom: 1px solid var(--border);
}
.milldata-table tr:hover {
background: var(--hover);
}
.item-num {
font-weight: 600;
color: var(--accent);
white-space: nowrap;
}
.metric-name {
max-width: 280px;
}
.value-cell {
text-align: right;
font-family: 'Consolas', 'Monaco', monospace;
white-space: nowrap;
}
.value-cell.negative {
color: #ef5350;
}
.category-badge {
display: inline-block;
padding: 2px 8px;
background: var(--hover);
color: var(--accent);
border-radius: 12px;
font-size: 0.7rem;
white-space: nowrap;
}
.no-data {
text-align: center;
padding: 2rem;
color: var(--text-muted);
}
.connection-error {
background: #ffebee;
color: #c62828;
padding: 1rem;
border-radius: 8px;
text-align: center;
margin-bottom: 1rem;
}
</style>
<div class="app-content">
<section class="data-panel">
<?php if ($connectionError): ?>
<div class="connection-error">
Unable to connect to the database. Please check the connection settings.
</div>
<?php endif; ?>
<div class="milldata-stats">
<div class="milldata-stat">
<div class="value"><?= $stats['TotalReports'] ?? 0 ?></div>
<div class="label">Mills</div>
</div>
<div class="milldata-stat">
<div class="value"><?= number_format($stats['TotalMetrics'] ?? 0) ?></div>
<div class="label">Metrics</div>
</div>
<div class="milldata-stat">
<div class="value"><?= formatMillDate($stats['EarliestDate'] ?? null) ?></div>
<div class="label">Earliest</div>
</div>
<div class="milldata-stat">
<div class="value"><?= formatMillDate($stats['LatestDate'] ?? null) ?></div>
<div class="label">Latest</div>
</div>
<a href="milldata-compare.php" class="compare-mills-btn">🔀 Compare Mills</a>
<a href="milldata-dashboard.php" class="compare-mills-btn" style="background: #10b981;">📊 Dashboard</a>
</div>
<div class="milldata-layout">
<aside class="milldata-sidebar">
<h2>Reports</h2>
<ul class="report-list">
<?php foreach ($sourceFiles as $file): ?>
<li>
<a href="?file=<?= urlencode($file['SourceFileName']) ?>"
class="<?= $file['SourceFileName'] == $selectedFile ? 'active' : '' ?>">
<?= htmlspecialchars($file['SourceFileName']) ?>
<div class="date">
<?= formatMillDate($file['BeginningDate']) ?> - <?= formatMillDate($file['EndingDate']) ?>
</div>
</a>
</li>
<?php endforeach; ?>
<?php if (empty($sourceFiles)): ?>
<li class="no-data">No reports found</li>
<?php endif; ?>
</ul>
</aside>
<main class="milldata-main">
<?php if ($selectedReport): ?>
<div class="milldata-report-header">
<h2><?= htmlspecialchars($selectedReport['ReportTitle'] ?? $selectedReport['SourceFileName']) ?></h2>
<div class="report-meta">
<span>📅 <?= formatMillDate($selectedReport['BeginningDate']) ?> - <?= formatMillDate($selectedReport['EndingDate']) ?></span>
<span>🏭
<select onchange="window.location.href='?file=<?= urlencode($selectedFile) ?>&report='+this.value" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--surface); color: var(--text);">
<?php foreach ($millsForFile as $mill):
$displayName = getMillDisplayName($millNameLookup, $mill['MillName']);
?>
<option value="<?= $mill['ReportId'] ?>" <?= $mill['ReportId'] == $selectedReportId ? 'selected' : '' ?>>
<?= htmlspecialchars($displayName) ?>
</option>
<?php endforeach; ?>
</select>
</span>
</div>
</div>
<form class="milldata-filters" method="get">
<input type="hidden" name="file" value="<?= htmlspecialchars($selectedFile) ?>">
<input type="hidden" name="report" value="<?= $selectedReportId ?>">
<input type="text" name="search" placeholder="Search metrics..."
value="<?= htmlspecialchars($searchTerm) ?>">
<select name="category">
<option value="">All Categories</option>
<?php foreach ($categories as $cat): ?>
<option value="<?= htmlspecialchars($cat) ?>"
<?= $cat === $selectedCategory ? 'selected' : '' ?>>
<?= htmlspecialchars($cat) ?>
</option>
<?php endforeach; ?>
</select>
<button type="submit">Filter</button>
<?php if ($searchTerm || $selectedCategory): ?>
<a href="?file=<?= urlencode($selectedFile) ?>&report=<?= $selectedReportId ?>" class="clear-link">Clear</a>
<?php endif; ?>
</form>
<div class="results-count">
Showing <?= count($metrics) ?> metrics
<?php if ($searchTerm): ?>
matching "<?= htmlspecialchars($searchTerm) ?>"
<?php endif; ?>
</div>
<div class="milldata-table-wrapper">
<div class="milldata-table-header">
<table>
<thead>
<tr>
<th>Item</th>
<th>Metric</th>
<th>RUN</th>
<th>TO DATE</th>
<th>Category</th>
</tr>
</thead>
</table>
</div>
<div class="milldata-table-container">
<table class="milldata-table">
<tbody>
<?php foreach ($metrics as $m): ?>
<tr>
<td class="item-num"><?= htmlspecialchars($m['ItemNumber'] ?? '') ?></td>
<td class="metric-name"><?= htmlspecialchars($m['MetricName'] ?? '') ?></td>
<td class="value-cell <?= ($m['RunValueNumeric'] ?? 0) < 0 ? 'negative' : '' ?>">
<?= htmlspecialchars($m['RunValue'] ?? '') ?>
</td>
<td class="value-cell <?= ($m['ToDateValueNumeric'] ?? 0) < 0 ? 'negative' : '' ?>">
<?= htmlspecialchars($m['ToDateValue'] ?? '') ?>
</td>
<td>
<?php if ($m['Category']): ?>
<span class="category-badge"><?= htmlspecialchars($m['Category']) ?></span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<?php if (empty($metrics)): ?>
<tr>
<td colspan="5" class="no-data">No metrics found</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
<?php else: ?>
<div class="no-data">
<p>Select a report from the sidebar to view metrics</p>
</div>
<?php endif; ?>
</main>
</div>
</section>
</div>
<?php require __DIR__ . '/../includes/layout/footer.php'; ?>