<?php
require_once '../../config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

function ensureCustomerFeedbackTable(mysqli $db): void
{
    $db->query("
        CREATE TABLE IF NOT EXISTS customer_feedback (
            id INT AUTO_INCREMENT PRIMARY KEY,
            customer_id INT NULL,
            customer_name VARCHAR(120) NOT NULL,
            customer_email VARCHAR(120) NOT NULL,
            subject VARCHAR(180) NOT NULL,
            message TEXT NOT NULL,
            rating TINYINT NULL,
            status VARCHAR(20) NOT NULL DEFAULT 'new',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_customer_id (customer_id),
            INDEX idx_created_at (created_at),
            INDEX idx_status (status)
        )
    ");
}

try {
    ensureCustomerFeedbackTable($mysqli);

    $query = "
        SELECT
            f.id,
            f.customer_id,
            f.customer_name,
            f.customer_email,
            f.subject,
            f.message,
            f.rating,
            f.status,
            f.created_at
        FROM customer_feedback f
        ORDER BY f.created_at DESC
        LIMIT 120
    ";
    $result = $mysqli->query($query);
    if (!$result) {
        throw new Exception('Failed to load customer feedback');
    }

    $feedback = [];
    while ($row = $result->fetch_assoc()) {
        $feedback[] = [
            'id' => (int)$row['id'],
            'customer_id' => $row['customer_id'] !== null ? (int)$row['customer_id'] : null,
            'customer_name' => (string)($row['customer_name'] ?? 'N/A'),
            'customer_email' => (string)($row['customer_email'] ?? ''),
            'subject' => (string)($row['subject'] ?? ''),
            'message' => (string)($row['message'] ?? ''),
            'rating' => $row['rating'] !== null ? (int)$row['rating'] : null,
            'status' => (string)($row['status'] ?? 'new'),
            'created_at' => (string)($row['created_at'] ?? '')
        ];
    }

    echo json_encode([
        'success' => true,
        'feedback' => $feedback,
        'count' => count($feedback)
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
