<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once 'db/config.php';

// Mock data, mirroring the structure from the image and previous context
$cases = [
    [
        'id' => 'HR-2024-1847',
        'title' => 'Manager Conflict Resolution',
        'status' => 'in-review',
        'severity' => 'high',
        'department' => 'Engineering',
        'assignedTo' => 'Jennifer Smith',
        'assignedToRole' => 'Senior HR Manager',
        'createdDate' => 'Dec 10, 2024',
        'lastUpdate' => '2 hours ago',
        'commentsCount' => 8,
        'partiesInvolved' => 3,
        'tags' => ['Conflict', 'Management', 'Urgent'],
        'checklist' => [
            ['item' => 'Initial complaint documented', 'completed' => true],
            ['item' => 'Meeting with complainant scheduled', 'completed' => true],
            ['item' => 'Meeting with manager', 'completed' => false],
            ['item' => 'Resolution plan drafted', 'completed' => false],
        ],
        'timeline' => [
            ['status' => 'Opened', 'details' => 'Case opened by HR department', 'date' => 'Dec 15, 2024 10:30 AM', 'completed' => true],
            ['status' => 'Investigation', 'details' => 'Initial interviews conducted', 'date' => 'Dec 18, 2024 2:45 PM', 'completed' => true],
            ['status' => 'Mediation', 'details' => 'Mediation session scheduled', 'date' => 'Dec 22, 2024 3:00 PM', 'completed' => false],
            ['status' => 'Resolution', 'details' => 'Awaiting final sign-off', 'date' => null, 'completed' => false],
        ],
        'comments' => [
            ['author' => 'Jennifer Smith', 'role' => 'Senior HR Manager', 'time' => '2 hours ago', 'comment' => 'Just completed the meeting with David. He acknowledged the concerns and is willing to work on improving team communication. I\'ve scheduled a follow-up session for next week to review progress.'],
            ['author' => 'Michael Torres', 'role' => 'Team Lead', 'time' => '1 day ago', 'comment' => 'Thanks for the quick response on this. The team really appreciates that this is being taken seriously. I think we\'re seeing some improvement already in daily standups.'],
        ]
    ],
    // Add other cases here...
    [
        'id' => 'HR-2024-1852',
        'title' => 'Benefits Inquiry - Health Insurance',
        'status' => 'open',
        'severity' => 'low',
        'department' => 'Sales',
        'assignedTo' => 'Michael Torres',
        'assignedToRole' => 'HR Coordinator',
        'createdDate' => 'Dec 12, 2024',
        'lastUpdate' => '4 hours ago',
        'commentsCount' => 3,
        'partiesInvolved' => 1,
        'tags' => ['Benefits', 'Inquiry', 'Insurance'],
        'checklist' => [
            ['item' => 'Received employee question', 'completed' => true],
            ['item' => 'Forwarded to benefits provider', 'completed' => true],
            ['item' => 'Awaiting provider response', 'completed' => false]
        ],
        'timeline' => [
            ['status' => 'Opened', 'details' => 'Employee submitted a question about health insurance coverage.', 'date' => 'Dec 12, 2024 9:00 AM', 'completed' => true]
        ],
        'comments' => [
             ['author' => 'Michael Torres', 'role' => 'HR Coordinator', 'time' => '4 hours ago', 'comment' => 'I have forwarded the inquiry to our insurance provider. Should have an answer within 2 business days.']
        ]
    ],
    [
        'id' => 'HR-2024-1850',
        'title' => 'FMLA Request - Medical Leave',
        'status' => 'open',
        'severity' => 'medium',
        'department' => 'Marketing',
        'assignedTo' => 'Jennifer Smith',
        'assignedToRole' => 'Senior HR Manager',
        'createdDate' => 'Dec 11, 2024',
        'lastUpdate' => '1 day ago',
        'commentsCount' => 2,
        'partiesInvolved' => 1,
        'tags' => ['FMLA', 'Leave', 'Medical'],
        'checklist' => [
            ['item' => 'Received FMLA request form', 'completed' => true],
            ['item' => 'Verify employee eligibility', 'completed' => true],
            ['item' => 'Awaiting medical certification', 'completed' => false],
            ['item' => 'Notify manager of leave dates', 'completed' => false]
        ],
        'timeline' => [
            ['status' => 'Request Received', 'details' => 'FMLA request form submitted by employee.', 'date' => 'Dec 11, 2024 11:00 AM', 'completed' => true],
            ['status' => 'Eligibility Verified', 'details' => 'Employee eligibility for FMLA confirmed.', 'date' => 'Dec 12, 2024 3:00 PM', 'completed' => true],
            ['status' => 'Pending Certification', 'details' => 'Awaiting required medical certification from healthcare provider.', 'date' => null, 'completed' => false]
        ],
        'comments' => [
            ['author' => 'Jennifer Smith', 'role' => 'Senior HR Manager', 'time' => '1 day ago', 'comment' => 'Eligibility for FMLA has been confirmed. I have notified the employee that we are now waiting for the medical certification documents to proceed.']
        ]
    ],
    [
        'id' => 'HR-2024-1851',
        'title' => 'Onboarding Documentation',
        'status' => 'closed',
        'severity' => 'low',
        'department' => 'General',
        'assignedTo' => 'Michael Torres',
        'assignedToRole' => 'HR Coordinator',
        'createdDate' => 'Dec 9, 2024',
        'lastUpdate' => '3 days ago',
        'commentsCount' => 1,
        'partiesInvolved' => 1,
        'tags' => ['Onboarding', 'New Hire'],
        'checklist' => [
            ['item' => 'Sent welcome packet', 'completed' => true],
            ['item' => 'Received signed offer letter', 'completed' => true],
            ['item' => 'Completed I-9 verification', 'completed' => true]
        ],
        'timeline' => [
            ['status' => 'Offer Sent', 'details' => 'Job offer and welcome packet sent to new hire.', 'date' => 'Dec 5, 2024', 'completed' => true],
            ['status' => 'Documents Signed', 'details' => 'Received all signed onboarding documents.', 'date' => 'Dec 8, 2024', 'completed' => true],
            ['status' => 'Onboarding Complete', 'details' => 'All onboarding steps have been successfully completed.', 'date' => 'Dec 9, 2024', 'completed' => true]
        ],
        'comments' => [
            ['author' => 'Michael Torres', 'role' => 'HR Coordinator', 'time' => '3 days ago', 'comment' => 'All onboarding paperwork for the new hire is complete and has been filed. Marking this case as closed.']
        ]
    ],
    [
        'id' => 'HR-2024-1855',
        'title' => 'Workplace Safety Concern',
        'status' => 'in-review',
        'severity' => 'high',
        'department' => 'Facilities',
        'assignedTo' => 'Jennifer Smith',
        'assignedToRole' => 'Senior HR Manager',
        'createdDate' => 'Dec 14, 2024',
        'lastUpdate' => '6 hours ago',
        'commentsCount' => 5,
        'partiesInvolved' => 2,
        'tags' => ['Safety', 'Facilities', 'Urgent'],
        'checklist' => [
            ['item' => 'Anonymous report received', 'completed' => true],
            ['item' => 'Initial walkthrough completed', 'completed' => false],
            ['item' => 'Interviewed relevant staff', 'completed' => false]
        ],
        'timeline' => [
            ['status' => 'Report Filed', 'details' => 'Anonymous safety concern regarding the warehouse was received.', 'date' => 'Dec 14, 2024 4:30 PM', 'completed' => true],
            ['status' => 'Investigation Started', 'details' => 'Opened an official investigation into the reported concern.', 'date' => 'Dec 15, 2024 9:00 AM', 'completed' => false]
        ],
        'comments' => [
            ['author' => 'Jennifer Smith', 'role' => 'Senior HR Manager', 'time' => '6 hours ago', 'comment' => 'I have received the anonymous report and will be conducting an initial walkthrough of the facilities tomorrow morning to assess the situation. All further updates will be logged here.']
        ]
    ]
];

$cases_json = json_encode($cases);


function get_severity_badge($severity) {
    switch (strtolower($severity)) {
        case 'high': return 'bg-red-100 text-red-800';
        case 'medium': return 'bg-yellow-100 text-yellow-800';
        case 'low': return 'bg-green-100 text-green-800';
        default: return 'bg-gray-100 text-gray-800';
    }
}

function get_status_badge($status) {
    switch (strtolower($status)) {
        case 'in-review': return 'bg-blue-100 text-blue-800';
        case 'open': return 'bg-gray-200 text-gray-800';
        case 'closed': return 'bg-green-200 text-green-800';
        default: return 'bg-gray-100 text-gray-800';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HR Cases - FinMox</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/lucide/4.2.0/lucide.min.css" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
</head>
<body class="bg-gray-50">
    <div class="flex h-screen bg-white">
        <?php include '_sidebar.php'; ?>

        <div class="flex-1 flex flex-col overflow-hidden">
            <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50">
                <div class="container mx-auto px-6 py-8">
                    <div class="flex flex-col md:flex-row gap-8">

                        <!-- Left Column: Case Details -->
                        <div id="case-details-column" class="w-full md:w-3/5 lg:w-3/5 order-2 md:order-1">
                            <div class="space-y-6">
                                
                                <!-- Case Header -->
                                <div class="bg-white border border-gray-200 rounded-2xl p-6">
                                    <div class="flex justify-between items-center mb-4">
                                        <h2 id="case-title" class="text-2xl font-bold text-gray-900">Manager Conflict Resolution</h2>
                                        <div class="flex items-center gap-2">
                                            <span id="case-severity-badge" class="text-sm font-semibold px-3 py-1 rounded-lg <?php echo get_severity_badge('high'); ?>">High Severity</span>
                                             <select id="case-status-dropdown" class="border border-gray-300 rounded-lg text-sm font-medium focus:ring-blue-500 focus:border-blue-500">
                                                <option>Open</option>
                                                <option selected>In Review</option>
                                                <option>Closed</option>
                                            </select>
                                        </div>
                                    </div>
                                    <p id="case-id-date" class="text-sm text-gray-500">Case #HR-2024-1847 • Created Dec 10, 2024</p>
                                </div>

                                <!-- Case Timeline -->
                                <div class="bg-white border border-gray-200 rounded-2xl p-6">
                                     <h3 class="text-xl font-bold text-gray-900 mb-6">Case Timeline</h3>
                                     <div id="case-timeline-content" class="space-y-8 relative">
                                        <!-- Timeline items will be injected here -->
                                     </div>
                                 </div>

                                <!-- Comments Section -->
                                <div class="bg-white border border-gray-200 rounded-2xl p-6">
                                    <h3 class="text-xl font-bold text-gray-900 mb-6">Comments & Discussion</h3>
                                    <div id="case-comments-content" class="space-y-6">
                                        <!-- Comments will be injected here -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column: Contextual Sidebar & Case List -->
                        <div class="w-full md:w-2/5 lg:w-2/5 order-1 md:order-2 space-y-6">
                            
                            <!-- Contextual Details -->
                             <div class="bg-white border border-gray-200 rounded-2xl p-6">
                                <h3 class="text-lg font-bold text-gray-900 mb-6">Case Details</h3>
                                <div class="space-y-5">
                                    <div>
                                        <p class="text-sm text-gray-500 mb-1">Assigned HR Rep</p>
                                        <div class="flex items-center gap-3">
                                            <img id="case-assignee-img" src="https://i.pravatar.cc/40?u=jennifer" class="w-10 h-10 rounded-full" alt="Jennifer Smith">
                                            <div>
                                                <p id="case-assignee-name" class="font-semibold text-gray-800">Jennifer Smith</p>
                                                <p id="case-assignee-role" class="text-sm text-gray-500">Senior HR Manager</p>
                                            </div>
                                        </div>
                                    </div>
                                    <hr>
                                    <div>
                                        <p class="text-sm text-gray-500 mb-1">Department</p>
                                        <p id="case-department" class="font-medium text-gray-800">Engineering</p>
                                    </div>
                                    <div>
                                        <p class="text-sm text-gray-500 mb-1">Parties Involved</p>
                                        <p id="case-parties" class="font-medium text-gray-800">3 employees</p>
                                    </div>
                                    <hr>
                                    <div>
                                        <p class="text-sm text-gray-500 mb-3">Tags</p>
                                        <div id="case-tags" class="flex flex-wrap gap-2">
                                            <span class="bg-blue-100 text-blue-800 text-sm font-medium px-3 py-1 rounded-md">Conflict</span>
                                            <span class="bg-blue-100 text-blue-800 text-sm font-medium px-3 py-1 rounded-md">Management</span>
                                            <span class="bg-red-100 text-red-800 text-sm font-medium px-3 py-1 rounded-md">Urgent</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Resolution Checklist -->
                            <div class="bg-white border border-gray-200 rounded-2xl p-6">
                                <div class="flex justify-between items-center mb-3">
                                    <h3 class="text-lg font-bold text-gray-900">Resolution Checklist</h3>
                                    <span id="checklist-progress-text" class="text-sm font-semibold text-gray-600">2/4</span>
                                </div>
                                <div class="w-full bg-gray-200 rounded-full h-2 mb-4">
                                    <div id="checklist-progress-bar" class="bg-blue-600 h-2 rounded-full" style="width: 50%"></div>
                                </div>
                                <div id="checklist-items" class="space-y-3">
                                    <!-- Checklist items will be injected here -->
                                </div>
                            </div>

                            <!-- Case List -->
                            <div class="bg-white border border-gray-200 rounded-2xl p-6">
                                <h3 class="text-lg font-bold text-gray-900 mb-4">All Cases</h3>
                                <div class="space-y-3">
                                    <?php foreach ($cases as $case):
                                        // Corrected escaping for the data-case-id attribute
                                    ?>
                                        <a href="#" class="case-link block p-4 bg-gray-50 rounded-xl border border-gray-200 hover:border-blue-500 transition-colors cursor-pointer" data-case-id="<?php echo htmlspecialchars($case['id']); ?>">
                                            <div class="flex items-start justify-between">
                                                <p class="font-bold text-gray-800 group-hover:text-blue-600"><?php echo htmlspecialchars($case['title']); ?></p>
                                                <span class="text-xs font-semibold px-2 py-1 rounded-full <?php echo get_severity_badge($case['severity']); ?>"><?php echo htmlspecialchars(ucfirst($case['severity'])); ?></span>
                                            </div>
                                            <p class="text-xs text-gray-500 mt-1"><?php echo htmlspecialchars($case['id']); ?></p>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        const casesData = <?php echo $cases_json; ?>;
        const casesMap = new Map(casesData.map(c => [c.id, c]));

        const caseTitle = document.getElementById('case-title');
        const caseIdDate = document.getElementById('case-id-date');
        const caseSeverityBadge = document.getElementById('case-severity-badge');
        const caseStatusDropdown = document.getElementById('case-status-dropdown');
        
        const caseAssigneeImg = document.getElementById('case-assignee-img');
        const caseAssigneeName = document.getElementById('case-assignee-name');
        const caseAssigneeRole = document.getElementById('case-assignee-role');
        const caseDepartment = document.getElementById('case-department');
        const caseParties = document.getElementById('case-parties');
        const caseTags = document.getElementById('case-tags');

        const checklistProgressText = document.getElementById('checklist-progress-text');
        const checklistProgressBar = document.getElementById('checklist-progress-bar');
        const checklistItems = document.getElementById('checklist-items');
        
        const timelineContent = document.getElementById('case-timeline-content');
        const commentsContent = document.getElementById('case-comments-content');

        function getSeverityBadgeClass(severity) {
            switch (severity.toLowerCase()) {
                case 'high': return 'bg-red-100 text-red-800';
                case 'medium': return 'bg-yellow-100 text-yellow-800';
                case 'low': return 'bg-green-100 text-green-800';
                default: return 'bg-gray-100 text-gray-800';
            }
        }

        function renderChecklist(checklist) {
            checklistItems.innerHTML = '';
            if (!checklist || checklist.length === 0) {
                 checklistItems.innerHTML = '<p class="text-sm text-gray-500">No checklist items.</p>';
                 checklistProgressBar.style.width = '0%';
                 checklistProgressText.textContent = '0/0';
                 return;
            }
            
            let completedCount = 0;
            checklist.forEach(item => {
                if (item.completed) completedCount++;
                const itemEl = document.createElement('div');
                itemEl.className = 'flex items-center';
                itemEl.innerHTML = `
                    <div class="${item.completed ? 'bg-blue-600' : 'border border-gray-400'} rounded-full w-5 h-5 flex items-center justify-center mr-3"><svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path></svg></div>
                    <span class="${item.completed ? 'text-gray-500 line-through' : 'text-gray-800'} text-sm">${item.item}</span>
                `;
                checklistItems.appendChild(itemEl);
            });

            const progress = (completedCount / checklist.length) * 100;
            checklistProgressBar.style.width = `${progress}%`;
            checklistProgressText.textContent = `${completedCount}/${checklist.length}`;
        }
        
        function renderTimeline(timeline) {
            timelineContent.innerHTML = '';
            if (!timeline || timeline.length === 0) {
                 timelineContent.innerHTML = '<p class="text-sm text-gray-500">No timeline events.</p>';
                 return;
            }

            // Vertical line
            const line = document.createElement('div');
            line.className = 'absolute left-4 top-2 bottom-2 w-0.5 bg-gray-200';
            timelineContent.appendChild(line);

            timeline.forEach(item => {
                const itemEl = document.createElement('div');
                itemEl.className = 'relative pl-12';
                itemEl.innerHTML = `
                    <div class="${item.completed ? 'bg-blue-600' : 'border-2 border-gray-400'} absolute left-4 top-1.5 -translate-x-1/2 w-5 h-5 rounded-full z-10 bg-white flex items-center justify-center" >
                         ${item.completed ? '<svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path></svg>' : ''}
                    </div>
                    <div class="flex items-center justify-between">
                        <p class="font-bold text-gray-800">${item.status}</p>
                        <p class="text-sm text-gray-500">${item.date || ''}</p>
                    </div>
                    <p class="text-sm text-gray-600 mt-1">${item.details}</p>
                `;
                timelineContent.appendChild(itemEl);
            });
        }
        
        function renderComments(comments) {
            commentsContent.innerHTML = '';
            if (!comments || comments.length === 0) {
                 commentsContent.innerHTML = '<p class="text-sm text-gray-500">No comments yet.</p>';
                 return;
            }
            comments.forEach(comment => {
                const itemEl = document.createElement('div');
                itemEl.className = 'flex items-start gap-4';
                itemEl.innerHTML = `
                    <img src="https://i.pravatar.cc/40?u=${comment.author.replace(/\s/g, '')}" class="w-10 h-10 rounded-full" alt="${comment.author}">
                    <div class="flex-1">
                        <div class="flex justify-between items-center">
                            <div>
                                <p class="font-semibold text-gray-800">${comment.author}</p>
                                <p class="text-xs text-gray-500">${comment.role}</p>
                            </div>
                            <p class="text-xs text-gray-400">${comment.time}</p>
                        </div>
                        <p class="text-sm text-gray-700 mt-2 bg-gray-50 p-3 rounded-lg">${comment.comment}</p>
                    </div>
                `;
                commentsContent.appendChild(itemEl);
            });
        }

        function updateCaseDetails(caseId) {
            const caseData = casesMap.get(caseId);
            if (!caseData) return;

            // Header
            caseTitle.textContent = caseData.title;
            caseIdDate.textContent = `Case #${caseData.id} • Created ${caseData.createdDate}`;
            caseSeverityBadge.textContent = caseData.severity.charAt(0).toUpperCase() + caseData.severity.slice(1);
            caseSeverityBadge.className = `text-sm font-semibold px-3 py-1 rounded-lg ${getSeverityBadgeClass(caseData.severity)}`;
            caseStatusDropdown.value = caseData.status.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase());

            // Details card
            caseAssigneeImg.src = `https://i.pravatar.cc/40?u=${caseData.assignedTo.replace(/\s/g, '')}`;
            caseAssigneeName.textContent = caseData.assignedTo;
            caseAssigneeRole.textContent = caseData.assignedToRole;
            caseDepartment.textContent = caseData.department;
            caseParties.textContent = `${caseData.partiesInvolved} employees`;
            caseTags.innerHTML = '';
            caseData.tags.forEach(tag => {
                const tagEl = document.createElement('span');
                tagEl.className = 'bg-blue-100 text-blue-800 text-sm font-medium px-3 py-1 rounded-md';
                tagEl.textContent = tag;
                if(tag.toLowerCase() === 'urgent') {
                    tagEl.className = 'bg-red-100 text-red-800 text-sm font-medium px-3 py-1 rounded-md';
                }
                caseTags.appendChild(tagEl);
            });

            // Checklist
            renderChecklist(caseData.checklist);
            
            // Timeline
            renderTimeline(caseData.timeline);

            // Comments
            renderComments(caseData.comments);
        }

        // Setup links
        const caseLinks = document.querySelectorAll('.case-link');
        caseLinks.forEach(link => {
            link.addEventListener('click', function (e) {
                e.preventDefault();
                
                // Update active state
                caseLinks.forEach(l => l.classList.remove('bg-blue-100', 'border-blue-500'));
                this.classList.add('bg-blue-100', 'border-blue-500');

                const caseId = this.dataset.caseId;
                updateCaseDetails(caseId);
            });
        });

        // Show first case by default
        if (casesData.length > 0) {
            const firstCaseId = casesData[0].id;
            updateCaseDetails(firstCaseId);
            const firstLink = document.querySelector('.case-link');
            if(firstLink) {
                 firstLink.classList.add('bg-blue-100', 'border-blue-500');
            }
        }
    });
    </script>
</body>
</html>