<?php
ob_start();
error_reporting(0);
ini_set('display_errors', 0);

ob_clean();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'config.php';

$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $stmt = $db->prepare("
        INSERT INTO user_feedback (device_id, user_name, feedback_type, subject, message, device_info, app_version)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        $input['device_id'] ?? '',
        $input['user_name'] ?? 'Anónimo',
        $input['feedback_type'] ?? 'general',
        $input['subject'] ?? '',
        $input['message'] ?? '',
        $input['device_info'] ?? '',
        $input['app_version'] ?? '1.0'
    ]);
    
    echo json_encode(['success' => true, 'message' => 'Feedback recibido']);
    
} elseif ($method === 'GET') {
    $status = $_GET['status'] ?? 'all';
    
    $query = "SELECT * FROM user_feedback";
    if ($status !== 'all') {
        $query .= " WHERE status = ?";
    }
    $query .= " ORDER BY created_at DESC";
    
    $stmt = $db->prepare($query);
    if ($status !== 'all') {
        $stmt->execute([$status]);
    } else {
        $stmt->execute();
    }
    
    $feedback = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['success' => true, 'data' => $feedback]);
    
} elseif ($method === 'PUT') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $stmt = $db->prepare("
        UPDATE user_feedback 
        SET status = ?, admin_response = ?, responded_at = CURRENT_TIMESTAMP
        WHERE id = ?
    ");
    
    $stmt->execute([
        $input['status'] ?? 'reviewed',
        $input['admin_response'] ?? '',
        $input['id']
    ]);
    
    echo json_encode(['success' => true]);
}
