<?php
// pages/issues.php
requireRole('any');

// Handle Status Update
if (isset($_GET['status']) && isset($_GET['id'])) {
    $new_status = clean_input($_GET['status']);
    $issue_id = (int)$_GET['id'];
    
    // Only update allowed statuses (Resolve is now handled via POST for comments)
    if (in_array($new_status, ['Open','In Progress','Closed'])) {
        $pdo->prepare("UPDATE issues SET status = ?, updated_at = NOW() WHERE id = ?")->execute([$new_status, $issue_id]);
        $success = "Issue status updated.";
    }
}

// Handle Delete Issue
if (isset($_GET['delete_id'])) {
    requireRole('admin');
    $del_id = (int)$_GET['delete_id'];
    if ($pdo->prepare("DELETE FROM issues WHERE id = ?")->execute([$del_id])) {
        $success = "Issue deleted successfully.";
    }
}

// Handle Status Update with Comments (via POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $issue_id = (int)$_POST['issue_id'];
    $notes = clean_input($_POST['notes']);
    $new_status = clean_input($_POST['new_status']);
    $resolver_id = $_SESSION['member_id'] ?? null;

    $sql = "UPDATE issues SET status = ?, resolution_notes = CONCAT(IFNULL(resolution_notes, ''), '\n', ?), updated_at = NOW()";
    if ($new_status == 'Resolved') {
        $sql .= ", resolved_by = ?, resolved_at = NOW()";
        $params = [$new_status, 'Status -> ' . $new_status . ': ' . $notes, $resolver_id, $issue_id];
    } else {
        $params = [$new_status, 'Status -> ' . $new_status . ': ' . $notes, $issue_id];
    }
    // Correctly prepare statement for variable params
    $sql .= " WHERE id = ?";

    $stmt = $pdo->prepare($sql);
    if ($stmt->execute($params)) {
        $success = "Issue status updated to $new_status.";
    }
}

// Filters
$status_filter = isset($_GET['filter_status']) ? $_GET['filter_status'] : 'In Progress';
$priority_filter = isset($_GET['filter_priority']) ? $_GET['filter_priority'] : '';
$type_filter = isset($_GET['filter_type']) ? $_GET['filter_type'] : '';
$dept_filter = isset($_GET['filter_dept']) ? $_GET['filter_dept'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Fetch filter options from settings
$issue_types = $pdo->query("SELECT DISTINCT value FROM settings_options WHERE category='issue_types' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);
$departments = $pdo->query("SELECT DISTINCT value FROM settings_options WHERE category='departments' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);

$sql = "
    SELECT i.*, 
    m1.full_name as reporter_name, 
    m2.full_name as assignee_name,
    s.type as service_type,
    s.service_date
    FROM issues i
    JOIN members m1 ON i.reported_by = m1.id
    LEFT JOIN members m2 ON i.assigned_to = m2.id
    LEFT JOIN services s ON i.service_id = s.id
    WHERE 1=1
";

$params = [];

if ($status_filter != 'All') {
    $sql .= " AND i.status = ?";
    $params[] = $status_filter;
}

if (!empty($priority_filter)) {
    $sql .= " AND i.priority = ?";
    $params[] = $priority_filter;
}

if (!empty($type_filter)) {
    $sql .= " AND i.type = ?";
    $params[] = $type_filter;
}

if (!empty($dept_filter)) {
    $sql .= " AND i.department = ?";
    $params[] = $dept_filter;
}

if (!empty($date_from)) {
    $sql .= " AND DATE(i.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $sql .= " AND DATE(i.created_at) <= ?";
    $params[] = $date_to;
}

$sql .= " ORDER BY i.priority DESC, i.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$issues = $stmt->fetchAll();

// Helper function to calculate age based on date reported
function getIssueAge($date_reported) {
    if (!$date_reported) return '-';
    $now = new DateTime();
    $reported = new DateTime($date_reported);
    $diff = $now->diff($reported);
    
    if ($diff->days == 0) {
        if ($diff->h == 0) {
            return $diff->i . " min" . ($diff->i != 1 ? 's' : '');
        }
        return $diff->h . " hour" . ($diff->h != 1 ? 's' : '');
    } elseif ($diff->days < 7) {
        return $diff->days . " day" . ($diff->days != 1 ? 's' : '');
    } else {
        $months = floor($diff->days / 30);
        return $months . " month" . ($months != 1 ? 's' : '');
    }
}
?>

<div style="display: flex; justify-content: space-between; align-items: center;">
    <h1>Issue Tracking</h1>
    <div style="display: flex; gap: 10px;">
        <button onclick="window.print()" class="btn" style="background-color: #666;"><i class="fas fa-print"></i> Print PDF</button>
        <button onclick="downloadJPG()" class="btn" style="background-color: #666;"><i class="fas fa-image"></i> Download JPG</button>
        <a href="index.php?page=issue_form" class="btn">Report New Issue</a>
    </div>
</div>

<?php if (isset($success)): ?>
<div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card" style="margin-top: 20px;">
    <!-- Status Filter Tabs -->
    <div style="margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #444;">
        <a href="index.php?page=issues&filter_status=In Progress" class="btn" style="<?php echo $status_filter=='In Progress'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">In Progress</a>
        <a href="index.php?page=issues&filter_status=Resolved" class="btn" style="<?php echo $status_filter=='Resolved'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">Resolved</a>
        <a href="index.php?page=issues&filter_status=Closed" class="btn" style="<?php echo $status_filter=='Closed'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">Closed</a>
        <a href="index.php?page=issues&filter_status=Open" class="btn" style="<?php echo $status_filter=='Open'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">Open</a>
        <a href="index.php?page=issues&filter_status=All" class="btn" style="<?php echo $status_filter=='All'?'background-color:#444;':'background-color:transparent; border:1px solid #444;'; ?>">All</a>
    </div>

    <!-- Advanced Filters -->
    <form method="GET" style="margin-bottom: 20px;">
        <input type="hidden" name="page" value="issues">
        <input type="hidden" name="filter_status" value="<?php echo htmlspecialchars($status_filter); ?>">
        
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; margin-bottom: 10px;">
            <div>
                <label style="font-size: 0.85rem; color: #888; margin-bottom: 3px; display: block;">Priority</label>
                <select name="filter_priority" class="form-control" style="padding: 8px;">
                    <option value="">All Priorities</option>
                    <option value="urgent" <?php if($priority_filter=='urgent') echo 'selected'; ?>>🔴 Urgent</option>
                    <option value="normal" <?php if($priority_filter=='normal') echo 'selected'; ?>>🟡 Normal</option>
                    <option value="low" <?php if($priority_filter=='low') echo 'selected'; ?>>🟢 Low</option>
                </select>
            </div>
            
            <div>
                <label style="font-size: 0.85rem; color: #888; margin-bottom: 3px; display: block;">Type</label>
                <select name="filter_type" class="form-control" style="padding: 8px;">
                    <option value="">All Types</option>
                    <?php foreach($issue_types as $t): ?>
                    <option value="<?php echo htmlspecialchars($t); ?>" <?php if($type_filter==$t) echo 'selected'; ?>>
                        <?php echo htmlspecialchars($t); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label style="font-size: 0.85rem; color: #888; margin-bottom: 3px; display: block;">Department</label>
                <select name="filter_dept" class="form-control" style="padding: 8px;">
                    <option value="">All Departments</option>
                    <?php foreach($departments as $d): ?>
                    <option value="<?php echo htmlspecialchars($d); ?>" <?php if($dept_filter==$d) echo 'selected'; ?>>
                        <?php echo htmlspecialchars($d); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label style="font-size: 0.85rem; color: #888; margin-bottom: 3px; display: block;">From Date</label>
                <input type="date" name="date_from" class="form-control" style="padding: 8px;" value="<?php echo htmlspecialchars($date_from); ?>">
            </div>
            
            <div>
                <label style="font-size: 0.85rem; color: #888; margin-bottom: 3px; display: block;">To Date</label>
                <input type="date" name="date_to" class="form-control" style="padding: 8px;" value="<?php echo htmlspecialchars($date_to); ?>">
            </div>
        </div>
        
        <div style="display: flex; gap: 10px;">
            <button type="submit" class="btn">Apply Filters</button>
            <?php if($priority_filter || $type_filter || $dept_filter || $date_from || $date_to): ?>
            <a href="index.php?page=issues&filter_status=<?php echo $status_filter; ?>" class="btn" style="background-color: #666;">Clear Filters</a>
            <?php endif; ?>
        </div>
    </form>

    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>Priority</th>
                    <th>Type / Dept</th>
                    <th>Location</th>
                    <th>Service / Event</th>
                    <th>Summary of Issue (For Dashboard/Reports)</th>
                    <th>Date Reported</th>
                    <th>Assigned To</th>
                    <th>Status</th>
                    <th>Age</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($issues) > 0): ?>
                    <?php foreach ($issues as $i): ?>
                    <tr>
                        <td>
                            <?php 
                            $priority_color = '#ffa000'; // normal - yellow
                            $priority_icon = '🟡';
                            if ($i['priority'] == 'urgent') {
                                $priority_color = 'var(--danger-color)';
                                $priority_icon = '🔴';
                            } elseif ($i['priority'] == 'low') {
                                $priority_color = 'var(--success-color)';
                                $priority_icon = '🟢';
                            }
                            ?>
                            <span style="font-size: 1.2rem;"><?php echo $priority_icon; ?></span>
                            <div style="font-size: 0.75rem; color: <?php echo $priority_color; ?>; font-weight: bold; text-transform: uppercase;">
                                <?php echo htmlspecialchars($i['priority']); ?>
                            </div>
                        </td>
                        <td>
                            <strong><?php echo htmlspecialchars($i['type']); ?></strong><br>
                            <small><?php echo htmlspecialchars($i['department']); ?></small>
                        </td>
                        <td>
                            <?php if(!empty($i['location'])): ?>
                                <small><?php echo htmlspecialchars($i['location']); ?></small>
                            <?php else: ?>
                                <small style="color: #666;">N/A</small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if($i['service_id']): ?>
                                <small><strong><?php echo htmlspecialchars($i['service_type']); ?></strong></small><br>
                                <small style="color: #888;"><?php echo date('M j, Y', strtotime($i['service_date'] ?? 'now')); ?></small>
                            <?php else: ?>
                                <small style="color: #666;">General / Operations</small>
                            <?php endif; ?>
                        </td>
                        <td class="description-cell">
                             <?php 
                             if (!empty($i['description_summary'])) {
                                 echo htmlspecialchars($i['description_summary']);
                             } else {
                                 $desc = htmlspecialchars($i['description']);
                                 echo strlen($desc) > 100 ? substr($desc, 0, 100) . '...' : $desc;
                             }
                             ?>
                             <div class="full-description no-export" style="display:none;">
                                 <?php echo nl2br(htmlspecialchars($i['description'])); ?>
                             </div>
                        </td>
                        <td>
                            <?php 
                            $reported_date = $i['date_reported'] ?? $i['created_at'];
                            echo date("M j, Y g:i A", strtotime($reported_date)); 
                            ?><br>
                            <small style="color:#888;">by <?php echo htmlspecialchars($i['reporter_name']); ?></small>
                        </td>
                        <td><?php echo htmlspecialchars($i['assignee_name'] ?? 'Unassigned'); ?></td>
                        <td>
                             <?php 
                            $status_color = '#ffa000';
                            if ($i['status'] == 'Open') $status_color = 'var(--danger-color)';
                            if ($i['status'] == 'Resolved') $status_color = 'var(--success-color)';
                            if ($i['status'] == 'Closed') $status_color = '#555';
                            ?>
                            <span class="badge" style="background: <?php echo $status_color; ?>; padding: 2px 6px; border-radius: 4px;"><?php echo htmlspecialchars($i['status']); ?></span>
                        </td>
                        <td style="white-space: nowrap; color: #888; font-size: 0.85rem;">
                            <?php echo getIssueAge($i['date_reported'] ?? $i['created_at']); ?>
                        </td>
                        <td style="white-space: nowrap;">
                            <a href="index.php?page=issue_form&id=<?php echo $i['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; margin-right: 5px;">Edit</a>
                            <?php if($i['status'] == 'Open'): ?>
                                <button onclick="showResolveModal(<?php echo $i['id']; ?>, 'In Progress')" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: #666;">Start</button>
                            <?php elseif($i['status'] == 'In Progress'): ?>
                                <button onclick="showResolveModal(<?php echo $i['id']; ?>, 'Resolved')" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: var(--success-color);">Resolve</button>
                                <a href="index.php?page=issues&id=<?php echo $i['id']; ?>&status=Closed&filter_status=<?php echo $status_filter; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: #333;">Close</a>
                            <?php elseif($i['status'] == 'Resolved'): ?>
                                <a href="index.php?page=issues&id=<?php echo $i['id']; ?>&status=Closed&filter_status=<?php echo $status_filter; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: #333;">Close</a>
                            <?php endif; ?>
                            
                            <?php if(hasRole('admin')): ?>
                                <a href="index.php?page=issues&delete_id=<?php echo $i['id']; ?>&filter_status=<?php echo $status_filter; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: var(--danger-color);" onclick="return confirm('Permanently delete this issue?')">Delete</a>
                            <?php endif; ?>
                            
                            <?php if(!empty($i['resolution_notes'])): ?>
                                <div style="font-size: 0.75rem; color: #888; mt-1; max-width: 200px; font-style: italic;">
                                    Notes: <?php echo htmlspecialchars($i['resolution_notes']); ?>
                                </div>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="8" style="text-align: center;">No issues found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Resolve Modal -->
<div id="resolveModal" class="modal" style="display:none; position: fixed; z-index: 1001; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8);">
    <div class="card" style="width: 400px; margin: 100px auto;">
        <h3>Resolve Issue</h3>
        <p>Please enter resolution notes/comments:</p>
        <form method="POST">
            <input type="hidden" name="issue_id" id="modal_issue_id">
            <textarea name="resolution_notes" class="form-control" rows="4" placeholder="How was this issue fixed?" required style="margin-bottom: 15px;"></textarea>
            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                <button type="button" onclick="closeResolveModal()" class="btn" style="background: #333;">Cancel</button>
                <button type="submit" name="resolve_issue" class="btn">Confirm Resolution</button>
            </div>
        </form>
    </div>
</div>

<script>
function showResolveModal(id) {
    document.getElementById('modal_issue_id').value = id;
    document.getElementById('resolveModal').style.display = 'block';
}
function closeResolveModal() {
    document.getElementById('resolveModal').style.display = 'none';
}
// Close on outside click
window.onclick = function(event) {
    if (event.target == document.getElementById('resolveModal')) {
        closeResolveModal();
    }
}



function downloadJPG() {
    const element = document.querySelector('.card');
    
    html2canvas(element, {
        backgroundColor: '#ffffff',
        scale: 2,
        onclone: (clonedDoc) => {
            // This runs on the CLONED DOM before rendering, perfect for export modifications
            const clonedCard = clonedDoc.querySelector('.card');
            const clonedBody = clonedDoc.body;
            
            // 1. Force styles via class (if CSS matches)
            clonedBody.classList.add('jpg-export-mode');
            clonedCard.classList.add('jpg-export-mode-active');
            
            // 2. MANUAL OVERRIDES (Belt and Suspenders)
            clonedCard.style.backgroundColor = '#ffffff';
            clonedCard.style.color = '#000000';
            clonedCard.style.border = 'none';
            clonedCard.style.boxShadow = 'none';
            
            // Inject Heading (It's outside the card in the main page)
            const heading = clonedDoc.createElement('h1');
            heading.innerText = 'Issue Tracking Report';
            heading.style.textAlign = 'center';
            heading.style.color = '#000000';
            heading.style.marginBottom = '20px';
            clonedCard.insertBefore(heading, clonedCard.firstChild);
            
            // 3. Manually hide columns (Indices 1 and 3 because nth-child is 1-based, but querySelectorAll is array)
            // Header columns: 2nd and 4th -> indices 1 and 3. Last -> index length-1
            const rows = clonedCard.querySelectorAll('tr');
            rows.forEach(row => {
                row.style.backgroundColor = '#ffffff';
                row.style.color = '#000000';
                
                const cells = row.cells;
                if (cells.length > 5) { // Ensure it's the main table
                    // Hide columns according to request:
                    // Hide 2nd column (Type / Dept)
                    if(cells[1]) cells[1].style.display = 'none';
                    // Hide 4th column (Service / Event)
                    if(cells[3]) cells[3].style.display = 'none';
                    // Hide Last column (Actions)
                    if(cells[cells.length-1]) cells[cells.length-1].style.display = 'none';
                    
                    // Force cell styles
                    for(let i=0; i<cells.length; i++) {
                        cells[i].style.backgroundColor = '#ffffff';
                        cells[i].style.color = '#000000';
                        cells[i].style.border = '1px solid #ccc';
                    }
                }
            });
            
            // 4. Force Badges to look right
            const badges = clonedCard.querySelectorAll('.badge');
            badges.forEach(b => {
                // Keep background color (computed), but ensure text is readable if needed? 
                // Usually OK, but let's ensure print-color-adjust
                b.style.printColorAdjust = 'exact';
                b.style.webkitPrintColorAdjust = 'exact';
                b.style.border = '1px solid #000';
            });
        }
    }).then(canvas => {
        const link = document.createElement('a');
        link.download = 'issues-report.jpg';
        link.href = canvas.toDataURL('image/jpeg', 0.9);
        link.click();
    });
}
</script>

<style>
/* Shared Print/Export Styles */
@media print, all {
    /* Rules applied during JPG export via class */
    body.jpg-export-mode nav, 
    body.jpg-export-mode header, 
    body.jpg-export-mode .sidebar, 
    body.jpg-export-mode .navbar, 
    body.jpg-export-mode .btn, 
    body.jpg-export-mode .alert, 
    body.jpg-export-mode form { display: none !important; }
    
    body.jpg-export-mode .card {
        background-color: #ffffff !important;
        color: #000000 !important;
        box-shadow: none !important;
        border: none !important;
    }
    
    body.jpg-export-mode table { width: 100% !important; background-color: #ffffff !important; }
    body.jpg-export-mode table th, 
    body.jpg-export-mode table td {
        background-color: #ffffff !important;
        color: #000000 !important;
        border: 1px solid #ccc !important;
    }
    body.jpg-export-mode table th { background-color: #f0f0f0 !important; }
    
    /* Hide Columns: 2 (Type/Dept), 4 (Service/Event), Last (Actions) */
    body.jpg-export-mode table th:nth-child(2), body.jpg-export-mode table td:nth-child(2),
    body.jpg-export-mode table th:nth-child(4), body.jpg-export-mode table td:nth-child(4),
    body.jpg-export-mode table th:nth-last-child(1), body.jpg-export-mode table td:nth-last-child(1) {
        display: none !important;
    }
}

@media print {
    /* Force Issue Summary only for PDF/JPG export */
    .description-cell {
        max-width: 300px !important;
    }
    .full-description, .no-export {
        display: none !important;
    }

    /* Hide Navigation and UI elements */
    nav, header, .sidebar, .navbar, .btn, .alert, form { display: none !important; }
    
    /* Reset layout for print */
    .container, .main-panel, .content, .wrapper { 
        width: 100% !important; 
        margin: 0 !important; 
        padding: 0 !important; 
        left: 0 !important;
        transform: none !important;
    }
    
    /* Force White Background */
    html, body { 
        background-color: #ffffff !important; 
        color: #000000 !important; 
        height: auto !important; 
        overflow: visible !important;
    }
    
    /* Card / Table Container */
    .card { 
        background-color: #ffffff !important; 
        box-shadow: none !important; 
        border: none !important; 
        margin: 0 !important;
    }
    
    /* Typography */
    h1 { color: #000 !important; margin-bottom: 20px !important; }
    
    /* Table Styling */
    table { width: 100% !important; border-collapse: collapse !important; background-color: #ffffff !important; }
    table tr, table td, table tbody { background-color: #ffffff !important; }
    
    table th, table td { 
        color: #000 !important; 
        border: 1px solid #ccc !important; 
        padding: 6px !important; 
        font-size: 10pt !important;
    }
    table th { background-color: #f0f0f0 !important; font-weight: bold !important; }
    
    /* Hide Columns: 2 (Type/Dept), 4 (Service/Event), Last (Actions) */
    table th:nth-child(2), table td:nth-child(2),
    table th:nth-child(4), table td:nth-child(4),
    table th:nth-last-child(1), table td:nth-last-child(1) { display: none !important; }
    
    /* Badges - Allow Color */
    .badge { 
        border: 1px solid #000 !important; 
        /* REMOVED background: transparent to allow colors */
        color: #000 !important; /* Ensure readability? Or trust badge text color? */
        /* Status badge text depends on bg. 
           In code: background: var(--danger-color) etc.
           We want to Keep that.
           We need print-color-adjust.
        */
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
        font-weight: bold !important;
        padding: 2px 6px !important;
    }
    
    /* Icons text fallback */
    .fa, .fas { display: none !important; } 
}
</style>
