<?php
// Start session and include necessary files
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/Contactus.php'; // This class handles dsps_tbl_feedback

// Redirect if not logged in or not a DAC Staff
redirect_if_not_logged_in('../index.php');
redirect_if_not_role('DAC Staff', '../index.php');

// Initialize Contactus class (for feedback management)
$contactUs = new Contactus($pdo);

$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? null;

// Handle form submissions for responding to feedback
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action_type = $_POST['action_type'] ?? ''; // 'respond' or 'delete'
    $feedback_id = $_POST['feedback_id'] ?? null;
    $respond_text = trim($_POST['respond_text'] ?? '');
    $status = $_POST['status'] ?? 'New'; // Default status for response

    if ($action_type === 'respond') {
        if (empty($respond_text)) {
            set_message('Response text cannot be empty.', 'danger');
        } elseif ($feedback_id) {
            try {
                $contactUs->respondToFeedback($feedback_id, $respond_text, $status, $_SESSION['user_id']);
                set_message('Feedback responded to successfully!', 'success');
            } catch (Exception $e) {
                set_message('Error responding to feedback: ' . $e->getMessage(), 'danger');
            }
        }
    } elseif ($action_type === 'delete') {
        if ($feedback_id) {
            try {
                $contactUs->deleteFeedback($feedback_id);
                set_message('Feedback deleted successfully!', 'success');
            } catch (Exception $e) {
                set_message('Error deleting feedback: ' . $e->getMessage(), 'danger');
            }
        }
    }
    header('Location: manage_contactus.php');
    exit();
}

// Fetch feedback entries for display
$feedbackEntries = $contactUs->getAllFeedback();

// Prepare data for responding if action is 'respond'
$respondFeedback = null;
if ($action === 'respond' && $id) {
    $respondFeedback = $contactUs->getFeedbackById($id);
}
?>

<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_admin.php");
?>
<body>
    <div class="wrapper">

        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_admin.php");
        ?>

        <!-- Main Content -->
        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded-3">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Manage Contact Us (Feedback)</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php
            // Display session messages
            if (isset($_SESSION['message'])) {
                echo '<div class="alert alert-' . $_SESSION['message_type'] . ' alert-dismissible fade show rounded" role="alert">' . htmlspecialchars($_SESSION['message']) . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
                unset($_SESSION['message']);
                unset($_SESSION['message_type']);
            }
            ?>

            <?php if ($respondFeedback): ?>
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">Respond to Feedback #<?php echo htmlspecialchars($respondFeedback['pkdspsfb_id']); ?></h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <strong>From:</strong> <?php echo htmlspecialchars($respondFeedback['dspsfb_name']); ?> (<?php echo htmlspecialchars($respondFeedback['dspsfb_email']); ?>)
                    </div>
                    <div class="mb-3">
                        <strong>Submitted On:</strong> <?php echo htmlspecialchars($respondFeedback['dspsfb_reg_datetime']); ?>
                    </div>
                    <div class="mb-3">
                        <strong>Message:</strong>
                        <p class="border p-3 rounded-3 bg-light"><?php echo nl2br(htmlspecialchars($respondFeedback['dspsfb_body_text'])); ?></p>
                    </div>
                    <?php if (!empty($respondFeedback['dspsfb_respond_text'])): ?>
                    <div class="mb-3">
                        <strong>Previous Response:</strong>
                        <p class="border p-3 rounded-3 bg-light text-muted"><?php echo nl2br(htmlspecialchars($respondFeedback['dspsfb_respond_text'])); ?></p>
                    </div>
                    <?php endif; ?>

                    <form action="manage_contactus.php" method="POST">
                        <input type="hidden" name="action_type" value="respond">
                        <input type="hidden" name="feedback_id" value="<?php echo htmlspecialchars($respondFeedback['pkdspsfb_id']); ?>">

                        <div class="mb-3">
                            <label for="respond_text" class="form-label">Your Response</label>
                            <textarea class="form-control rounded-3" id="respond_text" name="respond_text" rows="5" required><?php echo htmlspecialchars($respondFeedback['dspsfb_respond_text'] ?? ''); ?></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select rounded" id="status" name="status" required>
                                <option value="New" <?php echo ($respondFeedback['dspsfb_status'] == 'New') ? 'selected' : ''; ?>>New</option>
                                <option value="In Progress" <?php echo ($respondFeedback['dspsfb_status'] == 'In Progress') ? 'selected' : ''; ?>>In Progress</option>
                                <option value="Resolved" <?php echo ($respondFeedback['dspsfb_status'] == 'Resolved') ? 'selected' : ''; ?>>Resolved</option>
                                <option value="Archived" <?php echo ($respondFeedback['dspsfb_status'] == 'Archived') ? 'selected' : ''; ?>>Archived</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary rounded">
                            <i class="fas fa-reply me-2"></i> Send Response
                        </button>
                        <a href="manage_contactus.php" class="btn btn-secondary rounded ms-2">Cancel</a>
                    </form>
                </div>
            </div>
            <?php endif; ?>

            <div class="card">
                <div class="card-header text-white" style="background-color: #28a745;">
                    <h5 class="mb-0">All Feedback Messages</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Message</th>
                                    <th>Status</th>
                                    <th>Submitted On</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($feedbackEntries)): ?>
                                    <?php foreach ($feedbackEntries as $feedback): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($feedback['pkdspsfb_id']); ?></td>
                                            <td><?php echo htmlspecialchars($feedback['dspsfb_name']); ?></td>
                                            <td><?php echo htmlspecialchars($feedback['dspsfb_email']); ?></td>
                                            <td><?php echo htmlspecialchars(substr($feedback['dspsfb_body_text'], 0, 100)) . (strlen($feedback['dspsfb_body_text']) > 100 ? '...' : ''); ?></td>
                                            <td><span class="badge bg-<?php
                                                if ($feedback['dspsfb_status'] == 'New') echo 'danger';
                                                else if ($feedback['dspsfb_status'] == 'In Progress') echo 'warning';
                                                else if ($feedback['dspsfb_status'] == 'Resolved') echo 'success';
                                                else echo 'secondary';
                                            ?>"><?php echo htmlspecialchars($feedback['dspsfb_status']); ?></span></td>
                                            <td><?php echo htmlspecialchars($feedback['dspsfb_reg_datetime']); ?></td>
                                            <td>
                                                <a href="manage_contactus.php?action=respond&id=<?php echo htmlspecialchars($feedback['pkdspsfb_id']); ?>" class="btn btn-sm btn-primary rounded btn-action">
                                                    <i class="fas fa-reply"></i> Respond
                                                </a>
                                                <form action="manage_contactus.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this feedback?');">
                                                    <input type="hidden" name="action_type" value="delete">
                                                    <input type="hidden" name="feedback_id" value="<?php echo htmlspecialchars($feedback['pkdspsfb_id']); ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger rounded btn-action">
                                                        <i class="fas fa-trash-alt"></i> Delete
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" class="text-center">No feedback messages found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <?php
    // Include Footer file for owner pages
    include_once("../includes/footer_admin.php");
    ?>  
</body>
</html>
