<?php
/**
 * Admin - Feedback Dashboard
 * View, manage, and analyze all client feedback submissions
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

// Check permission
if (!$auth->canAccessPage('feedbacks')) {
    header('Location: ?page=admin/dashboard');
    exit();
}

// Get filter parameters
$filter_month = $_GET['month'] ?? date('m');
$filter_year = $_GET['year'] ?? date('Y');
$filter_client = $_GET['client'] ?? null;

// Build query
$where = "WHERE MONTH(f.Date) = ? AND YEAR(f.Date) = ?";
$params = [(int)$filter_month, (int)$filter_year];

if ($filter_client) {
    $where .= " AND f.Client = ?";
    $params[] = $filter_client;
}

// Get all feedbacks for the selected period
$feedbacks = $db->fetchAll(
    "SELECT f.*, u.name as client_name
     FROM feedback f
     LEFT JOIN users u ON f.Client = u.id
     $where
     ORDER BY f.Date DESC",
    $params
);

// Get unique clients for filter dropdown
$clients = $db->fetchAll(
    "SELECT DISTINCT f.Client, u.name
     FROM feedback f
     LEFT JOIN users u ON f.Client = u.id
     WHERE f.Client IS NOT NULL
     ORDER BY u.name"
);

// Calculate aggregate statistics
$stats = [
    'total_feedbacks' => 0,
    'avg_guard_score' => 0,
    'avg_controller_score' => 0,
    'avg_management_score' => 0,
    'avg_overall_score' => 0,
    'clients_count' => 0,
];

if (!empty($feedbacks)) {
    $stats['total_feedbacks'] = count($feedbacks);
    $stats['clients_count'] = count(array_unique(array_column($feedbacks, 'Client')));
    
    $totalGuard = 0;
    $totalController = 0;
    $totalManagement = 0;
    $totalOverall = 0;
    
    foreach ($feedbacks as $f) {
        $totalGuard += $f['Guard_Score'] ?? 0;
        $totalController += $f['Controller_Score'] ?? 0;
        $totalManagement += $f['Management_Score'] ?? 0;
        $totalOverall += $f['Overall_Score'] ?? 0;
    }
    
    $count = count($feedbacks);
    $stats['avg_guard_score'] = round($totalGuard / $count, 2);
    $stats['avg_controller_score'] = round($totalController / $count, 2);
    $stats['avg_management_score'] = round($totalManagement / $count, 2);
    $stats['avg_overall_score'] = round($totalOverall / $count, 2);
}

require_once __DIR__ . '/../../layouts/header.php';
?>

<div class="container mx-auto px-4 py-8 max-w-7xl">
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-4xl font-bold text-gray-800">
            <i class="fas fa-star text-yellow-600 mr-3"></i>Feedback Dashboard
        </h1>
        <p class="text-gray-600 mt-2">View and analyze all client feedback submissions</p>
    </div>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-5 gap-4 mb-8">
        <!-- Total Feedbacks -->
        <div class="bg-white rounded-lg shadow border border-gray-200 p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Total Feedbacks</p>
                    <p class="text-3xl font-bold text-blue-600 mt-2"><?php echo $stats['total_feedbacks']; ?></p>
                </div>
                <div class="text-4xl text-blue-200"><i class="fas fa-comment"></i></div>
            </div>
        </div>

        <!-- Avg Overall Score -->
        <div class="bg-white rounded-lg shadow border border-gray-200 p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Avg Overall Score</p>
                    <p class="text-3xl font-bold text-amber-600 mt-2"><?php echo $stats['avg_overall_score']; ?>/5</p>
                </div>
                <div class="text-4xl text-amber-200"><i class="fas fa-star"></i></div>
            </div>
        </div>

        <!-- Guard Score -->
        <div class="bg-white rounded-lg shadow border border-gray-200 p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Guard Score</p>
                    <p class="text-3xl font-bold text-green-600 mt-2"><?php echo $stats['avg_guard_score']; ?>/5</p>
                </div>
                <div class="text-4xl text-green-200"><i class="fas fa-user-shield"></i></div>
            </div>
        </div>

        <!-- Controller Score -->
        <div class="bg-white rounded-lg shadow border border-gray-200 p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Controller Score</p>
                    <p class="text-3xl font-bold text-purple-600 mt-2"><?php echo $stats['avg_controller_score']; ?>/5</p>
                </div>
                <div class="text-4xl text-purple-200"><i class="fas fa-tasks"></i></div>
            </div>
        </div>

        <!-- Management Score -->
        <div class="bg-white rounded-lg shadow border border-gray-200 p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm font-semibold">Management Score</p>
                    <p class="text-3xl font-bold text-red-600 mt-2"><?php echo $stats['avg_management_score']; ?>/5</p>
                </div>
                <div class="text-4xl text-red-200"><i class="fas fa-chart-line"></i></div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow border border-gray-200 p-6 mb-8">
        <h2 class="text-lg font-bold text-gray-800 mb-4">Filters</h2>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- Month Filter -->
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Month</label>
                <select id="monthFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" onchange="applyFilters()">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                        <option value="<?php echo $m; ?>" <?php echo ($m == $filter_month) ? 'selected' : ''; ?>>
                            <?php echo date('F', mktime(0, 0, 0, $m)); ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>

            <!-- Year Filter -->
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Year</label>
                <select id="yearFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" onchange="applyFilters()">
                    <?php for ($y = date('Y'); $y >= date('Y') - 5; $y--): ?>
                        <option value="<?php echo $y; ?>" <?php echo ($y == $filter_year) ? 'selected' : ''; ?>>
                            <?php echo $y; ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>

            <!-- Client Filter -->
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">Client</label>
                <select id="clientFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" onchange="applyFilters()">
                    <option value="">All Clients</option>
                    <?php foreach ($clients as $client): ?>
                        <option value="<?php echo $client['Client']; ?>" <?php echo ($filter_client == $client['Client']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($client['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Export Button -->
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">&nbsp;</label>
                <button onclick="exportToCSV()" class="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold transition flex items-center justify-center gap-2">
                    <i class="fas fa-download"></i>Export CSV
                </button>
            </div>
        </div>
    </div>

    <!-- Feedbacks Table -->
    <div class="bg-white rounded-lg shadow border border-gray-200 overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-bold text-gray-800">Feedback Records (<?php echo count($feedbacks); ?>)</h2>
        </div>

        <?php if (!empty($feedbacks)): ?>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Date</th>
                            <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Client</th>
                            <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">Subject</th>
                            <th class="px-6 py-3 text-center text-sm font-semibold text-gray-700">Guard</th>
                            <th class="px-6 py-3 text-center text-sm font-semibold text-gray-700">Controller</th>
                            <th class="px-6 py-3 text-center text-sm font-semibold text-gray-700">Management</th>
                            <th class="px-6 py-3 text-center text-sm font-semibold text-gray-700">Overall</th>
                            <th class="px-6 py-3 text-center text-sm font-semibold text-gray-700">Action</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php foreach ($feedbacks as $feedback): ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="px-6 py-4 text-sm text-gray-700">
                                    <?php echo date('M d, Y', strtotime($feedback['Date'])); ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-700">
                                    <?php echo htmlspecialchars($feedback['client_name'] ?? 'Unknown'); ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-700">
                                    <?php echo htmlspecialchars($feedback['Subject'] ?? '-'); ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-center">
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold
                                        <?php 
                                            $score = $feedback['Guard_Score'] ?? 0;
                                            echo $score >= 4.5 ? 'bg-green-100 text-green-700' : 
                                                 ($score >= 3.5 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700');
                                        ?>">
                                        <?php echo $score . '/5'; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-center">
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold
                                        <?php 
                                            $score = $feedback['Controller_Score'] ?? 0;
                                            echo $score >= 4.5 ? 'bg-green-100 text-green-700' : 
                                                 ($score >= 3.5 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700');
                                        ?>">
                                        <?php echo $score . '/5'; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-center">
                                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold
                                        <?php 
                                            $score = $feedback['Management_Score'] ?? 0;
                                            echo $score >= 4.5 ? 'bg-green-100 text-green-700' : 
                                                 ($score >= 3.5 ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700');
                                        ?>">
                                        <?php echo $score . '/5'; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-center font-bold">
                                    <span class="text-lg">
                                        <?php 
                                            $overall = $feedback['Overall_Score'] ?? 0;
                                            echo $overall . '/5';
                                            $starClass = $overall >= 4.5 ? 'text-green-600' : 
                                                        ($overall >= 3.5 ? 'text-yellow-600' : 'text-red-600');
                                        ?>
                                    </span>
                                    <div class="text-xs mt-1 <?php echo $starClass; ?>">
                                        <?php for ($i = 0; $i < 5; $i++): ?>
                                            <i class="fas fa-star"></i>
                                        <?php endfor; ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm text-center">
                                    <button onclick="viewFeedbackDetail(<?php echo $feedback['FeedID']; ?>)" class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 transition text-xs font-semibold">
                                        View
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="p-12 text-center text-gray-500">
                <i class="fas fa-inbox text-4xl mb-3 opacity-50"></i>
                <p>No feedbacks found for the selected period</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function applyFilters() {
    const month = document.getElementById('monthFilter').value;
    const year = document.getElementById('yearFilter').value;
    const client = document.getElementById('clientFilter').value;
    
    let url = '?page=admin/feedbacks&month=' + month + '&year=' + year;
    if (client) url += '&client=' + client;
    
    window.location.href = url;
}

function viewFeedbackDetail(feedId) {
    window.location.href = '?page=admin/feedbacks/detail&id=' + feedId;
}

function exportToCSV() {
    const month = document.getElementById('monthFilter').value;
    const year = document.getElementById('yearFilter').value;
    const client = document.getElementById('clientFilter').value;
    
    let url = '?page=api&endpoint=admin/export-feedbacks&month=' + month + '&year=' + year;
    if (client) url += '&client=' + client;
    
    window.location.href = url;
}
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
