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

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

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

// Create uploads directory if not exists
if (!file_exists('../uploads/manuals')) {
    mkdir('../uploads/manuals', 0777, true);
}

// Handle manual upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['manual_pdf'])) {
    $allowed = ['pdf'];
    $filename = $_FILES['manual_pdf']['name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    if (!in_array($ext, $allowed)) {
        $error = "Only PDF files are allowed!";
    } elseif ($_FILES['manual_pdf']['size'] > 10485760) { // 10MB max
        $error = "File size must be less than 10MB!";
    } else {
        // Save manual info to JSON
        $manualData = readJson('maintenance_manual');
        
        $newVersion = isset($manualData['version']) ? $manualData['version'] + 1 : 1;
        $newFilename = 'maintenance_manual_v' . $newVersion . '_' . time() . '.pdf';
        $filepath = 'uploads/manuals/' . $newFilename;
        
        if (move_uploaded_file($_FILES['manual_pdf']['tmp_name'], '../' . $filepath)) {
            $manualData = [
                'version' => $newVersion,
                'filename' => $newFilename,
                'filepath' => $filepath,
                'filesize' => round($_FILES['manual_pdf']['size'] / 1024, 2), // KB
                'uploaded_by' => $_SESSION['user_id'],
                'uploaded_at' => date('Y-m-d H:i:s'),
                'description' => $_POST['description'] ?? '',
                'is_active' => true
            ];
            
            // Deactivate old manual
            $allManuals = readJson('maintenance_manuals_history');
            if (empty($allManuals)) {
                $allManuals = [];
            }
            
            // Add to history
            $allManuals[] = $manualData;
            writeJson('maintenance_manuals_history', $allManuals);
            
            // Save current manual
            writeJson('maintenance_manual', $manualData);
            
            // Notify all employees via email
            $employees = getAllEmployees();
            $emailCount = 0;
            $subject = "📚 New Maintenance Policy Manual Uploaded (Version " . $newVersion . ")";
            
            foreach ($employees as $emp) {
                $emailMsg = "<h3>Maintenance Policy Manual Updated</h3>
                            <p><strong>Version:</strong> " . $newVersion . "</p>
                            <p><strong>Uploaded:</strong> " . date('F j, Y g:i A') . "</p>
                            <p><strong>Description:</strong> " . htmlspecialchars($_POST['description'] ?? 'No description') . "</p>
                            <p><strong>File Size:</strong> " . round($_FILES['manual_pdf']['size'] / 1024, 2) . " KB</p>
                            <p>Please login to the portal to view the latest maintenance policy manual.</p>
                            <hr>
                            <p><small>This is an automated notification from Employee Portal.</small></p>";
                
                if (sendEmailNotification($emp['email'], $subject, $emailMsg)) {
                    $emailCount++;
                }
            }
            
            $message = "✅ Maintenance Policy Manual uploaded successfully!<br>";
            $message .= "📧 Email notifications sent to " . $emailCount . " employees.<br>";
            $message .= "📄 Version: " . $newVersion;
        } else {
            $error = "Failed to upload file!";
        }
    }
}

// Get current manual info
$currentManual = readJson('maintenance_manual');
$manualsHistory = readJson('maintenance_manuals_history');
?>
<?php include('../includes/header.php'); ?>
<div class="sidebar">
    <h3>📋 Admin Menu</h3>
    <a href="dashboard.php" class="btn" style="display: block;">📊 Dashboard</a>
    <a href="add_user.php" class="btn" style="display: block;">👤 Add Employee</a>
    <a href="manage_users.php" class="btn" style="display: block;">📋 Manage Users</a>
    <a href="add_memo.php" class="btn" style="display: block;">📝 Add Memo</a>
    <a href="add_quiz.php" class="btn" style="display: block;">📚 Add Quiz</a>
    <a href="inbox.php" class="btn" style="display: block;">📥 Safety Reports</a>
    <a href="upload_manual.php" class="btn" style="display: block; background: #667eea;">📘 Upload Manual</a>
</div>
<div class="content">
    <h2>📘 Maintenance Policy Manual</h2>
    
    <?php if($message): ?>
        <div class="alert alert-info" style="background: #d4edda; border-left: 4px solid #27ae60; padding: 15px;">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <?php if($error): ?>
        <div class="alert alert-warning" style="background: #f8d7da; border-left: 4px solid #e74c3c; padding: 15px;">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <?php if(!empty($currentManual)): ?>
        <div class="card" style="margin-bottom: 20px;">
            <h3>Current Version: <?php echo $currentManual['version']; ?></h3>
            <table style="width: 100%;">
                <tr><td style="width: 150px;"><strong>Uploaded:</strong></td><td><?php echo date('F j, Y g:i A', strtotime($currentManual['uploaded_at'])); ?></td></tr>
                <tr><td><strong>File Size:</strong></td><td><?php echo $currentManual['filesize']; ?> KB</td></tr>
                <tr><td><strong>Description:</strong></td><td><?php echo nl2br(htmlspecialchars($currentManual['description'] ?? 'No description')); ?></td></tr>
                <tr><td><strong>Current Manual:</strong></td>
                    <td>
                        <a href="../<?php echo $currentManual['filepath']; ?>" target="_blank" class="btn btn-success" style="background: #27ae60;">
                            📖 View Current Manual
                        </a>
                    </td>
                </tr>
            </table>
        </div>
    <?php endif; ?>
    
    <div class="card">
        <h3>Upload New Version</h3>
        <form method="POST" enctype="multipart/form-data">
            <label>Select PDF File *</label>
            <input type="file" name="manual_pdf" accept=".pdf" required>
            <small style="color: #666;">Max file size: 10MB. Only PDF files allowed.</small>
            
            <label>Version Description / Changes</label>
            <textarea name="description" rows="3" placeholder="Describe what's new in this version..."></textarea>
            
            <button type="submit" class="btn btn-success" style="background: #27ae60; margin-top: 10px;">
                📤 Upload New Version
            </button>
        </form>
    </div>
    
    <?php if(!empty($manualsHistory) && count($manualsHistory) > 1): ?>
        <div class="card">
            <h3>Version History</h3>
            <div class="table-responsive">
                <table style="width: 100%;">
                    <thead>
                        <tr style="background: #f8f9fa;">
                            <th>Version</th>
                            <th>Upload Date</th>
                            <th>File Size</th>
                            <th>Description</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $history = array_reverse($manualsHistory);
                        foreach($history as $manual): 
                        ?>
                        <tr>
                            <td><strong>v<?php echo $manual['version']; ?></strong><?php echo ($manual['version'] == $currentManual['version']) ? ' (Current)' : ''; ?></td>
                            <td><?php echo date('M j, Y', strtotime($manual['uploaded_at'])); ?></td>
                            <td><?php echo $manual['filesize']; ?> KB</td>
                            <td><?php echo htmlspecialchars(substr($manual['description'] ?? '', 0, 50)) . (strlen($manual['description'] ?? '') > 50 ? '...' : ''); ?></td>
                            <td>
                                <a href="../<?php echo $manual['filepath']; ?>" target="_blank" class="btn" style="padding: 5px 10px; font-size: 12px;">View</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>