<?php
/**
 * داده تست بازار ملک — آگهی‌های نمونه با مخاطب‌های مختلف
 * C:\xampp\php\php.exe run-melk-listings-seed.php
 * C:\xampp\php\php.exe run-melk-listings-seed.php --reset
 */
declare(strict_types=1);

define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';
require_once ACC_PATH . 'includes/helpers/acl-functions.php';

header('Content-Type: application/json; charset=utf-8');
global $wpdb;

$reset = in_array('--reset', $argv ?? [], true);
$pre   = $wpdb->prefix;
$pass  = 'Melk1234';
$log   = ['users' => [], 'listings' => []];

ob_start();
include __DIR__ . '/run-melk-extensions-install.php';
ob_end_clean();

if ( $reset ) {
    $wpdb->query("DELETE FROM {$pre}melk_listings");
    $log['reset'] = true;
}

function mls_role_id( string $slug ): int {
    global $wpdb;
    return (int) $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM {$wpdb->prefix}acl_roles WHERE slug = %s", $slug
    ));
}

function mls_ensure_user( string $login, string $name, string $email = '' ): int {
    global $wpdb, $pass, $log;
    $id = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT ID FROM {$wpdb->users} WHERE user_login = %s", $login
    ));
    if ( $id ) {
        $wpdb->update("{$wpdb->users}", [
            'user_pass' => wp_hash_password($pass),
            'display_name' => $name,
        ], ['ID' => $id]);
        $log['users'][] = ['login' => $login, 'id' => $id, 'action' => 'updated'];
        return $id;
    }
    $max = (int) $wpdb->get_var("SELECT COALESCE(MAX(ID), 0) FROM {$wpdb->users}");
    $id  = $max + 1;
    $now = date('Y-m-d H:i:s');
    $wpdb->insert("{$wpdb->users}", [
        'ID' => $id, 'user_login' => $login,
        'user_pass' => wp_hash_password($pass),
        'user_nicename' => sanitize_title($login),
        'user_email' => $email ?: $login . '@melk.test',
        'user_registered' => $now, 'display_name' => $name,
        'user_status' => 0,
    ]);
    $log['users'][] = ['login' => $login, 'id' => $id, 'action' => 'created'];
    return $id;
}

function mls_assign_role( int $user_id, string $role_slug, ?string $scope_type = 'global', ?int $scope_id = null ): void {
    global $wpdb;
    $role_id = mls_role_id($role_slug);
    if ( ! $role_id || ! $user_id ) return;
    $exists = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->prefix}acl_user_roles WHERE user_id=%d AND role_id=%d",
        $user_id, $role_id
    ));
    if ( $exists ) return;
    $wpdb->insert("{$wpdb->prefix}acl_user_roles", [
        'user_id' => $user_id, 'role_id' => $role_id,
        'scope_type' => $scope_type ?? 'global', 'scope_id' => $scope_id, 'granted_by' => 2,
    ]);
}

function mls_user_name( int $uid ): string {
    global $wpdb;
    $row = $wpdb->get_row($wpdb->prepare(
        "SELECT display_name, user_login FROM {$wpdb->users} WHERE ID = %d", $uid
    ), ARRAY_A);
    return $row ? ($row['display_name'] ?: $row['user_login']) : '';
}

function mls_upsert_listing( array $row ): int {
    global $wpdb, $log, $pre;
    $key = $row['listing_key'];
    $existing = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM {$pre}melk_listings WHERE listing_key = %s", $key
    ));
    $data = [
        'deal_type'                   => $row['deal_type'],
        'property_type'               => $row['property_type'] ?? 'residential_apartment',
        'title'                       => $row['title'],
        'description'                 => $row['description'] ?? '',
        'price'                       => $row['price'] ?? null,
        'rent_period'                 => $row['rent_period'] ?? null,
        'area_sqm'                    => $row['area_sqm'] ?? null,
        'rooms'                       => $row['rooms'] ?? null,
        'district_id'                 => $row['district_id'] ?? null,
        'neighborhood_id'             => $row['neighborhood_id'] ?? null,
        'renovation_code'             => $row['renovation_code'] ?? null,
        'visibility_mode'             => $row['visibility_mode'] ?? 'network',
        'visibility_roles'            => isset($row['visibility_roles']) ? wp_json_encode($row['visibility_roles']) : null,
        'visibility_user_ids'         => isset($row['visibility_user_ids']) ? wp_json_encode($row['visibility_user_ids']) : null,
        'visibility_usernames'        => isset($row['visibility_usernames']) ? wp_json_encode($row['visibility_usernames']) : null,
        'visibility_district_ids'     => isset($row['visibility_district_ids']) ? wp_json_encode($row['visibility_district_ids']) : null,
        'visibility_neighborhood_ids' => isset($row['visibility_neighborhood_ids']) ? wp_json_encode($row['visibility_neighborhood_ids']) : null,
        'form_template_key'           => $row['form_template_key'] ?? null,
        'form_data'                   => isset($row['form_data']) ? wp_json_encode($row['form_data'], JSON_UNESCAPED_UNICODE) : null,
        'status'                      => $row['status'] ?? 'active',
        'created_by'                  => $row['created_by'],
        'created_by_name'             => $row['created_by_name'],
    ];
    if ( $existing ) {
        $wpdb->update("{$pre}melk_listings", $data, ['id' => $existing]);
        $log['listings'][] = ['key' => $key, 'id' => $existing, 'action' => 'updated'];
        return $existing;
    }
    $data['listing_key'] = $key;
    $wpdb->insert("{$pre}melk_listings", $data);
    $id = (int) $wpdb->insert_id;
    $log['listings'][] = ['key' => $key, 'id' => $id, 'action' => 'created'];
    return $id;
}

$uid_agent = mls_ensure_user('melk_agent', 'مشاور املاک — رضا کریمی');
mls_assign_role($uid_agent, 'agent', 'neighborhood', 1);

$uid_lead  = (int) $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_login='melk_lead_d1' LIMIT 1");
$uid_mgr   = (int) $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_login='melk_mgr_007' LIMIT 1");
$uid_admin = (int) $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_login='ostadowner' LIMIT 1");
if ( ! $uid_admin ) {
    $uid_admin = (int) $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_login='melk_sysadmin' LIMIT 1");
}

$publishers = array_filter([
    'admin' => $uid_admin,
    'lead'  => $uid_lead,
    'mgr'   => $uid_mgr,
    'agent' => $uid_agent,
]);

$samples = [
    [
        'listing_key' => 'ML-DEMO-01',
        'form_template_key' => 'sale_residential_apartment',
        'deal_type' => 'sale',
        'property_type' => 'residential_apartment',
        'title' => 'آپارتمان ۱۲۰ متری نوساز — منطقه ۱',
        'description' => 'دو خواب، پارکینگ و انباری، نزدیک مترو. مناسب خانواده.',
        'price' => 8500000000,
        'area_sqm' => 120,
        'rooms' => 2,
        'district_id' => 1,
        'neighborhood_id' => 1,
        'renovation_code' => '۱-۲۳۴-۵۶۷۸',
        'form_data' => [
            'floor_no' => 4, 'total_floors' => 8, 'year_built' => 1402,
            'document_type' => 'single_deed', 'parking' => 'covered', 'elevator' => 'yes',
            'heating' => 'radiator', 'condition' => 'new', 'address_detail' => 'کوچه گلستان ۱۲',
        ],
        'visibility_mode' => 'network',
        'created_by' => $publishers['admin'] ?? $publishers['lead'] ?? 2,
    ],
    [
        'listing_key' => 'ML-DEMO-02',
        'form_template_key' => 'rent_residential_apartment',
        'deal_type' => 'rent',
        'property_type' => 'residential_apartment',
        'title' => 'اجاره واحد ۹۰ متری — فقط منطقه ۱',
        'description' => 'اجاره ماهانه، بدون رهن کامل. مخاطب: اعضای منطقه ۱.',
        'price' => 25000000,
        'rent_period' => 'monthly',
        'area_sqm' => 90,
        'rooms' => 2,
        'district_id' => 1,
        'form_data' => [
            'deposit_amount' => 500000000, 'furnished' => 'no', 'min_lease_months' => 12,
            'pets_allowed' => 'no', 'utilities_included' => 'tenant', 'address_detail' => 'بلوار زند',
        ],
        'visibility_mode' => 'geo',
        'visibility_district_ids' => [1],
        'created_by' => $publishers['lead'] ?? $publishers['admin'] ?? 2,
    ],
    [
        'listing_key' => 'ML-DEMO-03',
        'form_template_key' => 'partnership_land',
        'deal_type' => 'partnership',
        'property_type' => 'residential_land',
        'title' => 'مشارکت در ساخت — زمین ۴۰۰ متری',
        'description' => 'زمین با سند تک‌برگ، آماده قرارداد مشارکت. مخاطب: مدیران محله و سرگروه‌ها.',
        'price' => null,
        'area_sqm' => 400,
        'district_id' => 1,
        'form_data' => [
            'land_use' => 'residential', 'document_type' => 'single_deed',
            'owner_share_pct' => 40, 'builder_share_pct' => 60,
            'project_duration_months' => 24, 'units_count' => 8,
            'license_status' => 'pending', 'estimated_value' => 12000000000,
        ],
        'visibility_mode' => 'role',
        'visibility_roles' => ['neighborhood_manager', 'district_lead'],
        'created_by' => $publishers['mgr'] ?? $publishers['lead'] ?? 2,
    ],
    [
        'listing_key' => 'ML-DEMO-04',
        'form_template_key' => 'mortgage_residential',
        'deal_type' => 'mortgage',
        'property_type' => 'residential_villa',
        'title' => 'رهن و اجاره ویلا — فقط melk_agent',
        'description' => 'آگهی خصوصی برای مشاور مشخص‌شده.',
        'price' => 15000000,
        'rent_period' => 'monthly',
        'area_sqm' => 200,
        'rooms' => 3,
        'district_id' => 1,
        'form_data' => [
            'mortgage_amount' => 500000000, 'rent_amount' => 15000000,
            'address_detail' => 'شهرک غرب، فاز ۲',
        ],
        'visibility_mode' => 'users',
        'visibility_usernames' => ['melk_agent'],
        'visibility_user_ids' => $uid_agent ? [$uid_agent] : [],
        'created_by' => $publishers['lead'] ?? $publishers['admin'] ?? 2,
    ],
    [
        'listing_key' => 'ML-DEMO-05',
        'form_template_key' => 'rent_commercial_retail',
        'deal_type' => 'rent_commercial',
        'property_type' => 'commercial_retail',
        'title' => 'اجاره مغازه ۴۵ متری — خیابان اصلی',
        'description' => 'مناسب پوشاک یا خدمات. سرویس بهداشتی مجزا.',
        'price' => 45000000,
        'rent_period' => 'monthly',
        'area_sqm' => 45,
        'district_id' => 1,
        'form_data' => [
            'commercial_use' => 'retail', 'ceiling_height_m' => 3.5,
            'street_frontage' => 'main', 'transfer_fee' => 800000000,
            'address_detail' => 'خیابان معالی‌آباد',
        ],
        'visibility_mode' => 'public',
        'created_by' => $publishers['agent'] ?? $publishers['mgr'] ?? 2,
    ],
    [
        'listing_key' => 'ML-DEMO-06',
        'form_template_key' => 'pre_sale_apartment',
        'deal_type' => 'pre_sale',
        'property_type' => 'residential_apartment',
        'title' => 'پیش‌فروش پروژه ۱۴ طبقه — off-plan',
        'description' => 'تحویل ۱۸ ماهه، پرداخت اقساطی. مخاطب: مشاوران املاک.',
        'price' => 6200000000,
        'area_sqm' => 105,
        'rooms' => 2,
        'district_id' => 1,
        'form_data' => [
            'developer_name' => 'سازه‌نوین', 'project_name' => 'برج آسمان',
            'delivery_date' => '۱۴۰۷/۰۶', 'completion_pct' => 35,
            'payment_plan' => '۴۰٪ پیش‌پرداخت، ۶۰٪ اقساط ۱۸ ماهه', 'floor_no' => 7,
        ],
        'visibility_mode' => 'role',
        'visibility_roles' => ['agent', 'district_lead'],
        'created_by' => $publishers['lead'] ?? $publishers['admin'] ?? 2,
    ],
];

foreach ( $samples as $s ) {
    $uid = (int) ($s['created_by'] ?? 0);
    if ( ! $uid ) continue;
    $s['created_by_name'] = mls_user_name($uid);
    mls_upsert_listing($s);
}

echo json_encode([
    'ok' => true,
    'message' => 'آگهی‌های نمونه بازار ملک درج شد',
    'publishers' => $publishers,
    'log' => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
