<?php
// api/marketplace.php
require_once '../config/database.php';
require_once __DIR__ . '/session_auth.php';
rvu_audit_context_from_request($pdo);
header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$path_info = isset($_SERVER['PATH_INFO']) ? explode('/', trim($_SERVER['PATH_INFO'], '/')) : [];
$id = $path_info[0] ?? null;

$input = json_decode(file_get_contents("php://input"), true) ?? [];

try {
    if ($method === 'GET') {
        echo json_encode($pdo->query("SELECT * FROM marketplace_items")->fetchAll(PDO::FETCH_ASSOC));
    } 
    elseif ($method === 'POST') {
        $sql = "INSERT INTO marketplace_items (title, price, description, seller_name, seller_phone, image_url, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$input['title'], $input['price'], $input['description'], $input['seller_name'], $input['seller_phone'] ?? "", $input['image_url'] ?? null, $input['status'] ?? 'Pending']);
        http_response_code(201);
        echo json_encode(["message" => "Listing submitted successfully!", "id" => $pdo->lastInsertId()]);
    } 
    elseif ($method === 'PATCH' && $id) {
        $status = $input['status'];
        $report_reason = $input['report_reason'] ?? null;
        
        $sql = "UPDATE marketplace_items SET status = ?";
        $params = [$status];
        if ($report_reason !== null) { $sql .= ", report_reason = ?"; $params[] = $report_reason; }
        
        $sql .= " WHERE id = ?";
        $params[] = $id;

        $pdo->prepare($sql)->execute($params);
        echo json_encode(["message" => "Item status updated to " . $status]);
    } 
    elseif ($method === 'DELETE' && $id) {
        $pdo->prepare("DELETE FROM marketplace_items WHERE id = ?")->execute([$id]);
        http_response_code(204);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["detail" => $e->getMessage()]);
}
?>