<?php
/**
 * Feedback Submission Handler
 * Works on both localhost and cPanel
 */

header('Content-Type: application/json');

// Load database helper
require_once __DIR__ . '/config/database_helper.php';

// Load existing feedback
$feedbacks = DatabaseHelper::loadJson('customer_feedback.json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = filter_var(trim($_POST['feedback_name'] ?? ''), FILTER_SANITIZE_STRING);
    $email = filter_var(trim($_POST['feedback_email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $rating = (int)($_POST['rating'] ?? 5);
    $text = filter_var(trim($_POST['feedback_text'] ?? ''), FILTER_SANITIZE_STRING);
    
    // Validate inputs
    if (empty($name) || empty($email) || empty($text)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required!']);
        exit;
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid email address!']);
        exit;
    }
    
    // Ensure rating is between 1-5
    $rating = max(1, min(5, $rating));
    
    // Add new feedback
    $feedbacks[] = [
        'name' => $name,
        'email' => $email,
        'rating' => $rating,
        'feedback' => $text,
        'submitted_date' => date('Y-m-d H:i:s'),
        'ip_address' => $_SERVER['REMOTE_ADDR'],
        'status' => 'new'
    ];
    
    // Save feedback using database helper
    if (DatabaseHelper::saveJson('customer_feedback.json', $feedbacks)) {
        echo json_encode(['success' => true, 'message' => 'Thank you for your feedback!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error saving feedback.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request.']);
}
?>
