<?php
ob_clean();
header("Content-Type: application/json; charset=UTF-8");

error_reporting(E_ALL);
ini_set('display_errors', 0);

set_error_handler(function ($severity, $message, $file, $line) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "PHP Error: $message"
    ]);
    exit;
});

require_once __DIR__ . '/config/koneksi.php';
require_once __DIR__ . '/config/jwt.php';

// ================= AUTH HEADER =================
function getAuthHeader() {
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        return $_SERVER['HTTP_AUTHORIZATION'];
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        return $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    } elseif (function_exists('getallheaders')) {
        $headers = getallheaders();
        return $headers['Authorization'] ?? $headers['authorization'] ?? '';
    }
    return '';
}

// ================= METHOD =================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        "success" => false,
        "message" => "Method harus POST"
    ]);
    exit;
}

// ================= TOKEN =================
$auth = getAuthHeader();

if (!$auth) {
    echo json_encode([
        "success" => false,
        "message" => "Unauthorized"
    ]);
    exit;
}

$token = trim(str_replace("Bearer ", "", $auth));
$userData = verifyJWT($token);

if (!$userData) {
    echo json_encode([
        "success" => false,
        "message" => "Token invalid"
    ]);
    exit;
}

$userId = $userData['user_id'] ?? null;
$companyId = $userData['company_id'] ?? null;

if (!$userId) {
    echo json_encode([
        "success" => false,
        "message" => "User tidak valid"
    ]);
    exit;
}

// ================= INPUT SUPPORT JSON / FORM-DATA =================
$raw = file_get_contents("php://input");
$json = json_decode($raw, true);

if (is_array($json)) {
    $rating = isset($json['rating']) ? intval($json['rating']) : 0;
    $message = isset($json['message']) ? trim($json['message']) : '';
    $appVersion = isset($json['app_version']) ? trim($json['app_version']) : '';
    $deviceInfo = isset($json['device_info']) ? trim($json['device_info']) : '';
} else {
    $rating = isset($_POST['rating']) ? intval($_POST['rating']) : 0;
    $message = isset($_POST['message']) ? trim($_POST['message']) : '';
    $appVersion = isset($_POST['app_version']) ? trim($_POST['app_version']) : '';
    $deviceInfo = isset($_POST['device_info']) ? trim($_POST['device_info']) : '';
}

// ================= VALIDASI =================
if ($rating < 1 || $rating > 5) {
    echo json_encode([
        "success" => false,
        "message" => "Rating harus 1 sampai 5"
    ]);
    exit;
}

if ($message === '') {
    echo json_encode([
        "success" => false,
        "message" => "Masukan wajib diisi"
    ]);
    exit;
}

if (strlen($message) > 3000) {
    echo json_encode([
        "success" => false,
        "message" => "Masukan terlalu panjang"
    ]);
    exit;
}

if ($appVersion === '') {
    $appVersion = null;
}

if ($deviceInfo === '') {
    $deviceInfo = null;
}

$now = date('Y-m-d H:i:s');
$status = 'new';

// ================= INSERT =================
$stmt = $conn->prepare("
    INSERT INTO app_feedbacks
    (
        company_id,
        user_id,
        rating,
        message,
        app_version,
        device_info,
        status,
        created_at,
        updated_at
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");

if (!$stmt) {
    echo json_encode([
        "success" => false,
        "message" => $conn->error
    ]);
    exit;
}

$stmt->bind_param(
    "ssissssss",
    $companyId,
    $userId,
    $rating,
    $message,
    $appVersion,
    $deviceInfo,
    $status,
    $now,
    $now
);

if (!$stmt->execute()) {
    echo json_encode([
        "success" => false,
        "message" => $stmt->error
    ]);
    exit;
}

echo json_encode([
    "success" => true,
    "message" => "Feedback berhasil dikirim"
]);