<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once('../includes/functions.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'employee') {
    header("Location: ../login.php");
    exit();
}

$userId = $_SESSION['user_id'];
$reportId = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get the report
$reports = readJson('reports');
$currentReport = null;

foreach ($reports as $report) {
    if ($report['id'] == $reportId && $report['user_id'] == $userId) {
        $currentReport = $report;
        break;
    }
}

if (!$currentReport) {
    header("Location: my_reports.php");
    exit();
}

// Handle reply submission
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_reply'])) {
    $replyText = trim($_POST['reply']);
    
    if (empty($replyText)) {
        $error = "Please enter a reply message.";
    } else {
        if (addReportReply($reportId, $userId, $replyText, 'employee')) {
            $message = "✅ Reply added successfully!";
            // Refresh report data
            $reports = readJson('reports');
            foreach ($reports as $report) {
                if ($report['id'] == $reportId) {
                    $currentReport = $report;
                    break;
                }
            }
        } else {
            $error = "❌ Failed to add reply.";
        }
    }
}

$replies = getReportReplies($reportId);
$user = getUserById($userId);
?>
<?php include('../includes/header.php'); ?>
<style>
    .report-detail {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }
    .attachments-section {
        margin-top: 20px;
        padding: 15px;
        background: #e8f4f8;
        border-radius: 8px;
    }
    .attachment-item {
        background: white;
        padding: 10px;
        border-radius: 8px;
        text-align: center;
        min-width: 120px;
    }
    .reply-section {
        margin-top: 20px;
    }
    .reply-card {
        background: white;
        border-left: 4px solid #667eea;
        padding: 15px;
        margin-bottom: 15px;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    .reply-admin {
        border-left-color: #e74c3c;
        background: #fff5f5;
    }
    .reply-employee {
        border-left-color: #27ae60;
        background: #f0fff4;
    }
    .reply-meta {
        font-size: 12px;
        color: #666;
        margin-bottom: 8px;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 10px;
    }
    .reply-badge {
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 10px;
        font-weight: bold;
    }
    .badge-admin {
        background: #e74c3c;
        color: white;
    }
    .badge-employee {
        background: #27ae60;
        color: white;
    }
    .reply-text {
        margin-top: 8px;
        line-height: 1.5;
    }
    .reply-form {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        margin-top: 20px;
    }
    .reply-form textarea {
        width: 100%;
        padding: 12px;
        border: 1px solid #ddd;
        border-radius: 8px;
        resize: vertical;
        font-family: inherit;
    }
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: bold;
    }
    .status-unread {
        background: #e74c3c;
        color: white;
    }
    .status-read {
        background: #27ae60;
        color: white;
    }
</style>
<div class="sidebar">
    <h3>👤 Employee Menu</h3>
    <a href="dashboard.php" class="btn" style="display: block;">🏠 Dashboard</a>
    <a href="view_memos.php" class="btn" style="display: block;">📝 Memos</a>
    <a href="take_quiz.php" class="btn" style="display: block;">📚 Take Quiz</a>
    <a href="safety_report.php" class="btn" style="display: block;">⚠️ New Report</a>
    <a href="my_reports.php" class="btn" style="display: block;">📋 My Reports</a>
    <a href="profile.php" class="btn" style="display: block;">👤 Profile</a>
    <a href="view_manual.php" class="btn" style="display: block;">📘 Maintenance Manual</a>
</div>
<div class="content">
    <h2>📋 Safety Report #<?php echo $reportId; ?></h2>
    
    <?php if($message): ?>
        <div class="alert alert-success" style="background: #d4edda; border-left: 4px solid #27ae60; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <?php if($error): ?>
        <div class="alert alert-danger" style="background: #f8d7da; border-left: 4px solid #e74c3c; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <div class="report-detail">
        <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 15px;">
            <h3 style="margin: 0;"><?php echo htmlspecialchars($currentReport['title']); ?></h3>
            <span class="status-badge <?php echo $currentReport['status'] == 'unread' ? 'status-unread' : 'status-read'; ?>">
                <?php echo $currentReport['status'] == 'unread' ? '🔴 Unread by Admin' : '✅ Read by Admin'; ?>
            </span>
        </div>
        
        <div class="report-meta" style="margin-bottom: 15px;">
            <strong>Submitted:</strong> <?php echo date('F j, Y g:i A', strtotime($currentReport['created_at'])); ?>
        </div>
        
        <div style="background: white; padding: 15px; border-radius: 8px; margin-top: 10px;">
            <strong>Report Details:</strong>
            <p style="margin-top: 10px; line-height: 1.6;"><?php echo nl2br(htmlspecialchars($currentReport['content'])); ?></p>
        </div>
    </div>
    
    <!-- Attachments Section -->
    <?php if (!empty($currentReport['attachments'])): ?>
        <div class="attachments-section">
            <h4>📎 Attached Files (<?php echo count($currentReport['attachments']); ?>)</h4>
            <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;">
                <?php foreach($currentReport['attachments'] as $file): ?>
                    <div class="attachment-item">
                        <?php 
                        $fileExt = pathinfo($file['saved_name'], PATHINFO_EXTENSION);
                        $isImage = in_array(strtolower($fileExt), ['jpg', 'jpeg', 'png', 'gif', 'webp']);
                        ?>
                        <?php if ($isImage): ?>
                            <a href="../<?php echo $file['path']; ?>" target="_blank">
                                <img src="../<?php echo $file['path']; ?>" style="max-width: 100px; max-height: 100px; border-radius: 5px;">
                            </a>
                            <br>
                        <?php else: ?>
                            <div style="font-size: 30px;">📄</div>
                        <?php endif; ?>
                        <a href="../<?php echo $file['path']; ?>" target="_blank" style="font-size: 12px; word-break: break-all;">
                            <?php echo htmlspecialchars($file['original_name']); ?>
                        </a>
                        <br>
                        <small><?php echo round($file['size'] / 1024, 1); ?> KB</small>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>
    
    <!-- Replies Section -->
    <div class="reply-section">
        <h3>💬 Discussion Thread (<?php echo count($replies); ?> replies)</h3>
        
        <?php if(empty($replies)): ?>
            <p style="color: #999; padding: 20px; text-align: center; background: #f8f9fa; border-radius: 8px;">No replies yet. Admin will respond soon.</p>
        <?php else: ?>
            <?php foreach($replies as $reply): 
                $replyUser = getUserById($reply['user_id']);
                $isAdmin = $reply['user_role'] == 'admin';
            ?>
                <div class="reply-card <?php echo $isAdmin ? 'reply-admin' : 'reply-employee'; ?>">
                    <div class="reply-meta">
                        <div>
                            <strong><?php echo htmlspecialchars($replyUser ? $replyUser['full_name'] : 'Unknown'); ?></strong>
                            <span class="reply-badge <?php echo $isAdmin ? 'badge-admin' : 'badge-employee'; ?>">
                                <?php echo $isAdmin ? 'Admin' : 'You'; ?>
                            </span>
                        </div>
                        <div><?php echo date('F j, Y g:i A', strtotime($reply['created_at'])); ?></div>
                    </div>
                    <div class="reply-text">
                        <?php echo nl2br(htmlspecialchars($reply['reply'])); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <!-- Add Reply Form -->
        <div class="reply-form">
            <h4>Add Your Reply</h4>
            <form method="POST">
                <textarea name="reply" rows="4" placeholder="Type your message here..." required></textarea>
                <button type="submit" name="add_reply" class="btn btn-success" style="background: #27ae60; margin-top: 10px;">💬 Post Reply</button>
            </form>
        </div>
    </div>
    
    <div style="margin-top: 20px;">
        <a href="my_reports.php" class="btn" style="background: #95a5a6;">← Back to My Reports</a>
    </div>
</div>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>