<?php
    error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('../includes/functions.php');

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

$message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $memos = readJson('memos');
    $newId = getNextId('memos');
    
    // Handle PDF upload
    $pdfPath = '';
    if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] == 0) {
        $allowed = ['pdf'];
        $filename = $_FILES['pdf_file']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $pdfPath = 'uploads/memos/memo_' . $newId . '_' . time() . '.pdf';
            if (!file_exists('../uploads/memos')) {
                mkdir('../uploads/memos', 0777, true);
            }
            move_uploaded_file($_FILES['pdf_file']['tmp_name'], '../' . $pdfPath);
        }
    }
    
    $memo = [
        'id' => $newId,
        'title' => $_POST['title'],
        'content' => $_POST['content'],
        'pdf_file' => $pdfPath,
        'has_pdf' => !empty($pdfPath),
        'created_by' => $_SESSION['user_id'],
        'assigned_to' => $_POST['user_ids'],
        'read_by' => [],
        'read_at' => [],
        'created_at' => date('Y-m-d H:i:s')
    ];
    
    $memos[] = $memo;
    writeJson('memos', $memos);
    
    // Send emails to assigned employees
    $employees = getAllEmployees();
    $emailCount = 0;
    foreach ($employees as $emp) {
        if (in_array($emp['id'], $_POST['user_ids'])) {
            $subject = "📝 New Memo: " . $_POST['title'];
            $emailMsg = "<h3>New Memo Assigned</h3>
                        <p><strong>Title:</strong> " . htmlspecialchars($_POST['title']) . "</p>
                        <p><strong>Content:</strong> " . nl2br(htmlspecialchars($_POST['content'])) . "</p>";
            if (!empty($pdfPath)) {
                $emailMsg .= "<p><strong>📎 Attachment:</strong> PDF document included</p>";
            }
            $emailMsg .= "<p><strong>Action Required:</strong> Please login to the portal to read and acknowledge this memo.</p>
                        <hr>
                        <p><small>This is an automated notification from Employee Portal.</small></p>";
            sendEmailNotification($emp['email'], $subject, $emailMsg);
            $emailCount++;
        }
    }
    
    $message = "✅ Memo added successfully!<br>";
    $message .= "📧 Email notifications sent to " . $emailCount . " employees.<br>";
    if (!empty($pdfPath)) {
        $message .= "📎 PDF file uploaded successfully.<br>";
    }
    $message .= "📝 Total employees assigned: " . count($_POST['user_ids']);
}

$employees = getAllEmployees();
?>
<?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>
</div>
<div class="content">
    <h2>Add New Memo</h2>
    <?php if($message): ?>
        <div class="alert alert-info"><?php echo $message; ?></div>
    <?php endif; ?>
    
    <form method="POST" enctype="multipart/form-data">
        <label>Memo Title *</label>
        <input type="text" name="title" required placeholder="Enter memo title">
        
        <label>Memo Content / Description *</label>
        <textarea name="content" rows="5" required placeholder="Type your memo content or description here..."></textarea>
        
        <label>📎 Attach PDF (Optional)</label>
        <input type="file" name="pdf_file" accept=".pdf">
        <small style="color: #666;">Supported format: PDF only. Max size: 5MB</small>
        
        <label>Assign to Employees (Hold Ctrl/Cmd to select multiple) *</label>
        <select name="user_ids[]" multiple size="8" required style="width: 100%; padding: 10px;">
            <?php foreach($employees as $emp): ?>
                <option value="<?php echo $emp['id']; ?>">
                    <?php echo htmlspecialchars($emp['full_name'] . " - " . $emp['email']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <small style="color: #666;">💡 Tip: Hold Ctrl (Windows) or Cmd (Mac) to select multiple employees</small>
        
        <button type="submit" class="btn btn-success" style="margin-top: 20px;">📝 Add Memo & Send Notifications</button>
        <a href="dashboard.php" class="btn" style="margin-top: 20px;">Cancel</a>
    </form>
</div>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>