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

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

function tableExists(mysqli $db, string $table): bool
{
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

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 {
    $customerId = (int)$_SESSION['user_id'];
    ensureCustomerFeedbackTable($conn);

    $feedback = [];

    $stmt = $conn->prepare("
        SELECT id, subject, message, rating, status, created_at
        FROM customer_feedback
        WHERE customer_id = ?
        ORDER BY created_at DESC
        LIMIT 30
    ");
    if (!$stmt) {
        throw new Exception('Failed to prepare feedback query');
    }
    $stmt->bind_param('i', $customerId);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $feedback[] = [
            'id' => (int)$row['id'],
            'subject' => (string)($row['subject'] ?? 'Feedback'),
            'message' => (string)($row['message'] ?? ''),
            'rating' => $row['rating'] !== null ? (int)$row['rating'] : null,
            'status' => (string)($row['status'] ?? 'new'),
            'created_at' => (string)($row['created_at'] ?? '')
        ];
    }
    $stmt->close();

    // Backward compatibility: include legacy reviews if customer_feedback is empty.
    if (count($feedback) === 0 && tableExists($conn, 'reviews')) {
        $legacyStmt = $conn->prepare("
            SELECT id, comment, rating, status, created_at
            FROM reviews
            WHERE customer_id = ?
            ORDER BY created_at DESC
            LIMIT 30
        ");
        if ($legacyStmt) {
            $legacyStmt->bind_param('i', $customerId);
            $legacyStmt->execute();
            $legacyResult = $legacyStmt->get_result();
            while ($row = $legacyResult->fetch_assoc()) {
                $feedback[] = [
                    'id' => (int)$row['id'],
                    'subject' => 'Feedback',
                    'message' => (string)($row['comment'] ?? ''),
                    'rating' => $row['rating'] !== null ? (int)$row['rating'] : null,
                    'status' => (string)($row['status'] ?? 'new'),
                    'created_at' => (string)($row['created_at'] ?? '')
                ];
            }
            $legacyStmt->close();
        }
    }

    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()]);
}
?>
