<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available.

$status_message = '';
$user_id = $_SESSION['user_id'] ?? 1; // Default to ID 1 for safety

// --- 1. Fetch All Users for Supervisor Dropdown ---
$users = [];
$sql_users = "SELECT user_id, username FROM users ORDER BY username ASC";
$result_users = $conn->query($sql_users);

if ($result_users && $result_users->num_rows > 0) {
    while ($row = $result_users->fetch_assoc()) {
        $users[] = $row;
    }
} else {
     // Fallback if no users exist (shouldn't happen in a real ERP)
    $status_message = "<div class='alert alert-warning'>Warning: No users found for supervisor selection.</div>";
}

// --- 2. Handle Form Submission ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $report_month = $_POST['report_month'] ?? null;
    $supervisor_id = (int)($_POST['supervisor_id'] ?? 0);
    $title = $conn->real_escape_string($_POST['title'] ?? '');
    $description = $conn->real_escape_string($_POST['description'] ?? '');
    
    // Determine the status based on which button was clicked
    if (isset($_POST['submit_report'])) {
        $status = 'Pending';
        $success_msg = "Activity Report submitted successfully! Status: Pending review by Supervisor.";
    } elseif (isset($_POST['save_draft'])) {
        $status = 'Draft';
        $success_msg = "Activity Report saved as draft.";
    } else {
        // Should not happen if buttons are properly named
        $status = 'Draft';
        $success_msg = "Activity Report saved as draft.";
    }

    // Input Validation
    if (!$report_month || $supervisor_id <= 0 || empty($title) || empty($description)) {
        $status_message = "<div class='alert alert-error'>Please fill in all required fields (Month, Supervisor, Title, Description).</div>";
    } else {
        
        $sql_insert = "INSERT INTO monthly_activities (submitted_by_user_id, supervisor_user_id, report_month, title, description, status, submission_date) 
                       VALUES (?, ?, ?, ?, ?, ?, NOW())";
        
        if ($stmt = $conn->prepare($sql_insert)) {
            $stmt->bind_param("iisss", $user_id, $supervisor_id, $report_month, $title, $description, $status);
            
            if ($stmt->execute()) {
                $status_message = "<div class='alert alert-success'>{$success_msg}</div>";
                // Clear inputs after successful submission (or reload page)
                // Note: Reloading will clear POST data, simplifying the view
            } else {
                $status_message = "<div class='alert alert-error'>Database error: " . $stmt->error . "</div>";
            }
            $stmt->close();
        } else {
            $status_message = "<div class='alert alert-error'>Database preparation error: " . $conn->error . "</div>";
        }
    }
}

// Prepare current month for default value in the month input
$default_month = date('Y-m'); 
?>

<div class="form-card">
    <h3>Create Monthly Activity Report</h3>
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=create_activity_report" method="post" id="activity_form">
        
        <div style="display: flex; gap: 20px; margin-bottom: 20px;">
            <div style="flex: 1;">
                <label for="report_month">SELECT MONTH *</label>
                <input type="month" name="report_month" id="report_month" value="<?php echo $default_month; ?>" required>
            </div>
            <div style="flex: 1;">
                <label for="supervisor_id">SUPERVISOR *</label>
                <select name="supervisor_id" id="supervisor_id" required>
                    <option value="">-- Select Supervisor --</option>
                    <?php 
                    foreach ($users as $user) {
                        // Prevent user from selecting themselves as supervisor, typically
                        if ($user['user_id'] != $user_id) {
                            echo '<option value="' . htmlspecialchars($user['user_id']) . '">' 
                               . htmlspecialchars($user['username']) 
                               . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>
        </div>

        <!-- Title -->
        <label for="title">TITLE *</label>
        <input type="text" name="title" id="title" required placeholder="Title-1">

        <!-- Description (Main Activity Content) -->
        <label for="description">DESCRIPTION *</label>
        <textarea name="description" id="description" rows="6" required placeholder="Description-1"></textarea>

        <!-- Action Buttons -->
        <div style="display: flex; gap: 10px; margin-top: 20px; justify-content: flex-start;">
            
            <!-- Submit Button (sends to supervisor, status = Pending) -->
            <button type="submit" name="submit_report" style="background-color: #2ecc71; color: white; border: none; padding: 10px 20px; border-radius: 5px;">
                <i class="fas fa-check"></i> Submit
            </button>
            
            <!-- Draft Button (saves locally, status = Draft) -->
            <button type="submit" name="save_draft" style="background-color: #34495e; color: white; border: none; padding: 10px 20px; border-radius: 5px;">
                <i class="fas fa-save"></i> Draft
            </button>
            
            <!-- Reset Button (clears form fields) -->
            <button type="reset" style="background-color: #f39c12; color: white; border: none; padding: 10px 20px; border-radius: 5px;">
                <i class="fas fa-undo"></i> Reset
            </button>
            
            <!-- Cancel/Close Button (redirects to list view) -->
            <button type="button" onclick="window.location.href='admin_dashboard.php?page=activity_report_list'" style="background-color: #e74c3c; color: white; border: none; padding: 10px 20px; border-radius: 5px;">
                <i class="fas fa-times"></i> Close
            </button>
        </div>
    </form>
</div>
<script>
    // Simple reset functionality enhancement (in case the browser doesn't clear the month input well)
    document.querySelector('button[type="reset"]').addEventListener('click', function() {
        document.getElementById('report_month').value = '<?php echo $default_month; ?>';
        document.getElementById('supervisor_id').selectedIndex = 0;
    });
</script>
