<?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 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($conn);

    $payload = json_decode(file_get_contents('php://input'), true);
    if (!is_array($payload)) {
        $payload = $_POST;
    }

    $customerId = (int)$_SESSION['user_id'];
    $customerName = trim((string)($_SESSION['user_name'] ?? ''));
    $customerEmail = trim((string)($_SESSION['user_email'] ?? ''));
    $subject = trim((string)($payload['subject'] ?? ''));
    $message = trim((string)($payload['message'] ?? ''));
    $ratingRaw = isset($payload['rating']) ? (int)$payload['rating'] : 0;
    $rating = ($ratingRaw >= 1 && $ratingRaw <= 5) ? $ratingRaw : null;

    if ($customerName === '') {
        $customerName = 'Customer #' . $customerId;
    }
    if ($customerEmail === '') {
        $lookup = $conn->prepare("SELECT email, firstname, lastname FROM customers WHERE id = ? LIMIT 1");
        if ($lookup) {
            $lookup->bind_param('i', $customerId);
            $lookup->execute();
            $row = $lookup->get_result()->fetch_assoc();
            $lookup->close();
            if ($row) {
                $dbName = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
                if ($dbName !== '') {
                    $customerName = $dbName;
                }
                $customerEmail = trim((string)($row['email'] ?? $customerEmail));
            }
        }
    }

    if ($subject === '') {
        $subject = 'General Feedback';
    }
    if (strlen($subject) < 3) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Subject must be at least 3 characters']);
        exit;
    }
    if (strlen($message) < 10) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Feedback message must be at least 10 characters']);
        exit;
    }

    $stmt = $conn->prepare("
        INSERT INTO customer_feedback (
            customer_id, customer_name, customer_email, subject, message, rating, status
        ) VALUES (?, ?, ?, ?, ?, ?, 'new')
    ");
    if (!$stmt) {
        throw new Exception('Failed to prepare feedback insert');
    }
    $stmt->bind_param('issssi', $customerId, $customerName, $customerEmail, $subject, $message, $rating);
    if (!$stmt->execute()) {
        $stmt->close();
        throw new Exception('Failed to save feedback');
    }
    $feedbackId = (int)$stmt->insert_id;
    $stmt->close();

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