<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

session_start();
include('../include/config.php');

// Check if user is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../login.php');
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || $user['is_admin'] != 1) {
    header('Location: ../user/dashboard.php');
    exit();
}

// Handle Status Update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_status'])) {
    $request_id = (int)$_POST['request_id'];
    $status = $_POST['status'];
    $priority = $_POST['priority'];
    $admin_response = trim($_POST['admin_response']);
    
    try {
        $stmt = $pdo->prepare("
            UPDATE feature_requests 
            SET status = ?, priority = ?, admin_response = ?, updated_at = NOW() 
            WHERE id = ?
        ");
        $stmt->execute([$status, $priority, $admin_response, $request_id]);
        
        $_SESSION['success'] = "Feature request updated successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error updating request: " . $e->getMessage();
    }
    
    header('Location: manage-feature-requests.php');
    exit();
}

// Handle Delete Request
if (isset($_GET['delete'])) {
    $request_id = (int)$_GET['delete'];
    
    try {
        // Get image path before deleting
        $stmt = $pdo->prepare("SELECT image_path FROM feature_requests WHERE id = ?");
        $stmt->execute([$request_id]);
        $request = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Delete the request
        $stmt = $pdo->prepare("DELETE FROM feature_requests WHERE id = ?");
        $stmt->execute([$request_id]);
        
        // Delete associated image file if exists
        if ($request && $request['image_path'] && file_exists('../' . $request['image_path'])) {
            unlink('../' . $request['image_path']);
        }
        
        $_SESSION['success'] = "Feature request deleted successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error deleting request!";
    }
    
    header('Location: manage-feature-requests.php');
    exit();
}

// Pagination and filtering
$records_per_page = 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// Status filter
$status_filter = isset($_GET['status']) && !empty($_GET['status']) ? $_GET['status'] : null;
$priority_filter = isset($_GET['priority']) && !empty($_GET['priority']) ? $_GET['priority'] : null;

// Build query
$where_conditions = [];
$params = [];

if ($status_filter) {
    $where_conditions[] = "status = ?";
    $params[] = $status_filter;
}

if ($priority_filter) {
    $where_conditions[] = "priority = ?";
    $params[] = $priority_filter;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$count_query = "SELECT COUNT(*) FROM feature_requests $where_clause";
$count_stmt = $pdo->prepare($count_query);
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $records_per_page);

// Fetch requests
$query = "SELECT * FROM feature_requests $where_clause ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($query);

// Bind parameters with explicit types
if (!empty($where_conditions)) {
    $param_index = 1;
    foreach ($params as $value) {
        $stmt->bindValue($param_index++, $value);
    }
}

// Bind LIMIT and OFFSET as integers
$stmt->bindValue(':limit', (int)$records_per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);

$stmt->execute();
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM feature_requests")->fetchColumn(),
    'pending' => $pdo->query("SELECT COUNT(*) FROM feature_requests WHERE status = 'pending'")->fetchColumn(),
    'under_review' => $pdo->query("SELECT COUNT(*) FROM feature_requests WHERE status = 'under_review'")->fetchColumn(),
    'in_progress' => $pdo->query("SELECT COUNT(*) FROM feature_requests WHERE status = 'in_progress'")->fetchColumn(),
    'completed' => $pdo->query("SELECT COUNT(*) FROM feature_requests WHERE status = 'completed'")->fetchColumn(),
    'rejected' => $pdo->query("SELECT COUNT(*) FROM feature_requests WHERE status = 'rejected'")->fetchColumn(),
];

// Fetch request for editing
$edit_request = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM feature_requests WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_request = $stmt->fetch(PDO::FETCH_ASSOC);
}

$page_title = WEB_NAME . " | Manage Feature Requests";
?>
<!DOCTYPE html>
<html lang="en" class="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="shortcut icon" type="image/png" href="<?php echo $site_data['web_url']; ?>/public/favicons/favicon.png">
    <style>
        .stat-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
        }
        .request-card {
            transition: all 0.3s ease;
        }
        .request-card:hover {
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen p-4 lg:p-8">

<div class="max-w-7xl mx-auto space-y-6">
    
    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-3xl font-bold text-slate-900">Manage Feature Requests</h1>
            <p class="text-slate-600 mt-1">Review and respond to user feature requests</p>
        </div>
        <a href="dashboard.php" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
            <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
        </a>
    </div>

    <!-- Alert Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="p-4 bg-green-50 border border-green-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-check-circle text-green-600 mr-3"></i>
                <span class="text-green-800 font-medium"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></span>
            </div>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="p-4 bg-red-50 border border-red-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-times-circle text-red-600 mr-3"></i>
                <span class="text-red-800 font-medium"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></span>
            </div>
        </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <div class="stat-card bg-white rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-slate-900"><?php echo $stats['total']; ?></div>
            <div class="text-sm text-slate-600 mt-1">Total</div>
        </div>
        <div class="stat-card bg-yellow-50 rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-yellow-700"><?php echo $stats['pending']; ?></div>
            <div class="text-sm text-yellow-600 mt-1">Pending</div>
        </div>
        <div class="stat-card bg-blue-50 rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-blue-700"><?php echo $stats['under_review']; ?></div>
            <div class="text-sm text-blue-600 mt-1">Under Review</div>
        </div>
        <div class="stat-card bg-purple-50 rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-purple-700"><?php echo $stats['in_progress']; ?></div>
            <div class="text-sm text-purple-600 mt-1">In Progress</div>
        </div>
        <div class="stat-card bg-green-50 rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-green-700"><?php echo $stats['completed']; ?></div>
            <div class="text-sm text-green-600 mt-1">Completed</div>
        </div>
        <div class="stat-card bg-red-50 rounded-xl shadow p-4 text-center">
            <div class="text-2xl font-bold text-red-700"><?php echo $stats['rejected']; ?></div>
            <div class="text-sm text-red-600 mt-1">Rejected</div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-4">
        <form method="GET" class="flex flex-wrap gap-3">
            <select name="status" class="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                <option value="">All Status</option>
                <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                <option value="under_review" <?php echo $status_filter == 'under_review' ? 'selected' : ''; ?>>Under Review</option>
                <option value="in_progress" <?php echo $status_filter == 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>Completed</option>
                <option value="rejected" <?php echo $status_filter == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
            </select>
            
            <select name="priority" class="px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                <option value="">All Priority</option>
                <option value="low" <?php echo $priority_filter == 'low' ? 'selected' : ''; ?>>Low</option>
                <option value="medium" <?php echo $priority_filter == 'medium' ? 'selected' : ''; ?>>Medium</option>
                <option value="high" <?php echo $priority_filter == 'high' ? 'selected' : ''; ?>>High</option>
                <option value="urgent" <?php echo $priority_filter == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
            </select>
            
            <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
                <i class="fas fa-filter mr-2"></i>Filter
            </button>
            
            <?php if ($status_filter || $priority_filter): ?>
            <a href="manage-feature-requests.php" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded-lg transition-colors">
                <i class="fas fa-times mr-2"></i>Clear
            </a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Edit Form (shown when editing) -->
    <?php if ($edit_request): ?>
    <div class="bg-white rounded-2xl shadow-lg p-6">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-xl font-bold text-slate-900">
                <i class="fas fa-edit text-blue-600 mr-2"></i>Update Request
            </h2>
            <a href="manage-feature-requests.php" class="text-slate-600 hover:text-slate-900">
                <i class="fas fa-times"></i>
            </a>
        </div>

        <form method="POST" class="space-y-6">
            <input type="hidden" name="update_status" value="1">
            <input type="hidden" name="request_id" value="<?php echo $edit_request['id']; ?>">

            <!-- User Info -->
            <div class="bg-slate-50 p-4 rounded-lg">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <div>
                        <span class="font-semibold text-slate-700">User:</span>
                        <span class="text-slate-900"><?php echo htmlspecialchars($edit_request['username']); ?></span>
                    </div>
                    <div>
                        <span class="font-semibold text-slate-700">Submitted:</span>
                        <span class="text-slate-900"><?php echo date('M d, Y H:i', strtotime($edit_request['created_at'])); ?></span>
                    </div>
                </div>
            </div>

            <!-- Feature Description -->
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Feature Description</label>
                <div class="p-4 bg-slate-50 border border-slate-200 rounded-lg text-slate-900">
                    <?php echo nl2br(htmlspecialchars($edit_request['feature_description'])); ?>
                </div>
            </div>

            <?php if ($edit_request['image_path']): ?>
            <!-- Image -->
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Attached Image</label>
                <img src="<?php echo WEBSITE_URL . '/' . $edit_request['image_path']; ?>" 
                     alt="Feature request" 
                     class="max-w-md rounded-lg border border-slate-200">
            </div>
            <?php endif; ?>

            <!-- Status and Priority -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Status *</label>
                    <select name="status" required class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        <option value="pending" <?php echo $edit_request['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="under_review" <?php echo $edit_request['status'] == 'under_review' ? 'selected' : ''; ?>>Under Review</option>
                        <option value="in_progress" <?php echo $edit_request['status'] == 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                        <option value="completed" <?php echo $edit_request['status'] == 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="rejected" <?php echo $edit_request['status'] == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Priority *</label>
                    <select name="priority" required class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        <option value="low" <?php echo $edit_request['priority'] == 'low' ? 'selected' : ''; ?>>Low</option>
                        <option value="medium" <?php echo $edit_request['priority'] == 'medium' ? 'selected' : ''; ?>>Medium</option>
                        <option value="high" <?php echo $edit_request['priority'] == 'high' ? 'selected' : ''; ?>>High</option>
                        <option value="urgent" <?php echo $edit_request['priority'] == 'urgent' ? 'selected' : ''; ?>>Urgent</option>
                    </select>
                </div>
            </div>

            <!-- Admin Response -->
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Admin Response</label>
                <textarea name="admin_response" rows="4" 
                          class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 resize-none"
                          placeholder="Add your response or notes..."><?php echo htmlspecialchars($edit_request['admin_response'] ?? ''); ?></textarea>
            </div>

            <!-- Buttons -->
            <div class="flex gap-3">
                <button type="submit" class="px-6 py-3 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold rounded-lg transition-all">
                    <i class="fas fa-save mr-2"></i>Update Request
                </button>
                <a href="manage-feature-requests.php" class="px-6 py-3 bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold rounded-lg transition-colors">
                    <i class="fas fa-times mr-2"></i>Cancel
                </a>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <!-- Requests List -->
    <div class="bg-white rounded-2xl shadow-lg p-6">
        <h2 class="text-xl font-bold text-slate-900 mb-6">
            <i class="fas fa-list text-blue-600 mr-2"></i>Feature Requests (<?php echo $total_records; ?>)
        </h2>

        <?php if (count($requests) > 0): ?>
        <div class="space-y-4">
            <?php foreach ($requests as $request): 
                $status_colors = [
                    'pending' => 'bg-yellow-100 text-yellow-800',
                    'under_review' => 'bg-blue-100 text-blue-800',
                    'in_progress' => 'bg-purple-100 text-purple-800',
                    'completed' => 'bg-green-100 text-green-800',
                    'rejected' => 'bg-red-100 text-red-800'
                ];
                
                $priority_colors = [
                    'low' => 'bg-gray-100 text-gray-700',
                    'medium' => 'bg-blue-100 text-blue-700',
                    'high' => 'bg-orange-100 text-orange-700',
                    'urgent' => 'bg-red-100 text-red-700'
                ];
            ?>
            <div class="request-card border border-slate-200 rounded-xl p-4">
                <div class="flex flex-col lg:flex-row gap-4">
                    <!-- Content -->
                    <div class="flex-1">
                        <div class="flex flex-wrap items-center gap-2 mb-3">
                            <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $status_colors[$request['status']]; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $request['status'])); ?>
                            </span>
                            <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $priority_colors[$request['priority']]; ?>">
                                <?php echo ucfirst($request['priority']); ?> Priority
                            </span>
                            <span class="text-xs text-slate-500">
                                by <strong><?php echo htmlspecialchars($request['username']); ?></strong>
                            </span>
                        </div>

                        <p class="text-sm text-slate-900 mb-3 leading-relaxed">
                            <?php echo nl2br(htmlspecialchars($request['feature_description'])); ?>
                        </p>

                        <?php if ($request['admin_response']): ?>
                        <div class="p-3 bg-blue-50 border-l-4 border-blue-500 rounded mb-3">
                            <p class="text-xs font-semibold text-blue-900 mb-1">
                                <i class="fas fa-reply mr-1"></i>Admin Response:
                            </p>
                            <p class="text-sm text-blue-800">
                                <?php echo nl2br(htmlspecialchars($request['admin_response'])); ?>
                            </p>
                        </div>
                        <?php endif; ?>

                        <div class="flex flex-wrap items-center gap-3 text-xs text-slate-500">
                            <span>
                                <i class="far fa-calendar mr-1"></i>
                                <?php echo date('M d, Y H:i', strtotime($request['created_at'])); ?>
                            </span>
                            <?php if ($request['upvotes'] > 0): ?>
                            <span>
                                <i class="fas fa-arrow-up mr-1"></i>
                                <?php echo $request['upvotes']; ?> upvotes
                            </span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Image -->
                    <?php if ($request['image_path']): ?>
                    <div class="lg:w-32">
                        <img src="<?php echo WEBSITE_URL . '/' . $request['image_path']; ?>" 
                             alt="Request image" 
                             class="w-full h-24 object-cover rounded-lg border border-slate-200">
                    </div>
                    <?php endif; ?>

                    <!-- Actions -->
                    <div class="flex lg:flex-col gap-2">
                        <a href="?edit=<?php echo $request['id']; ?>" 
                           class="px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded text-xs font-medium whitespace-nowrap">
                            <i class="fas fa-edit mr-1"></i>Edit
                        </a>
                        <a href="?delete=<?php echo $request['id']; ?>" 
                           onclick="return confirm('Are you sure you want to delete this request?')"
                           class="px-3 py-2 bg-red-600 hover:bg-red-700 text-white rounded text-xs font-medium whitespace-nowrap">
                            <i class="fas fa-trash mr-1"></i>Delete
                        </a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="flex items-center justify-center gap-3 mt-6">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?><?php echo $status_filter ? '&status=' . $status_filter : ''; ?><?php echo $priority_filter ? '&priority=' . $priority_filter : ''; ?>" 
                   class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
                    <i class="fas fa-chevron-left"></i>
                </a>
            <?php endif; ?>

            <span class="px-4 py-2 bg-slate-100 rounded-lg text-sm font-medium">
                Page <?php echo $page; ?> of <?php echo $total_pages; ?>
            </span>

            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page + 1; ?><?php echo $status_filter ? '&status=' . $status_filter : ''; ?><?php echo $priority_filter ? '&priority=' . $priority_filter : ''; ?>" 
                   class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
                    <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php else: ?>
        <div class="text-center py-12">
            <i class="fas fa-inbox text-4xl text-slate-300 mb-4"></i>
            <p class="text-slate-600">No feature requests found.</p>
        </div>
        <?php endif; ?>
    </div>

</div>

</body>
</html>