<?php
session_start();
require 'config.php';

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Handle GET requests for public feedback (no authentication required)
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'get_public_reviews') {
    header('Content-Type: application/json');
    
    // Fetch approved feedback ordered by creation date
    $sql = "SELECT f.id, f.message, f.rating, f.created_at, u.name as username 
            FROM feedback f
            JOIN users u ON f.user_id = u.id
            WHERE f.status = 'approved'
            ORDER BY f.created_at DESC
            LIMIT 10";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . $conn->error,
            'data' => []
        ]);
        exit;
    }
    
    $reviews = [];
    while ($row = $result->fetch_assoc()) {
        $reviews[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $reviews,
        'count' => count($reviews)
    ]);
    exit;
}

// Debug: Log the request
error_log("Feedback API called - Session ID: " . (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'NOT SET'));

// Check if user is logged in for other operations
if (!isset($_SESSION['user_id'])) {
    error_log("User not logged in");
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'User not logged in',
        'feedback' => null
    ]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Fetch all feedback submitted by user
    $user_id = $_SESSION['user_id'];
    $sql = "SELECT id, subject, message, rating, status, created_at 
            FROM feedback WHERE user_id = ? ORDER BY created_at DESC";
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        error_log("Database prepare error: " . $conn->error);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Database prepare error: ' . $conn->error,
            'feedback' => null
        ]);
        exit;
    }
    
    $stmt->bind_param("i", $user_id);
    if (!$stmt->execute()) {
        error_log("Database execute error: " . $stmt->error);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Database execute error: ' . $stmt->error,
            'feedback' => null
        ]);
        exit;
    }
    
    $result = $stmt->get_result();
    
    if (!$result) {
        error_log("Get result error: " . $stmt->error);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Failed to get results',
            'feedback' => null
        ]);
        exit;
    }
    
    $feedback = [];
    while ($row = $result->fetch_assoc()) {
        $feedback[] = $row;
    }
    
    error_log("Fetched " . count($feedback) . " feedback entries for user " . $user_id);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Feedback fetched successfully',
        'feedback' => $feedback
    ]);
    $stmt->close();
} elseif ($method === 'POST') {
    // Submit new feedback
    header('Content-Type: application/json');
    
    $user_id = $_SESSION['user_id'];
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate input
    if (!isset($input['subject']) || !isset($input['message']) || !isset($input['rating'])) {
        echo json_encode([
            'success' => false,
            'message' => 'Missing required fields: subject, message, or rating'
        ]);
        error_log("Missing required fields");
        exit;
    }
    
    $subject = trim($input['subject']);
    $message = trim($input['message']);
    $rating = intval($input['rating']);
    
    // Validate data
    if (empty($subject)) {
        echo json_encode([
            'success' => false,
            'message' => 'Subject cannot be empty'
        ]);
        error_log("Subject is empty");
        exit;
    }
    
    if (empty($message)) {
        echo json_encode([
            'success' => false,
            'message' => 'Feedback message cannot be empty'
        ]);
        error_log("Message is empty");
        exit;
    }
    
    if ($rating < 1 || $rating > 5) {
        echo json_encode([
            'success' => false,
            'message' => 'Rating must be between 1 and 5'
        ]);
        error_log("Invalid rating: " . $rating);
        exit;
    }
    
    // Insert feedback into database
    $sql = "INSERT INTO feedback (user_id, subject, message, rating, status, created_at) VALUES (?, ?, ?, ?, 'pending', NOW())";
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        error_log("Database prepare error: " . $conn->error);
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . $conn->error
        ]);
        exit;
    }
    
    if (!$stmt->bind_param("issi", $user_id, $subject, $message, $rating)) {
        error_log("Bind parameter error: " . $stmt->error);
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . $stmt->error
        ]);
        exit;
    }
    
    if (!$stmt->execute()) {
        error_log("Database execute error: " . $stmt->error);
        echo json_encode([
            'success' => false,
            'message' => 'Failed to submit feedback: ' . $stmt->error
        ]);
        exit;
    }
    
    $feedback_id = $stmt->insert_id;
    $stmt->close();
    
    error_log("Feedback submitted successfully - ID: " . $feedback_id . ", User ID: " . $user_id);
    echo json_encode([
        'success' => true,
        'message' => 'Thank you! Your feedback has been submitted successfully.',
        'feedback_id' => $feedback_id
    ]);
} else {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
    exit;
}

$conn->close();
?>
