<?php
/**
 * Marketplace — Create/Update My Listing
 * POST /v1/marketplace/my-listing
 * Body: { "office_name": "...", "city": "amman", "specialty": "tax", "description": "...", "phone": "...", "email": "..." }
 */

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

$decoded = RoleMiddleware::require(['super_admin', 'admin']);
$db = Database::getInstance();

$tenantId = $decoded['tenant_id'];
$data = input();

$errors = Validator::validate($data, [
    'office_name' => 'required',
    'city'        => 'required',
    'specialty'   => 'required',
]);

if ($errors) {
    json_error('بيانات ناقصة', 422, $errors);
}

try {
    // Check if listing exists
    $existing = $db->prepare("SELECT id FROM marketplace_listings WHERE tenant_id = ? LIMIT 1");
    $existing->execute([$tenantId]);
    $row = $existing->fetch();

    if ($row) {
        // Update
        $db->prepare("
            UPDATE marketplace_listings SET
                office_name = ?, city = ?, specialty = ?, description = ?,
                contact_phone = ?, contact_email = ?, updated_at = NOW()
            WHERE tenant_id = ?
        ")->execute([
            $data['office_name'], $data['city'], $data['specialty'],
            $data['description'] ?? '', $data['phone'] ?? '', $data['email'] ?? '',
            $tenantId
        ]);
        json_success(['id' => $row['id']], 'تم تحديث القائمة بنجاح');
    } else {
        // Create
        $id = Database::generateUuid();
        $db->prepare("
            INSERT INTO marketplace_listings (id, tenant_id, office_name, city, specialty, description, contact_phone, contact_email, is_active, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())
        ")->execute([
            $id, $tenantId, $data['office_name'], $data['city'], $data['specialty'],
            $data['description'] ?? '', $data['phone'] ?? '', $data['email'] ?? ''
        ]);
        json_success(['id' => $id], 'تم إضافة مكتبك للسوق بنجاح! 🎉');
    }
} catch (\Exception $e) {
    safe_error($e, 'marketplace/my-listing', 'حدث خطأ في حفظ القائمة.');
}
