<?php
/**
 * Marketplace — Accountant Directory & Service Listings
 * GET /v1/marketplace/listings
 * GET /v1/marketplace/listings?city=amman&specialty=tax
 * 
 * Public directory where accounting offices can list their services
 * and businesses can find accountants.
 */

use App\Core\Database;
use App\Core\Encryption;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$pagination = paginate_params(20, 50);

$city = $_GET['city'] ?? null;
$specialty = $_GET['specialty'] ?? null;
$search = $_GET['search'] ?? null;

$where = "ml.is_active = 1";
$params = [];

if ($city) {
    $where .= " AND ml.city = ?";
    $params[] = $city;
}
if ($specialty) {
    $where .= " AND ml.specialty = ?";
    $params[] = $specialty;
}
if ($search) {
    $where .= " AND (ml.office_name LIKE ? OR ml.description LIKE ?)";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

try {
    // Count
    $countStmt = $db->prepare("SELECT COUNT(*) FROM marketplace_listings ml WHERE {$where}");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();

    // Fetch
    $stmt = $db->prepare("
        SELECT ml.*, t.name as tenant_name
        FROM marketplace_listings ml
        LEFT JOIN tenants t ON ml.tenant_id = t.id
        WHERE {$where}
        ORDER BY ml.is_featured DESC, ml.rating DESC, ml.created_at DESC
        LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}
    ");
    $stmt->execute($params);
    $listings = $stmt->fetchAll();

    // Decrypt names
    foreach ($listings as &$l) {
        if (!empty($l['tenant_name'])) {
            $dec = Encryption::decrypt($l['tenant_name']);
            $l['tenant_name'] = ($dec !== false && $dec !== null) ? $dec : $l['tenant_name'];
        }
    }

    $cities = ['amman' => 'عمّان', 'irbid' => 'إربد', 'zarqa' => 'الزرقاء', 'aqaba' => 'العقبة', 'salt' => 'السلط', 'madaba' => 'مأدبا', 'karak' => 'الكرك', 'other' => 'أخرى'];
    $specialties = ['tax' => 'ضرائب', 'audit' => 'تدقيق', 'bookkeeping' => 'مسك دفاتر', 'payroll' => 'رواتب', 'consulting' => 'استشارات', 'general' => 'عام'];

    json_paginated($listings, $total, $pagination, 'سوق المحاسبين');

} catch (\Exception $e) {
    safe_error($e, 'marketplace/listings', 'حدث خطأ في تحميل القوائم.');
}
