<?php 
session_start();
include('includes/head.php');

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// PIN for confirmation
$admin_pin = "1234"; // Change this to a secure PIN

// Handle actions
$action = isset($_GET['action']) ? $_GET['action'] : '';
$feedback_id = isset($_GET['id']) ? intval($_GET['feedback_id']) : 0;

// Status colors
$status_colors = array(
    'new' => 'warning',
    'reviewed' => 'info',
    'actioned' => 'success'
);

// Type colors
$type_colors = array(
    'general' => 'primary',
    'complaint' => 'danger',
    'suggestion' => 'info',
    'dispute' => 'warning'
);

// Rating stars
$rating_stars = array(
    1 => '★☆☆☆☆',
    2 => '★★☆☆☆',
    3 => '★★★☆☆',
    4 => '★★★★☆',
    5 => '★★★★★'
);

// Rating colors
$rating_colors = array(
    1 => 'danger',
    2 => 'warning',
    3 => 'info',
    4 => 'primary',
    5 => 'success'
);

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    $target_id = isset($_POST['feedback_id']) ? intval($_POST['feedback_id']) : 0;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'update_status':
                $new_status = isset($_POST['status']) ? $_POST['status'] : '';
                $admin_note = isset($_POST['admin_note']) ? mysqli_real_escape_string($conn, $_POST['admin_note']) : '';
                
                if ($target_id > 0 && in_array($new_status, ['new', 'reviewed', 'actioned'])) {
                    $sql = "UPDATE feedback SET status = '$new_status', updated_at = NOW() WHERE id = $target_id";
                    if (mysqli_query($conn, $sql)) {
                        // Add admin response if provided
                        if ($admin_note) {
                            $response_sql = "INSERT INTO feedback_responses (feedback_id, admin_id, admin_name, response, created_at) 
                                           VALUES ($target_id, $admin_id, '$admin_name', '$admin_note', NOW())";
                            mysqli_query($conn, $response_sql);
                        }
                        
                        // Log activity
                        logAdminActivity(
                            'Feedback Status Updated',
                            "Updated feedback ID $target_id status to $new_status",
                            'Feedback',
                            $target_id,
                            'feedback'
                        );
                        
                        $success = "Feedback status updated successfully!";
                    } else {
                        $error = "Failed to update feedback status.";
                    }
                }
                break;
                
            case 'add_response':
                $response = isset($_POST['response']) ? mysqli_real_escape_string($conn, $_POST['response']) : '';
                $send_email = isset($_POST['send_email']) ? 1 : 0;
                
                if ($target_id > 0 && $response) {
                    $sql = "INSERT INTO feedback_responses (feedback_id, admin_id, admin_name, response, send_email, created_at) 
                           VALUES ($target_id, $admin_id, '$admin_name', '$response', $send_email, NOW())";
                    
                    if (mysqli_query($conn, $sql)) {
                        // Update feedback status if still new
                        $update_sql = "UPDATE feedback SET status = 'reviewed', updated_at = NOW() WHERE id = $target_id AND status = 'new'";
                        mysqli_query($conn, $update_sql);
                        
                        // Log activity
                        logAdminActivity(
                            'Feedback Response Added',
                            "Added response to feedback ID $target_id",
                            'Feedback',
                            $target_id,
                            'feedback'
                        );
                        
                        $success = "Response added successfully!";
                    } else {
                        $error = "Failed to add response.";
                    }
                }
                break;
                
            case 'delete_feedback':
                if ($target_id > 0) {
                    // Get feedback info before deletion
                    $feedback_sql = "SELECT subject FROM feedback WHERE id = $target_id";
                    $feedback_result = mysqli_query($conn, $feedback_sql);
                    $feedback_data = mysqli_fetch_assoc($feedback_result);
                    $subject = $feedback_data['subject'] ?: '';
                    
                    // Delete feedback
                    $sql = "DELETE FROM feedback WHERE id = $target_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        // Also delete responses
                        $delete_responses = "DELETE FROM feedback_responses WHERE feedback_id = $target_id";
                        mysqli_query($conn, $delete_responses);
                        
                        // Log activity
                        logAdminActivity(
                            'Feedback Deleted',
                            "Deleted feedback: $subject",
                            'Feedback',
                            $target_id,
                            'feedback'
                        );
                        
                        $success = "Feedback has been deleted successfully!";
                    } else {
                        $error = "Failed to delete feedback.";
                    }
                }
                break;
        }
    }
}

// Get filter parameters
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
$filter_rating = isset($_GET['rating']) ? intval($_GET['rating']) : 0;
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build query
$sql = "SELECT f.*, u.username, u.email 
        FROM feedback f 
        LEFT JOIN users u ON f.user_id = u.id 
        WHERE 1=1";
$count_sql = "SELECT COUNT(*) as total FROM feedback f WHERE 1=1";

// Apply filters
if ($filter_status) {
    $sql .= " AND f.status = '$filter_status'";
    $count_sql .= " AND f.status = '$filter_status'";
}

if ($filter_type) {
    $sql .= " AND f.type = '$filter_type'";
    $count_sql .= " AND f.type = '$filter_type'";
}

if ($filter_rating > 0) {
    $sql .= " AND f.rating = $filter_rating";
    $count_sql .= " AND f.rating = $filter_rating";
}

if ($search) {
    $sql .= " AND (f.subject LIKE '%$search%' OR f.message LIKE '%$search%' OR u.username LIKE '%$search%' OR u.email LIKE '%$search%')";
    $count_sql .= " AND (f.subject LIKE '%$search%' OR f.message LIKE '%$search%')";
}

if ($date_from) {
    $sql .= " AND DATE(f.created_at) >= '$date_from'";
    $count_sql .= " AND DATE(f.created_at) >= '$date_from'";
}

if ($date_to) {
    $sql .= " AND DATE(f.created_at) <= '$date_to'";
    $count_sql .= " AND DATE(f.created_at) <= '$date_to'";
}

// Get counts for stats
$stats_sql = "SELECT 
    SUM(CASE WHEN status = 'new' THEN 1 ELSE 0 END) as new_count,
    SUM(CASE WHEN status = 'reviewed' THEN 1 ELSE 0 END) as reviewed_count,
    SUM(CASE WHEN status = 'actioned' THEN 1 ELSE 0 END) as actioned_count,
    COUNT(*) as total_count,
    AVG(rating) as avg_rating
    FROM feedback";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Add sorting
$sql .= " ORDER BY f.created_at DESC";

// Execute query
$result = mysqli_query($conn, $sql);
?>

<!DOCTYPE html>
<html lang="en">
  	
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-comment-dots me-2"></i>Feedback Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#statsModal">
												<i class="fas fa-chart-bar me-1"></i> View Stats
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['new_count'] ?: 0; ?></h1>
														<p class="text-white mb-0">New Feedback</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['reviewed_count'] ?: 0; ?></h1>
														<p class="text-white mb-0">Reviewed</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['actioned_count'] ?: 0; ?></h1>
														<p class="text-white mb-0">Actioned</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo number_format($stats['avg_rating'] ?: 0, 1); ?>/5</h1>
														<p class="text-white mb-0">Average Rating</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row">
													<div class="col-md-2">
														<div class="form-group">
															<select class="form-control" name="status">
																<option value="">All Status</option>
																<option value="new" <?php echo $filter_status == 'new' ? 'selected' : ''; ?>>New</option>
																<option value="reviewed" <?php echo $filter_status == 'reviewed' ? 'selected' : ''; ?>>Reviewed</option>
																<option value="actioned" <?php echo $filter_status == 'actioned' ? 'selected' : ''; ?>>Actioned</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<select class="form-control" name="type">
																<option value="">All Types</option>
																<option value="general" <?php echo $filter_type == 'general' ? 'selected' : ''; ?>>General</option>
																<option value="complaint" <?php echo $filter_type == 'complaint' ? 'selected' : ''; ?>>Complaint</option>
																<option value="suggestion" <?php echo $filter_type == 'suggestion' ? 'selected' : ''; ?>>Suggestion</option>
																<option value="dispute" <?php echo $filter_type == 'dispute' ? 'selected' : ''; ?>>Dispute</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<select class="form-control" name="rating">
																<option value="0">All Ratings</option>
																<option value="1" <?php echo $filter_rating == 1 ? 'selected' : ''; ?>>1 Star</option>
																<option value="2" <?php echo $filter_rating == 2 ? 'selected' : ''; ?>>2 Stars</option>
																<option value="3" <?php echo $filter_rating == 3 ? 'selected' : ''; ?>>3 Stars</option>
																<option value="4" <?php echo $filter_rating == 4 ? 'selected' : ''; ?>>4 Stars</option>
																<option value="5" <?php echo $filter_rating == 5 ? 'selected' : ''; ?>>5 Stars</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>" placeholder="From Date">
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>" placeholder="To Date">
														</div>
													</div>
													<div class="col-md-2">
														<button type="submit" class="btn btn-primary"><i class="fas fa-filter me-1"></i> Filter</button>
														<?php if ($filter_status || $filter_type || $filter_rating || $search || $date_from || $date_to): ?>
															<a href="feedback.php" class="btn btn-secondary">Clear</a>
														<?php endif; ?>
													</div>
												</form>
											</div>
											<div class="col-md-12 mt-3">
												<form method="GET" class="row">
													<div class="col-md-10">
														<div class="form-group">
															<input type="text" class="form-control" name="search" placeholder="Search feedback by subject, message, or user..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-2">
														<button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Search</button>
													</div>
												</form>
											</div>
										</div>
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Feedback Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="feedbackTable">
												<thead class="bg-light">
													<tr>
														<th width="50">ID</th>
														<th>User / Subject</th>
														<th width="100">Type</th>
														<th width="120">Rating</th>
														<th width="100">Status</th>
														<th width="150">Date</th>
														<th width="100">Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($feedback = mysqli_fetch_assoc($result)): ?>
															<?php
															$status_color = isset($status_colors[$feedback['status']]) ? $status_colors[$feedback['status']] : 'secondary';
															$type_color = isset($type_colors[$feedback['type']]) ? $type_colors[$feedback['type']] : 'secondary';
															$rating_color = isset($rating_colors[$feedback['rating']]) ? $rating_colors[$feedback['rating']] : 'secondary';
															$rating_star = isset($rating_stars[$feedback['rating']]) ? $rating_stars[$feedback['rating']] : 'N/A';
															$created_date = date('M d, Y H:i', strtotime($feedback['created_at']));
															$message_preview = strlen($feedback['message']) > 100 ? substr($feedback['message'], 0, 100) . '...' : $feedback['message'];
															?>
															<tr>
																<td><?php echo $feedback['id']; ?></td>
																<td>
																	<div class="d-flex align-items-start">
																		<div class="me-10">
																			<div class="bg-<?php echo $type_color; ?> rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																				<i class="fas fa-comment text-white"></i>
																			</div>
																		</div>
																		<div>
																			<p class="mb-0 fw-500"><?php echo htmlspecialchars($feedback['subject']); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($message_preview); ?></small>
																			<?php if ($feedback['username']): ?>
																				<p class="mb-0 mt-1"><small><i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($feedback['username']); ?> (<?php echo htmlspecialchars($feedback['email']); ?>)</small></p>
																			<?php else: ?>
																				<p class="mb-0 mt-1"><small><i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($feedback['name']); ?> (<?php echo htmlspecialchars($feedback['email']); ?>)</small></p>
																			<?php endif; ?>
																		</div>
																	</div>
																</td>
																<td>
																	<span class="badge bg-<?php echo $type_color; ?>"><?php echo ucfirst($feedback['type']); ?></span>
																</td>
																<td>
																	<?php if ($feedback['rating']): ?>
																		<div class="text-center">
																			<div class="text-<?php echo $rating_color; ?> fw-bold"><?php echo $rating_star; ?></div>
																			<small class="text-mute"><?php echo $feedback['rating']; ?>/5</small>
																		</div>
																	<?php else: ?>
																		<span class="badge bg-secondary">No Rating</span>
																	<?php endif; ?>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($feedback['status']); ?></span>
																</td>
																<td>
																	<small><?php echo $created_date; ?></small>
																</td>
																<td>
																	<div class="btn-group">
																		<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																			<i class="fas fa-cog"></i>
																		</button>
																		<div class="dropdown-menu">
																			<a class="dropdown-item view-feedback" href="#" data-bs-toggle="modal" data-bs-target="#viewModal" data-id="<?php echo $feedback['id']; ?>">
																				<i class="fas fa-eye me-2"></i> View Details
																			</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#statusModal" data-id="<?php echo $feedback['id']; ?>" data-status="<?php echo $feedback['status']; ?>">
																				<i class="fas fa-edit me-2"></i> Change Status
																			</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#responseModal" data-id="<?php echo $feedback['id']; ?>">
																				<i class="fas fa-reply me-2"></i> Add Response
																			</a>
																			<div class="dropdown-divider"></div>
																			<a class="dropdown-item text-danger delete-feedback" href="#" data-id="<?php echo $feedback['id']; ?>" data-subject="<?php echo htmlspecialchars($feedback['subject']); ?>">
																				<i class="fas fa-trash me-2"></i> Delete
																			</a>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="7" class="text-center py-20">
																<i class="fas fa-comment-slash fa-2x text-mute mb-3"></i>
																<h5>No feedback found</h5>
																<p class="text-mute">Try adjusting your search or filters</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Export Buttons -->
										<div class="row mt-20">
											<div class="col-md-12 text-end">
												<div class="btn-group">
													<button type="button" class="btn btn-light dropdown-toggle" data-bs-toggle="dropdown">
														<i class="fas fa-download me-1"></i> Export
													</button>
													<div class="dropdown-menu dropdown-menu-end">
														<a class="dropdown-item" href="export_feedback.php?format=csv&status=<?php echo $filter_status; ?>&type=<?php echo $filter_type; ?>&rating=<?php echo $filter_rating; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
															<i class="fas fa-file-csv"></i> CSV
														</a>
														<a class="dropdown-item" href="export_feedback.php?format=excel&status=<?php echo $filter_status; ?>&type=<?php echo $filter_type; ?>&rating=<?php echo $filter_rating; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
															<i class="fas fa-file-excel"></i> Excel
														</a>
														<a class="dropdown-item" href="export_feedback.php?format=pdf&status=<?php echo $filter_status; ?>&type=<?php echo $filter_type; ?>&rating=<?php echo $filter_rating; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
															<i class="fas fa-file-pdf"></i> PDF
														</a>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Viewing Feedback Details -->
		<div class="modal fade" id="viewModal" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="viewModalLabel">Feedback Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="feedbackDetails">
						<!-- Details will be loaded via JavaScript -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Changing Status -->
		<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="statusModalLabel">Change Feedback Status</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="update_status">
							<input type="hidden" name="feedback_id" id="statusFeedbackId">
							
							<div class="mb-3">
								<label class="form-label">New Status</label>
								<select class="form-control" name="status" required>
									<option value="new">New</option>
									<option value="reviewed">Reviewed</option>
									<option value="actioned">Actioned</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin Note (Optional)</label>
								<textarea class="form-control" name="admin_note" rows="3" placeholder="Add any notes about this status change..."></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Update Status</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Adding Response -->
		<div class="modal fade" id="responseModal" tabindex="-1" aria-labelledby="responseModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="responseModalLabel">Add Response to Feedback</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="add_response">
							<input type="hidden" name="feedback_id" id="responseFeedbackId">
							
							<div class="mb-3">
								<label class="form-label">Your Response <span class="text-danger">*</span></label>
								<textarea class="form-control" name="response" rows="6" placeholder="Enter your response to the user..." required></textarea>
								<small class="text-mute">This response will be recorded and can be sent to the user via email.</small>
							</div>
							
							<div class="mb-3">
								<div class="form-check">
									<input class="form-check-input" type="checkbox" name="send_email" id="sendEmail" value="1" checked>
									<label class="form-check-label" for="sendEmail">
										Send response via email to user
									</label>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Add Response</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Statistics -->
		<div class="modal fade" id="statsModal" tabindex="-1" aria-labelledby="statsModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="statsModalLabel">Feedback Statistics</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body">
						<div class="row">
							<div class="col-md-6">
								<div class="box mb-3">
									<div class="box-header">
										<h6 class="box-title">Status Distribution</h6>
									</div>
									<div class="box-body">
										<?php
										$status_stats_sql = "SELECT status, COUNT(*) as count FROM feedback GROUP BY status";
										$status_stats_result = mysqli_query($conn, $status_stats_sql);
										?>
										<table class="table table-sm">
											<thead>
												<tr>
													<th>Status</th>
													<th>Count</th>
													<th>Percentage</th>
												</tr>
											</thead>
											<tbody>
												<?php while ($status = mysqli_fetch_assoc($status_stats_result)): ?>
													<?php
													$percentage = $stats['total_count'] > 0 ? round(($status['count'] / $stats['total_count']) * 100, 1) : 0;
													$color = $status_colors[$status['status']] ?: 'secondary';
													?>
													<tr>
														<td><span class="badge bg-<?php echo $color; ?>"><?php echo ucfirst($status['status']); ?></span></td>
														<td><?php echo $status['count']; ?></td>
														<td>
															<div class="progress" style="height: 20px;">
																<div class="progress-bar bg-<?php echo $color; ?>" role="progressbar" style="width: <?php echo $percentage; ?>%">
																	<?php echo $percentage; ?>%
																</div>
															</div>
														</td>
													</tr>
												<?php endwhile; ?>
											</tbody>
										</table>
									</div>
								</div>
							</div>
							
							<div class="col-md-6">
								<div class="box mb-3">
									<div class="box-header">
										<h6 class="box-title">Type Distribution</h6>
									</div>
									<div class="box-body">
										<?php
										$type_stats_sql = "SELECT type, COUNT(*) as count FROM feedback GROUP BY type";
										$type_stats_result = mysqli_query($conn, $type_stats_sql);
										?>
										<table class="table table-sm">
											<thead>
												<tr>
													<th>Type</th>
													<th>Count</th>
													<th>Percentage</th>
												</tr>
											</thead>
											<tbody>
												<?php while ($type = mysqli_fetch_assoc($type_stats_result)): ?>
													<?php
													$percentage = $stats['total_count'] > 0 ? round(($type['count'] / $stats['total_count']) * 100, 1) : 0;
													$color = $type_colors[$type['type']] ?: 'secondary';
													?>
													<tr>
														<td><span class="badge bg-<?php echo $color; ?>"><?php echo ucfirst($type['type']); ?></span></td>
														<td><?php echo $type['count']; ?></td>
														<td>
															<div class="progress" style="height: 20px;">
																<div class="progress-bar bg-<?php echo $color; ?>" role="progressbar" style="width: <?php echo $percentage; ?>%">
																	<?php echo $percentage; ?>%
																</div>
															</div>
														</td>
													</tr>
												<?php endwhile; ?>
											</tbody>
										</table>
									</div>
								</div>
							</div>
						</div>
						
						<div class="row">
							<div class="col-md-12">
								<div class="box">
									<div class="box-header">
										<h6 class="box-title">Rating Distribution</h6>
									</div>
									<div class="box-body">
										<?php
										$rating_stats_sql = "SELECT rating, COUNT(*) as count FROM feedback WHERE rating > 0 GROUP BY rating ORDER BY rating DESC";
										$rating_stats_result = mysqli_query($conn, $rating_stats_sql);
										?>
										<div class="row">
											<?php while ($rating = mysqli_fetch_assoc($rating_stats_result)): ?>
												<?php
												$percentage = $stats['total_count'] > 0 ? round(($rating['count'] / $stats['total_count']) * 100, 1) : 0;
												$color = $rating_colors[$rating['rating']] ?: 'secondary';
												$stars = str_repeat('★', $rating['rating']) . str_repeat('☆', 5 - $rating['rating']);
												?>
												<div class="col-md-4 mb-3">
													<div class="text-center p-3 bg-light rounded">
														<h3 class="text-<?php echo $color; ?>"><?php echo $stars; ?></h3>
														<h4 class="fw-500"><?php echo $rating['count']; ?></h4>
														<p class="mb-0"><?php echo $percentage; ?>% of total</p>
													</div>
												</div>
											<?php endwhile; ?>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Hidden form for delete -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_feedback">
			<input type="hidden" name="feedback_id" id="deleteFeedbackId">
			<input type="hidden" name="admin_pin" id="deletePin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<!-- DataTables -->
		<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
		<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#feedbackTable').DataTable({
				"pageLength": 25,
				"order": [[0, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Status Modal
			$('#statusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var feedbackId = button.data('id');
				var currentStatus = button.data('status');
				var modal = $(this);
				
				modal.find('#statusFeedbackId').val(feedbackId);
				modal.find('select[name="status"]').val(currentStatus);
				modal.find('.modal-title').text('Change Status for Feedback #' + feedbackId);
			});
			
			// Response Modal
			$('#responseModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var feedbackId = button.data('id');
				var modal = $(this);
				
				modal.find('#responseFeedbackId').val(feedbackId);
				modal.find('.modal-title').text('Add Response to Feedback #' + feedbackId);
			});
			
			// View Feedback Details
			$('.view-feedback').click(function() {
				var feedbackId = $(this).data('id');
				
				// Show loading
				$('#feedbackDetails').html('<div class="text-center py-5"><i class="fas fa-spinner fa-spin fa-2x"></i><p>Loading...</p></div>');
				
				// Load feedback details
				$.ajax({
					url: 'ajax/get_feedback_details.php',
					type: 'GET',
					data: { id: feedbackId },
					success: function(data) {
						$('#feedbackDetails').html(data);
					},
					error: function() {
						$('#feedbackDetails').html('<div class="alert alert-danger">Failed to load feedback details.</div>');
					}
				});
			});
			
			// Delete Feedback
			$('.delete-feedback').click(function(e) {
				e.preventDefault();
				var feedbackId = $(this).data('id');
				var subject = $(this).data('subject');
				
				confirmDelete(feedbackId, subject);
			});
			
			// Auto-refresh stats every 30 seconds
			setInterval(function() {
				refreshFeedbackStats();
			}, 30000); // 30 seconds
		});
		
		// Refresh Feedback Stats
		function refreshFeedbackStats() {
			$.ajax({
				url: 'ajax/get_feedback_stats.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update the stat cards
						$('.bg-gradient-warning .fw-500').text(stats.new_count);
						$('.bg-gradient-info .fw-500').text(stats.reviewed_count);
						$('.bg-gradient-success .fw-500').text(stats.actioned_count);
						$('.bg-gradient-primary .fw-500').text(stats.avg_rating);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}
		
		// Confirm Delete with PIN
		function confirmDelete(feedbackId, subject) {
			Swal.fire({
				title: 'Delete Feedback?',
				html: `
					<p>Are you sure you want to delete this feedback?</p>
					<div class="alert alert-warning">
						<strong>Subject:</strong> ${subject}
					</div>
					<p class="text-danger"><strong>Warning:</strong> This action cannot be undone.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Feedback',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the delete form
					document.getElementById('deleteFeedbackId').value = feedbackId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.feedback-message {
			white-space: pre-line;
			background-color: #f8f9fa;
			padding: 15px;
			border-radius: 5px;
			border-left: 4px solid #007bff;
		}
		.response-bubble {
			background-color: #e8f4ff;
			padding: 10px 15px;
			border-radius: 10px;
			margin-bottom: 10px;
			border-left: 4px solid #007bff;
		}
		</style>
		
	</body>
</html>