<?php
/**
 * Overtime Taskforce Module — OT Management Hub
 * Tabs: Overview, OT Log, File Uploads, Embed Dashboard, Snowflake Data
 */
$db = getDB();
$isAdmin = hasRole('captain');

// Stats
$otThisMonth = $db->query("SELECT COALESCE(SUM(hours), 0) FROM ot_records WHERE shift_date >= DATE_FORMAT(NOW(), '%Y-%m-01')")->fetchColumn();
$otPending = (int)$db->query("SELECT COUNT(*) FROM ot_records WHERE status = 'pending'")->fetchColumn();
$otTotal = (int)$db->query("SELECT COUNT(*) FROM ot_records")->fetchColumn();
$embedUrl = getSetting('ot_embed_url', '');
?>

<div class="page-header">
    <h1>Overtime Taskforce</h1>
</div>

<!-- Tabs -->
<div class="segmented-control" style="margin-bottom:20px;">
    <button class="seg-btn active" data-tab-group="ot" data-tab="ot-overview" onclick="switchTab('ot','ot-overview')">Overview</button>
    <button class="seg-btn" data-tab-group="ot" data-tab="ot-log" onclick="switchTab('ot','ot-log')">OT Log</button>
    <button class="seg-btn" data-tab-group="ot" data-tab="ot-uploads" onclick="switchTab('ot','ot-uploads')">File Uploads</button>
    <button class="seg-btn" data-tab-group="ot" data-tab="ot-embed" onclick="switchTab('ot','ot-embed')">Embed Dashboard</button>
    <button class="seg-btn" data-tab-group="ot" data-tab="ot-snowflake" onclick="switchTab('ot','ot-snowflake')">Snowflake Data</button>
</div>

<!-- Tab 1: Overview -->
<div id="ot-overview" class="tab-content active" data-tab-content="ot">
    <div class="grid grid-4" style="margin-bottom:24px;">
        <div class="stat-card">
            <span class="stat-value"><?= number_format($otThisMonth, 1) ?></span>
            <span class="stat-label">OT Hours (This Month)</span>
        </div>
        <div class="stat-card">
            <span class="stat-value"><?= $otPending ?></span>
            <span class="stat-label">Pending Approval</span>
        </div>
        <div class="stat-card">
            <span class="stat-value"><?= $otTotal ?></span>
            <span class="stat-label">Total Records</span>
        </div>
        <div class="stat-card">
            <span class="stat-value">$<?= number_format($otThisMonth * 55, 0) ?></span>
            <span class="stat-label">Est. OT Cost (Month)</span>
        </div>
    </div>

    <div class="grid grid-2">
        <div class="card">
            <div class="card-header"><h2 class="card-title">OT Hours (Last 30 Days)</h2></div>
            <canvas id="otBarChart" height="250"></canvas>
        </div>
        <div class="card">
            <div class="card-header"><h2 class="card-title">OT by Unit</h2></div>
            <canvas id="otPieChart" height="250"></canvas>
        </div>
    </div>
</div>

<!-- Tab 2: OT Log -->
<div id="ot-log" class="tab-content" data-tab-content="ot">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">Overtime Records</h2>
            <div style="display:flex; gap:8px;">
                <button class="btn btn-sm btn-secondary" onclick="exportOtCsv()">Export CSV</button>
                <?php if ($isAdmin): ?>
                <button class="btn btn-sm btn-primary" onclick="openModal('addOtModal')">+ Add Record</button>
                <?php endif; ?>
            </div>
        </div>
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Employee</th>
                        <th>Unit</th>
                        <th>Hours</th>
                        <th>Type</th>
                        <th>Status</th>
                        <?php if ($isAdmin): ?><th>Actions</th><?php endif; ?>
                    </tr>
                </thead>
                <tbody id="otTableBody">
                <?php
                $query = $isAdmin
                    ? "SELECT o.*, u.first_name, u.last_name FROM ot_records o LEFT JOIN users u ON o.user_id = u.id ORDER BY o.shift_date DESC LIMIT 25"
                    : "SELECT o.*, u.first_name, u.last_name FROM ot_records o LEFT JOIN users u ON o.user_id = u.id WHERE o.user_id = :uid ORDER BY o.shift_date DESC LIMIT 25";
                $stmt = $db->prepare($query);
                if (!$isAdmin) $stmt->execute([':uid' => $user['id']]); else $stmt->execute();
                $records = $stmt->fetchAll();

                if (empty($records)): ?>
                    <tr><td colspan="7" style="text-align:center; color:var(--ios-secondary); padding:24px;">No overtime records found.</td></tr>
                <?php else:
                    foreach ($records as $r): ?>
                    <tr>
                        <td><?= htmlspecialchars($r['shift_date'] ?? '') ?></td>
                        <td><?= htmlspecialchars(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? '')) ?></td>
                        <td><?= htmlspecialchars($r['unit'] ?? '') ?></td>
                        <td><?= number_format($r['hours'] ?? 0, 1) ?></td>
                        <td><?= htmlspecialchars($r['ot_type'] ?? '') ?></td>
                        <td>
                            <?php $s = $r['status'] ?? 'pending'; ?>
                            <span class="badge <?= $s === 'approved' ? 'badge-green' : ($s === 'denied' ? 'badge-red' : 'badge-orange') ?>">
                                <?= ucfirst($s) ?>
                            </span>
                        </td>
                        <?php if ($isAdmin): ?>
                        <td>
                            <?php if ($s === 'pending'): ?>
                                <button class="btn btn-sm btn-success" onclick="approveOt(<?= $r['id'] ?>)">Approve</button>
                                <button class="btn btn-sm btn-outline" onclick="denyOt(<?= $r['id'] ?>)">Deny</button>
                            <?php endif; ?>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach;
                endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Tab 3: File Uploads -->
<div id="ot-uploads" class="tab-content" data-tab-content="ot">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">Documents &amp; Files</h2>
        </div>
        <form id="uploadForm" action="modules/overtime-taskforce/upload.php" method="POST" enctype="multipart/form-data" style="margin-bottom:20px;">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
            <div class="dropzone" id="otDropzone" onclick="document.getElementById('otFileInput').click();">
                <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom:8px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                <p style="font-weight:600;">Drop files here or click to browse</p>
                <p style="font-size:12px;">PDF, Excel, Word, Images — Max 10MB</p>
                <input type="file" id="otFileInput" name="file" style="display:none;" accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png">
            </div>
            <div class="form-group" style="margin-top:12px;">
                <label>Description</label>
                <input type="text" name="description" class="form-control" placeholder="Brief description of the file">
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>

        <div class="grid grid-3" id="uploadedFiles">
            <?php
            $files = $db->query("SELECT up.*, u.first_name, u.last_name FROM uploads up LEFT JOIN users u ON up.user_id = u.id WHERE up.module = 'overtime' ORDER BY up.uploaded_at DESC LIMIT 20")->fetchAll();
            foreach ($files as $f): ?>
            <div class="card" style="padding:16px;">
                <div style="display:flex; align-items:center; gap:10px; margin-bottom:8px;">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--ios-blue)" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                    <div style="flex:1; min-width:0;">
                        <div style="font-weight:600; font-size:13px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
                            <?= htmlspecialchars($f['original_name']) ?>
                        </div>
                        <div style="font-size:11px; color:var(--ios-secondary);">
                            <?= round(($f['file_size'] ?? 0) / 1024) ?> KB &middot; <?= date('M j', strtotime($f['uploaded_at'])) ?>
                        </div>
                    </div>
                </div>
                <?php if ($f['description']): ?>
                    <div style="font-size:12px; color:var(--ios-secondary); margin-bottom:8px;"><?= htmlspecialchars($f['description']) ?></div>
                <?php endif; ?>
                <div style="font-size:11px; color:var(--ios-tertiary);">
                    Uploaded by <?= htmlspecialchars($f['first_name'] . ' ' . $f['last_name']) ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($files)): ?>
                <div class="empty-state" style="grid-column:1/-1;"><h3>No files uploaded yet</h3></div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Tab 4: Embed Dashboard -->
<div id="ot-embed" class="tab-content" data-tab-content="ot">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">Embedded Analytics Dashboard</h2>
            <?php if ($isAdmin): ?>
            <button class="btn btn-sm btn-secondary" onclick="openModal('embedConfigModal')">Configure</button>
            <?php endif; ?>
        </div>
        <?php if ($embedUrl): ?>
            <iframe src="<?= htmlspecialchars($embedUrl) ?>" style="width:100%; height:600px; border:0; border-radius:8px;" allowfullscreen></iframe>
        <?php else: ?>
            <div class="empty-state" style="padding:60px;">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--ios-secondary)" stroke-width="1.5"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
                <h3>No Dashboard Configured</h3>
                <p>An admin can paste a Power BI, Google Data Studio, or Tableau embed URL here.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Tab 5: Snowflake Data -->
<div id="ot-snowflake" class="tab-content" data-tab-content="ot">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">Snowflake Synced Data</h2>
            <?php if ($isAdmin): ?>
            <button class="btn btn-sm btn-primary" onclick="syncSnowflake()">Sync Now</button>
            <?php endif; ?>
        </div>
        <div class="alert alert-info" style="margin-bottom:16px;">
            Snowflake data sync pulls ESO and OT analytics from the department's Snowflake data warehouse.
        </div>
        <div class="empty-state" style="padding:40px;">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--ios-secondary)" stroke-width="1.5"><circle cx="12" cy="12" r="3"/><path d="M12 1v6m0 6v6m8.66-15l-5.2 3m-6.92 4l-5.2 3m0-10l5.2 3m6.92 4l5.2 3"/></svg>
            <h3>Snowflake Connection</h3>
            <p>Last synced: <strong id="snowflakeLastSync">Never</strong></p>
            <p style="margin-top:8px;">Configure the cron job to enable automatic daily sync.</p>
        </div>
    </div>
</div>

<!-- Add OT Modal -->
<div class="modal-overlay" id="addOtModal">
    <div class="modal">
        <div class="modal-header">
            <h2>Add OT Record</h2>
            <button class="modal-close" onclick="closeModal('addOtModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form id="addOtForm" method="POST">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                <div class="form-group">
                    <label>Date</label>
                    <input type="date" name="shift_date" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>Unit</label>
                    <select name="unit" class="form-control">
                        <option value="Unit 1">Unit 1</option>
                        <option value="Unit 2">Unit 2</option>
                        <option value="Unit 3">Unit 3</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Hours</label>
                    <input type="number" name="hours" class="form-control" step="0.5" min="0" max="24" required>
                </div>
                <div class="form-group">
                    <label>OT Type</label>
                    <select name="ot_type" class="form-control">
                        <option value="Holdover">Holdover</option>
                        <option value="Callback">Callback</option>
                        <option value="Mandatory">Mandatory</option>
                        <option value="Voluntary">Voluntary</option>
                        <option value="Special Detail">Special Detail</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Notes</label>
                    <input type="text" name="notes" class="form-control" placeholder="Optional notes">
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal('addOtModal')">Cancel</button>
            <button class="btn btn-primary" onclick="document.getElementById('addOtForm').submit();">Save</button>
        </div>
    </div>
</div>

<script>
// Chart.js initialization
if (typeof Chart !== 'undefined') {
    // Bar chart — OT hours last 30 days
    const barCtx = document.getElementById('otBarChart');
    if (barCtx) {
        new Chart(barCtx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: <?php
                    $labels = []; $values = [];
                    for ($i = 29; $i >= 0; $i--) {
                        $d = date('Y-m-d', strtotime("-{$i} days"));
                        $labels[] = date('M j', strtotime($d));
                        $stmt = $db->prepare("SELECT COALESCE(SUM(hours),0) FROM ot_records WHERE shift_date = :d");
                        $stmt->execute([':d' => $d]);
                        $values[] = (float)$stmt->fetchColumn();
                    }
                    echo json_encode($labels);
                ?>,
                datasets: [{
                    label: 'OT Hours',
                    data: <?= json_encode($values) ?>,
                    backgroundColor: 'rgba(27, 108, 176, 0.8)',
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { y: { beginAtZero: true }, x: { display: false } }
            }
        });
    }

    // Pie chart — OT by unit
    const pieCtx = document.getElementById('otPieChart');
    if (pieCtx) {
        <?php
        $u1 = (float)$db->query("SELECT COALESCE(SUM(hours),0) FROM ot_records WHERE unit = 'Unit 1'")->fetchColumn();
        $u2 = (float)$db->query("SELECT COALESCE(SUM(hours),0) FROM ot_records WHERE unit = 'Unit 2'")->fetchColumn();
        $u3 = (float)$db->query("SELECT COALESCE(SUM(hours),0) FROM ot_records WHERE unit = 'Unit 3'")->fetchColumn();
        ?>
        new Chart(pieCtx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: ['Unit 1 (Green)', 'Unit 2 (Blue)', 'Unit 3 (Red)'],
                datasets: [{
                    data: [<?= $u1 ?>, <?= $u2 ?>, <?= $u3 ?>],
                    backgroundColor: ['#16A34A', '#2563EB', '#DC2626']
                }]
            },
            options: { responsive: true, maintainAspectRatio: false }
        });
    }
}

function exportOtCsv() {
    window.location.href = window.CFD_PORTAL.apiPath + '/ot-export.php?format=csv&csrf_token=' + window.CFD_PORTAL.csrfToken;
}

function syncSnowflake() {
    window.portalAPI('snowflake-sync.php', { method: 'POST', body: new FormData() })
        .then(data => { if (data) alert(data.message || 'Sync triggered.'); });
}
</script>
