<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/market_common.php';

try {
    rvu_ensure_market_tables($pdo);
    $user = rvu_market_require_user($pdo);
    $viewerId = (int)$user['id'];
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'GET') {
        $singleId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($singleId > 0) {
            $item = rvu_market_fetch_item($pdo, $singleId, $viewerId);
            if (!$item) rvu_market_json(['detail' => 'Listing not found.'], 404);
            rvu_market_json(['data' => $item]);
        }

        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = max(1, min(50, (int)($_GET['limit'] ?? 12)));
        $offset = ($page - 1) * $limit;
        $mine = rvu_market_bool($_GET['mine'] ?? false);
        $moderation = rvu_market_bool($_GET['moderation'] ?? false);
        $status = strtolower(trim((string)($_GET['status'] ?? 'active')));
        $category = trim((string)($_GET['category'] ?? ''));
        $campus = trim((string)($_GET['campus'] ?? ''));
        $q = trim((string)($_GET['q'] ?? ''));

        $conditions = [];
        $params = [':viewer_id' => $viewerId];
        $countParams = [];

        // Pending, reported, rejected and all-status administrative views are
        // moderation data and must never be exposed to ordinary members.
        if (!$mine && !$moderation && in_array($status, ['pending','reported','rejected','all'], true)
            && !rvu_market_is_admin($user['role'] ?? '')) {
            rvu_market_json(['detail' => 'Administrator access is required for this marketplace view.'], 403);
        }

        if ($moderation) {
            if (!rvu_market_is_admin($user['role'] ?? '')) {
                rvu_market_json(['detail' => 'Administrator access is required for marketplace moderation.'], 403);
            }
            $conditions[] = "i.status IN ('pending','reported')";
        } elseif ($mine) {
            $conditions[] = 'i.seller_user_id = :seller_user_id';
            $params[':seller_user_id'] = $viewerId;
            $countParams[':seller_user_id'] = $viewerId;
        } elseif ($status === 'active' || $status === 'approved') {
            $conditions[] = "i.status IN ('active','approved')";
        } elseif ($status !== 'all' && $status !== '') {
            $conditions[] = 'LOWER(i.status) = :status';
            $params[':status'] = $status;
            $countParams[':status'] = $status;
        }

        if ($category !== '') {
            $conditions[] = 'i.category = :category';
            $params[':category'] = $category;
            $countParams[':category'] = $category;
        }
        if ($campus !== '') {
            $conditions[] = 'i.campus = :campus';
            $params[':campus'] = $campus;
            $countParams[':campus'] = $campus;
        }
        if ($q !== '') {
            $conditions[] = "(
                i.title ILIKE :q OR
                i.description ILIKE :q OR
                i.category ILIKE :q OR
                COALESCE(i.seller_name,'') ILIKE :q OR
                COALESCE(i.location,'') ILIKE :q
            )";
            $params[':q'] = '%' . $q . '%';
            $countParams[':q'] = '%' . $q . '%';
        }

        $where = $conditions ? ' WHERE ' . implode(' AND ', $conditions) : '';
        $sql = rvu_market_item_select_sql() . $where . ' ORDER BY i.created_at DESC, i.id DESC LIMIT :limit OFFSET :offset';
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $rows = array_map('rvu_market_normalize_item', $rows);

        $countSql = 'SELECT COUNT(*) FROM campus_market_items i' . $where;
        $countStmt = $pdo->prepare($countSql);
        foreach ($countParams as $key => $value) {
            $countStmt->bindValue($key, $value);
        }
        $countStmt->execute();
        $total = (int)$countStmt->fetchColumn();

        rvu_market_json([
            'data' => $rows,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total,
                'has_more' => ($offset + count($rows)) < $total,
            ],
        ]);
    }

    if ($method === 'POST') {
        $input = rvu_market_input();
        $title = trim((string)($input['title'] ?? ''));
        $description = trim((string)($input['description'] ?? ''));
        $price = (float)($input['price'] ?? 0);
        $category = trim((string)($input['category'] ?? 'Other'));
        $condition = trim((string)($input['condition'] ?? 'Used - Good'));
        $quantity = max(1, (int)($input['quantity'] ?? 1));
        $sellerPhone = trim((string)($input['seller_phone'] ?? ''));
        $location = trim((string)($input['location'] ?? ''));

        if (mb_strlen($title) < 3 || mb_strlen($title) > 180) {
            rvu_market_json(['detail' => 'Item title must contain 3 to 180 characters.'], 422);
        }
        if (mb_strlen($description) < 5 || mb_strlen($description) > 10000) {
            rvu_market_json(['detail' => 'Description must contain 5 to 10,000 characters.'], 422);
        }
        if ($price < 0) {
            rvu_market_json(['detail' => 'Price cannot be negative.'], 422);
        }

        $sellerName = trim((string)($user['full_name'] ?? 'Rockview Member'));
        $campus = trim((string)($user['campus'] ?? ''));
        $status = rvu_market_is_admin($user['role'] ?? '') ? 'active' : 'pending';

        $stmt = $pdo->prepare("INSERT INTO campus_market_items
            (seller_user_id, title, description, price, category, condition, quantity,
             campus, location, seller_name, seller_phone, status, approved_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CASE WHEN ?='active' THEN CURRENT_TIMESTAMP ELSE NULL END)
            RETURNING id");
        $stmt->execute([
            $viewerId,
            $title,
            $description,
            $price,
            $category,
            $condition,
            $quantity,
            $campus !== '' ? $campus : null,
            $location !== '' ? $location : null,
            $sellerName,
            $sellerPhone !== '' ? $sellerPhone : null,
            $status,
            $status,
        ]);
        $id = (int)$stmt->fetchColumn();

        rvu_market_json([
            'id' => $id,
            'status' => $status,
            'message' => $status === 'active'
                ? 'Listing published successfully.'
                : 'Listing submitted for marketplace approval.',
        ], 201);
    }

    if ($method === 'PUT') {
        $itemId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($itemId <= 0) rvu_market_json(['detail' => 'Listing id is required.'], 422);
        $item = rvu_market_fetch_item($pdo, $itemId, $viewerId);
        if (!$item) rvu_market_json(['detail' => 'Listing not found.'], 404);
        if (!rvu_market_can_manage($user, $item['seller_user_id'])) {
            rvu_market_json(['detail' => 'You cannot edit this listing.'], 403);
        }

        $input = rvu_market_input();
        $allowed = ['title', 'description', 'price', 'category', 'condition', 'quantity', 'location', 'seller_phone'];
        $sets = [];
        $values = [];
        foreach ($allowed as $field) {
            if (!array_key_exists($field, $input)) continue;
            $sets[] = '"' . $field . '" = ?';
            $value = $input[$field];
            if ($field === 'price') $value = (float)$value;
            if ($field === 'quantity') $value = max(1, (int)$value);
            if (is_string($value)) $value = trim($value);
            $values[] = $value;
        }

        if (isset($input['status']) && strtolower((string)$input['status']) === 'sold') {
            $sets[] = "status = 'sold'";
            $sets[] = 'sold_at = CURRENT_TIMESTAMP';
        }

        if (!$sets) rvu_market_json(['detail' => 'No editable values supplied.'], 422);
        $sets[] = 'updated_at = CURRENT_TIMESTAMP';
        $values[] = $itemId;
        $pdo->prepare('UPDATE campus_market_items SET ' . implode(', ', $sets) . ' WHERE id = ?')->execute($values);
        rvu_market_json(['message' => 'Listing updated successfully.']);
    }

    if ($method === 'DELETE') {
        $itemId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($itemId <= 0) rvu_market_json(['detail' => 'Listing id is required.'], 422);
        $item = rvu_market_fetch_item($pdo, $itemId, $viewerId);
        if (!$item) rvu_market_json(['detail' => 'Listing not found.'], 404);
        if (!rvu_market_can_manage($user, $item['seller_user_id'])) {
            rvu_market_json(['detail' => 'You cannot delete this listing.'], 403);
        }
        $mediaStmt = $pdo->prepare('SELECT media_path, thumbnail_path FROM campus_market_media WHERE item_id = ?');
        $mediaStmt->execute([$itemId]);
        $media = $mediaStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $pdo->prepare('DELETE FROM campus_market_items WHERE id = ?')->execute([$itemId]);
        rvu_market_remove_physical_media($media);
        rvu_market_json(['message' => 'Listing deleted.']);
    }

    rvu_market_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_market_json(['detail' => 'Marketplace server error: ' . $e->getMessage()], 500);
}
