<?php
// FILE: create_activity_report.php
// Purpose: Allows an employee to create, submit, view, and manage monthly activity reports (Drafts & Submitted).

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include_once 'config/db_connection.php';

$status_message = '';
$user_id = $_SESSION['user_id'] ?? 1;

if (!isset($conn) || $conn->connect_error) {
    $status_message = "<div class='alert alert-error'>Database connection error. Please check config/db_connection.php.</div>";
    exit($status_message);
}

$report_id_to_edit = (int)($_GET['edit_id'] ?? 0);
$current_report_data = null;
$default_date = date('Y-m-d'); 

// --- 0. Handle Delete Action for Drafts ---
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    $sql_delete = "DELETE FROM monthly_activities WHERE report_id = ? AND submitted_by_user_id = ? AND status = 'Draft'";
    if ($stmt_del = $conn->prepare($sql_delete)) {
        $stmt_del->bind_param("ii", $delete_id, $user_id);
        if ($stmt_del->execute()) {
            $status_message = "<div class='alert alert-success'>Draft report ID: {$delete_id} deleted successfully.</div>";
        } else {
            $status_message = "<div class='alert alert-error'>Could not delete draft. Error: " . $stmt_del->error . "</div>";
        }
        $stmt_del->close();
    }
}

// --- 1. Fetch Users for Supervisor Dropdown ---
$users = [];
$sql_users = "SELECT user_id, username FROM users WHERE user_id != ? ORDER BY username ASC";
if ($stmt_users = $conn->prepare($sql_users)) {
    $stmt_users->bind_param("i", $user_id);
    $stmt_users->execute();
    $result_users = $stmt_users->get_result();
    while ($row = $result_users->fetch_assoc()) {
        $users[$row['user_id']] = $row['username'];
    }
    $stmt_users->close();
}

// --- 1.5 Fetch Report to Edit ---
if ($report_id_to_edit > 0) {
    $sql_edit = "SELECT report_id, report_month, supervisor_user_id, title, activity_description, status 
                 FROM monthly_activities 
                 WHERE report_id = ? AND submitted_by_user_id = ? AND status = 'Draft'";
    if ($stmt_edit = $conn->prepare($sql_edit)) {
        $stmt_edit->bind_param("ii", $report_id_to_edit, $user_id);
        $stmt_edit->execute();
        $result_edit = $stmt_edit->get_result();
        if ($result_edit->num_rows === 1) {
            $current_report_data = $result_edit->fetch_assoc();
            $default_date = date('Y-m-d', strtotime($current_report_data['report_month']));
        } else {
            $status_message = "<div class='alert alert-error'>Draft not found or you do not have permission to edit it.</div>";
            $report_id_to_edit = 0; 
        }
        $stmt_edit->close();
    }
}

// --- 2. Handle Form Submission ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $report_date = $_POST['report_date'] ?? null; 
    $supervisor_id = (int)($_POST['supervisor_id'] ?? 0);
    $title = $_POST['title'] ?? '';
	// FIX: Explicitly URL decode the string to replace '+' signs with spaces
    $activity_description = urldecode($_POST['activity_description'] ?? '');
    $report_id = (int)($_POST['report_id'] ?? 0);

    $status = isset($_POST['submit_report']) ? 'Pending' : 'Draft';
    $success_msg = ($status === 'Pending')
        ? "Activity Report submitted successfully for review."
        : "Activity Report saved as draft.";

    if (!$report_date || $supervisor_id <= 0 || empty($title) || empty($activity_description)) {
        $status_message = "<div class='alert alert-error'>Please fill in all required fields.</div>";
        if ($report_id > 0) $report_id_to_edit = $report_id;
        $current_report_data = [
            'report_id' => $report_id, 
            'report_month' => $report_date, 
            'supervisor_user_id' => $supervisor_id,
            'title' => $title, 
            'activity_description' => $activity_description 
        ];
    } else {
        $db_report_date = date('Y-m-d', strtotime($report_date));
        $title = trim($title);
        $activity_description = trim($activity_description);

        if ($report_id > 0) {
            // --- UPDATE EXISTING REPORT ---
            $sql_update = "UPDATE monthly_activities 
                           SET supervisor_user_id = ?, report_month = ?, title = ?, activity_description = ?, status = ?, submission_date = NOW() 
                           WHERE report_id = ? AND submitted_by_user_id = ? AND status = 'Draft'";
            if ($stmt = $conn->prepare($sql_update)) {
                // ✅ FIXED: correct binding order and types
                $stmt->bind_param("issssii", 
                    $supervisor_id, 
                    $db_report_date, 
                    $title, 
                    $activity_description, 
                    $status, 
                    $report_id, 
                    $user_id
                );
                if ($stmt->execute()) {
                    if ($stmt->affected_rows > 0) {
                        $status_message = "<div class='alert alert-success'>{$success_msg} (Updated Report ID: {$report_id})</div>";
                    } else {
                        $status_message = "<div class='alert alert-error'>Could not update report ID: {$report_id}. Check if it's still a draft.</div>";
                    }
                    $report_id_to_edit = 0; 
                } 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>";
            }
        } else {
            // --- INSERT NEW REPORT ---
            $sql_insert = "INSERT INTO monthly_activities 
                           (submitted_by_user_id, supervisor_user_id, report_month, title, activity_description, status, submission_date)
                           VALUES (?, ?, ?, ?, ?, ?, NOW())";

            if ($stmt = $conn->prepare($sql_insert)) {
                // ✅ FIXED HERE: activity_description is string (s), not integer
                $stmt->bind_param("iissss", 
                    $user_id, 
                    $supervisor_id, 
                    $db_report_date, 
                    $title, 
                    $activity_description, 
                    $status
                );
                if ($stmt->execute()) {
                    $status_message = "<div class='alert alert-success'>{$success_msg}</div>";
                } 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>";
            }
        }
    }
}

// --- 3. Fetch Draft Reports ---
$draft_reports = [];
$sql_drafts = "SELECT report_id, report_month, title, submission_date FROM monthly_activities WHERE submitted_by_user_id = ? AND status = 'Draft' ORDER BY submission_date DESC";
if ($stmt_drafts = $conn->prepare($sql_drafts)) {
    $stmt_drafts->bind_param("i", $user_id);
    $stmt_drafts->execute();
    $result_drafts = $stmt_drafts->get_result();
    while ($row = $result_drafts->fetch_assoc()) {
        $draft_reports[] = $row;
    }
    $stmt_drafts->close();
}

// --- 4. Fetch Submitted Reports ---
$submitted_reports = [];
$sql_submitted = "SELECT report_id, report_month, title, status, supervisor_user_id, status_date, activity_description, supervisor_feedback 
                  FROM monthly_activities 
                  WHERE submitted_by_user_id = ? AND status != 'Draft' ORDER BY submission_date DESC";
if ($stmt_submitted = $conn->prepare($sql_submitted)) {
    $stmt_submitted->bind_param("i", $user_id);
    $stmt_submitted->execute();
    $result_submitted = $stmt_submitted->get_result();
    while ($row = $result_submitted->fetch_assoc()) {
        $submitted_reports[] = $row;
    }
    $stmt_submitted->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Activity Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f4f7f9; margin: 0; padding: 20px; }
        .form-card { max-width: 900px; margin: 20px auto; padding: 25px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); background-color: #fff; }
        .form-card h3 { color: #2c3e50; border-bottom: 2px solid #ecf0f1; padding-bottom: 10px; margin-bottom: 20px; }
        label { display: block; margin-top: 15px; font-weight: bold; color: #555; }
        input[type="text"], input[type="date"], textarea, select { width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; }
        textarea { resize: vertical; }
        .alert { padding: 10px; margin-bottom: 15px; border-radius: 5px; font-weight: 600; }
        .alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        
        /* Consistent Button Styling */
        button, .btn { 
            cursor: pointer; 
            border: none; 
            padding: 10px 15px; 
            border-radius: 5px; 
            transition: background-color 0.2s; 
            font-weight: 600;
            display: inline-flex; 
            align-items: center;
            gap: 5px; 
        }
        button:hover, .btn:hover { opacity: 0.9; }
        
        .btn-submit { background-color: #6edc8f; color: #155724; } 
        .btn-draft { background-color: #aebfd4; color: #2c3e50; } 
        .btn-cancel { background-color: #f1a89d; color: #721c24; } 
        .btn-edit { background-color: #f7e09d; color: #8a6d3b; margin-right: 5px; } 
        .btn-delete { background-color: #f1a89d; color: #721c24; } 
        .btn-view { background-color: #92bce2; color: #1f3a5f; } 
        
        .report-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        .report-table th, .report-table td { border: 1px solid #eee; padding: 10px; text-align: left; font-size: 0.9em; }
        .report-table th { background-color: #ecf0f1; font-weight: 700; color: #34495e; }
        .status-badge { padding: 5px 10px; border-radius: 15px; font-size: 0.8em; font-weight: 700; display: inline-block; }
        .status-Pending { background-color: #f0ad4e; color: white; }
        .status-Approved { background-color: #5cb85c; color: white; }
        .status-Rejected { background-color: #d9534f; color: white; }
        .status-Draft { background-color: #777; color: white; }
    </style>
</head>
<body>
<div class="form-card">
    <h3>
        <?php echo $report_id_to_edit > 0 ? 'Edit Draft Activity Report' : 'Create New Monthly Activity Report'; ?>
        (Employee ID: <?php echo htmlspecialchars($user_id); ?>)
    </h3>
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=create_activity_report" method="post" id="activity_form">
        <?php if ($report_id_to_edit > 0) : ?>
            <input type="hidden" name="report_id" value="<?php echo htmlspecialchars($report_id_to_edit); ?>">
        <?php endif; ?>

        <div style="display: flex; gap: 20px; margin-bottom: 20px;">
            <div style="flex: 1;">
                <label for="report_date">SELECT DATE * <i class="fas fa-calendar-day"></i></label>
                <input type="date" name="report_date" id="report_date"
                       value="<?php echo htmlspecialchars($current_report_data['report_month'] ?? $default_date); ?>" 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
                    $selected_supervisor = $current_report_data['supervisor_user_id'] ?? '';
                    foreach ($users as $id => $username) {
                        $selected = ($id == $selected_supervisor) ? 'selected' : '';
                        echo '<option value="' . htmlspecialchars($id) . '" ' . $selected . '>'
                           . htmlspecialchars($username)
                           . '</option>';
                    }
                    ?>
                </select>
            </div>
        </div>

        <label for="title">TITLE *</label>
        <input type="text" name="title" id="title" required placeholder="Project Status Update for the day"
               value="<?php echo htmlspecialchars($current_report_data['title'] ?? ''); ?>">

        <label for="activity_description">ACTIVITY DESCRIPTION *</label>
        <textarea name="activity_description" id="activity_description" rows="6" required placeholder="Detailed list of activities completed today..."><?php echo htmlspecialchars($current_report_data['activity_description'] ?? ''); ?></textarea>

        <div style="display: flex; gap: 10px; margin-top: 20px; justify-content: flex-start;">

            <button type="submit" name="submit_report" class="btn-submit">
                <i class="fas fa-check"></i> Submit
            </button>

            <button type="submit" name="save_draft" class="btn-draft">
                <i class="fas fa-save"></i> Draft
            </button>

            <button type="reset" class="btn-cancel">
                <i class="fas fa-times"></i> Cancel
            </button>
        </div>
    </form>

    <hr style="margin-top: 30px; border-top: 1px solid #ecf0f1;">

    <h3 style="margin-top: 25px;">
        <i class="fas fa-file-alt"></i> My Draft Reports (<?php echo count($draft_reports); ?>)
    </h3>
    <?php if (empty($draft_reports)) : ?>
        <div class='alert alert-info' style='background-color: #d9edf7; color: #31708f;'>You have no saved draft reports.</div>
    <?php else : ?>
        <table class="report-table">
            <thead>
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Title</th>
                <th>Saved Date</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($draft_reports as $report) : ?>
                <tr>
                    <td><?php echo htmlspecialchars($report['report_id']); ?></td>
                    <td><?php echo htmlspecialchars(date('Y-m-d', strtotime($report['report_month']))); ?></td>
                    <td><?php echo htmlspecialchars($report['title']); ?></td>
                    <td><?php echo date('Y-m-d H:i', strtotime($report['submission_date'])); ?></td>
                    <td>
                        <a href="admin_dashboard.php?page=create_activity_report&edit_id=<?php echo $report['report_id']; ?>">
                            <button type="button" class="btn-edit"><i class="fas fa-edit"></i> Edit</button>
                        </a>
                        <a href="admin_dashboard.php?page=create_activity_report&delete_id=<?php echo $report['report_id']; ?>"
                           onclick="return confirm('Are you sure you want to delete this draft?');">
                            <button type="button" class="btn-delete"><i class="fas fa-trash"></i> Delete</button>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <hr style="margin-top: 30px; border-top: 1px solid #ecf0f1;">

    <h3 style="margin-top: 25px;">
        <i class="fas fa-paper-plane"></i> My Submitted Reports (<?php echo count($submitted_reports); ?>)
    </h3>
    <?php if (empty($submitted_reports)) : ?>
        <div class='alert alert-info' style='background-color: #d9edf7; color: #31708f;'>You have not submitted any reports yet.</div>
    <?php else : ?>
        <table class="report-table">
            <thead>
            <tr>
                <th>ID</th>
                <th>Date</th>
                <th>Title</th>
                <th>Supervisor</th>
                <th>Status</th>
                <th>Status Date</th>
                <th>Action</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($submitted_reports as $report) : ?>
                <tr id="report-row-<?php echo htmlspecialchars($report['report_id']); ?>">
                    <td><?php echo htmlspecialchars($report['report_id']); ?></td>
                    <td><?php echo htmlspecialchars(date('Y-m-d', strtotime($report['report_month']))); ?></td>
                    <td><?php echo htmlspecialchars($report['title']); ?></td>
                    <td><?php echo htmlspecialchars($users[$report['supervisor_user_id']] ?? 'N/A'); ?></td>
                    <td>
                        <span class="status-badge status-<?php echo htmlspecialchars($report['status']); ?>">
                            <?php echo htmlspecialchars($report['status']); ?>
                        </span>
                    </td>
                    <td><?php echo $report['status_date'] ? date('Y-m-d', strtotime($report['status_date'])) : 'N/A'; ?></td>
                    <td>
                        <button type="button" class="btn-view" data-bs-toggle="modal" data-bs-target="#viewReportModal"
                            data-report-id="<?php echo htmlspecialchars($report['report_id']); ?>"
                            data-title="<?php echo htmlspecialchars($report['title']); ?>"
							data-activity-description="<?php echo htmlspecialchars($report['activity_description'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                            data-date="<?php echo htmlspecialchars(date('Y-m-d', strtotime($report['report_month']))); ?>"
                            data-supervisor="<?php echo htmlspecialchars($users[$report['supervisor_user_id']] ?? 'N/A'); ?>"
                            data-status="<?php echo htmlspecialchars($report['status']); ?>"
                            data-feedback="<?php echo urlencode($report['supervisor_feedback'] ?? 'No feedback provided yet.'); ?>">
                            <i class="fas fa-eye"></i> View
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<div class="modal fade" id="viewReportModal" tabindex="-1" aria-labelledby="viewReportModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewReportModalLabel">Activity Report Details (<span id="modalReportID"></span>)</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p><strong>Date:</strong> <span id="modalDate"></span></p>
                <p><strong>Supervisor:</strong> <span id="modalSupervisor"></span></p>
                <p><strong>Status:</strong> <span id="modalStatus"></span></p>
                <hr>
                <h5><i class="fas fa-heading"></i> Report Title</h5>
                <p id="modalTitle"></p>
                <h5><i class="fas fa-list-alt"></i> Activity Description</h5>
                <p id="modalActivityDescription"></p> <hr>
                <h5><i class="fas fa-comment-dots"></i> Supervisor Feedback</h5>
                <p id="modalFeedback" class="text-muted"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
    $(document).ready(function() {
        // Event listener for when the modal is about to be shown
        $('#viewReportModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget); // Button that triggered the modal
            
            // Extract info from data-* attributes
            var reportId = button.data('report-id');
            var title = button.data('title');
            // VERIFIED: data attribute name
            var descriptionEncoded = button.data('activity-description'); 
            var date = button.data('date');
            var supervisor = button.data('supervisor');
            var status = button.data('status');
            var feedbackEncoded = button.data('feedback');

            // URL-decode the string before displaying it
			var description = button.data('activity-description');
            var feedback = decodeURIComponent(feedbackEncoded);

            // Update the modal's content.
            var modal = $(this);
            modal.find('#modalReportID').text('ID: ' + reportId);
            modal.find('#modalDate').text(date);
            modal.find('#modalSupervisor').text(supervisor);
            modal.find('#modalTitle').text(title);
            
            // Use .html() and replace line breaks with <br> for proper formatting
            // VERIFIED: Target new element ID
            modal.find('#modalActivityDescription').html(description.replace(/\n/g, '<br>'));
            
            modal.find('#modalFeedback').text(feedback);
            
            // Set up status badge
            var statusBadge = `<span class="status-badge status-${status}">${status}</span>`;
            modal.find('#modalStatus').html(statusBadge);
        });
    });
</script>
</body>
</html>