<?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();
}

$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $reports = readJson('reports');
        $newId = getNextId('reports');
        
        // Handle file uploads
        $uploadedFiles = [];
        $uploadDir = '../uploads/safety_reports/';
        
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        if (isset($_FILES['attachments'])) {
            $files = $_FILES['attachments'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain'];
            $maxSize = 5 * 1024 * 1024;
            
            for ($i = 0; $i < count($files['name']); $i++) {
                if ($files['error'][$i] == 0) {
                    $fileName = $files['name'][$i];
                    $fileTmp = $files['tmp_name'][$i];
                    $fileType = $files['type'][$i];
                    $fileSize = $files['size'][$i];
                    
                    if (!in_array($fileType, $allowedTypes)) {
                        $error .= "File '{$fileName}' type not allowed. ";
                        continue;
                    }
                    if ($fileSize > $maxSize) {
                        $error .= "File '{$fileName}' exceeds 5MB limit. ";
                        continue;
                    }
                    
                    $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                    $newFileName = 'report_' . $newId . '_' . time() . '_' . $i . '.' . $ext;
                    $destination = $uploadDir . $newFileName;
                    
                    if (move_uploaded_file($fileTmp, $destination)) {
                        $uploadedFiles[] = [
                            'original_name' => $fileName,
                            'saved_name' => $newFileName,
                            'path' => 'uploads/safety_reports/' . $newFileName,
                            'type' => $fileType,
                            'size' => $fileSize,
                            'uploaded_at' => date('Y-m-d H:i:s')
                        ];
                    } else {
                        $error .= "Failed to upload '{$fileName}'. ";
                    }
                }
            }
        }
        
        $report = [
            'id' => $newId,
            'user_id' => $_SESSION['user_id'],
            'title' => $_POST['title'],
            'content' => $_POST['content'],
            'attachments' => $uploadedFiles,
            'status' => 'unread',
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $reports[] = $report;
        writeJson('reports', $reports);
        
        $message = "✅ Safety report submitted successfully!";
        if (count($uploadedFiles) > 0) {
            $message .= "<br>📎 " . count($uploadedFiles) . " file(s) uploaded.";
        }
        if (!empty($error)) {
            $message .= "<br>⚠️ " . $error;
        }
        
    } catch (Exception $e) {
        $error = "Error: " . $e->getMessage();
    }
}
?>
<?php include('../includes/header.php'); ?>
<style>
    .file-list {
        margin-top: 10px;
        padding: 10px;
        background: #fefcf8;
        border-radius: 16px;
        border: 1px solid #e2cfb3;
    }
    .file-item {
        display: inline-block;
        margin: 5px;
        padding: 5px 10px;
        background: #f8efe5;
        border-radius: 30px;
        font-size: 0.75rem;
        color: #2c1e12;
    }
    .info-note {
        background: #faf3e8;
        padding: 12px;
        border-radius: 16px;
        margin-bottom: 20px;
        color: #6b1d2f;
        border-left: 4px solid #c9a87c;
    }
    /* Cancel button theme styling */
    .btn-cancel {
        background: #8b6b42;
        color: #faf3e8;
        width: 100%;
        text-align: center;
        margin-top: 10px;
        transition: background 0.2s;
    }
    .btn-cancel:hover {
        background: #6b4f2f;
        transform: translateY(-1px);
    }
</style>

<div class="sidebar">
    <h3>✈️ Crew Menu</h3>
    <a href="dashboard.php" class="btn">🏠 Dashboard</a>
    <a href="view_memos.php" class="btn">📝 Memos</a>
    <a href="take_quiz.php" class="btn">📚 Quizzes</a>
    <a href="safety_report.php" class="btn active">⚠️ New Report</a>
    <a href="my_reports.php" class="btn">📋 My Reports</a>
    <a href="profile.php" class="btn">👤 Profile</a>
    <a href="view_manual.php" class="btn">📘 Maintenance Manual</a>
</div>

<div class="content">
    <h2>⚠️ File Safety Report</h2>
    
    <?php if($message): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
    <?php endif; ?>
    
    <?php if($error && !$message): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <?php if(!$message): ?>
        <div class="info-note">
            ✈️ Use this form to report any safety concerns, hazards, incidents, or near‑misses.<br>
            You can attach images, PDFs, or documents (max 5MB per file, up to 5 files).
        </div>
        
        <form method="POST" enctype="multipart/form-data">
            <label>Report Title *</label>
            <input type="text" name="title" required placeholder="e.g., Spill in Hangar Bay, Equipment Malfunction">
            
            <label>Report Details *</label>
            <textarea name="content" rows="8" required placeholder="Please provide detailed information about the safety concern..."></textarea>
            
            <label>📎 Attach Files (Images, PDF, Documents)</label>
            <input type="file" name="attachments[]" multiple accept="image/*,application/pdf,.doc,.docx,.txt">
            <small style="color:#8b7355;">Allowed: JPG, PNG, GIF, PDF, DOC, TXT (Max 5MB each)</small>
            
            <div id="fileList" class="file-list" style="display: none;">
                <strong>Selected files:</strong>
                <div id="selectedFiles"></div>
            </div>
            
            <!-- Submit button -->
            <button type="submit" class="btn btn-primary" style="background: #6b1d2f; color: #f9e4c2; width: 100%; margin-top: 20px; padding: 14px;">✈️ Submit Report</button>
            
            <!-- Cancel button now properly themed -->
            <a href="dashboard.php" class="btn btn-cancel">Cancel</a>
        </form>
    <?php else: ?>
        <div style="text-align: center; margin-top: 20px;">
            <a href="my_reports.php" class="btn btn-primary">📋 View My Reports</a>
            <a href="dashboard.php" class="btn btn-cancel">🏠 Back to Dashboard</a>
        </div>
    <?php endif; ?>
</div>

<script>
    const fileInput = document.querySelector('input[type="file"]');
    const fileListDiv = document.getElementById('fileList');
    const selectedFilesDiv = document.getElementById('selectedFiles');
    
    if (fileInput) {
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                fileListDiv.style.display = 'block';
                let html = '';
                for (let i = 0; i < this.files.length; i++) {
                    const file = this.files[i];
                    const sizeKB = (file.size / 1024).toFixed(1);
                    html += `<div class="file-item">📎 ${file.name} (${sizeKB} KB)</div>`;
                }
                selectedFilesDiv.innerHTML = html;
            } else {
                fileListDiv.style.display = 'none';
            }
        });
    }
</script>

<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>