<?php
/**
 * نصب ماژول سرمایه‌گذار اقتصاد ملک
 * C:\xampp\php\php.exe run-melk-investor-install.php
 * C:\xampp\php\php.exe run-melk-investor-install.php --reset
 */
declare(strict_types=1);

if ( ! defined( 'ACC_BASE_PATH' ) ) {
    define( 'ACC_BASE_PATH', __DIR__ );
    require __DIR__ . '/standalone/bootstrap.php';
}

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

$reset = in_array( '--reset', $argv ?? [], true );
$pre   = $wpdb->prefix;
$pass  = 'Melk1234';
$log   = [];
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';

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

require_once ACC_PATH . 'includes/helpers/melk-investor.php';
require_once ACC_PATH . 'includes/helpers/acl-functions.php';

$tables = [
    "CREATE TABLE IF NOT EXISTS {$pre}melk_investor_profiles (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        display_title VARCHAR(200) NULL,
        wealth_tier VARCHAR(30) NOT NULL DEFAULT 'premium',
        bio TEXT NULL,
        phone VARCHAR(30) NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'approved',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY idx_user (user_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}melk_investment_criteria (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        title VARCHAR(200) NOT NULL,
        deal_types JSON NULL,
        property_types JSON NULL,
        district_ids JSON NULL,
        neighborhood_ids JSON NULL,
        min_area_sqm DECIMAL(12,2) NULL,
        max_area_sqm DECIMAL(12,2) NULL,
        budget_min DECIMAL(18,2) NULL,
        budget_max DECIMAL(18,2) NULL,
        notes TEXT NULL,
        alert_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_user (user_id),
        KEY idx_alert (alert_active)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}melk_listing_matches (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        criteria_id BIGINT UNSIGNED NOT NULL,
        listing_id BIGINT UNSIGNED NOT NULL,
        investor_user_id BIGINT UNSIGNED NOT NULL,
        match_score TINYINT UNSIGNED NOT NULL DEFAULT 0,
        seen_at DATETIME NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY idx_crit_list (criteria_id, listing_id),
        KEY idx_investor (investor_user_id),
        KEY idx_unseen (investor_user_id, seen_at)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}melk_investor_expert_requests (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        listing_id BIGINT UNSIGNED NULL,
        match_id BIGINT UNSIGNED NULL,
        expert_types JSON NOT NULL,
        subject VARCHAR(300) NOT NULL,
        description TEXT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'pending',
        expert_user_id BIGINT UNSIGNED NULL,
        response_text TEXT NULL,
        answered_at DATETIME NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_user (user_id),
        KEY idx_status (status)
    ) {$charset}",
];

foreach ( $tables as $sql ) {
    $wpdb->query( $sql );
    $log[] = 'table_ok';
}

if ( $reset ) {
    $wpdb->query( "DELETE FROM {$pre}melk_investor_expert_requests" );
    $wpdb->query( "DELETE FROM {$pre}melk_listing_matches" );
    $wpdb->query( "DELETE FROM {$pre}melk_investment_criteria" );
    $wpdb->query( "DELETE FROM {$pre}melk_investor_profiles" );
    $wpdb->query( "DELETE FROM {$pre}melk_listings WHERE listing_key LIKE 'ML-INV-%'" );
    $log[] = 'reset';
}

function mi_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 mi_ensure_perm( string $key, string $label ): void {
    global $wpdb, $log;
    $pre = $wpdb->prefix;
    $exists = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}acl_permissions WHERE permission_key = %s", $key
    ) );
    if ( ! $exists ) {
        $wpdb->insert( "{$pre}acl_permissions", [
            'permission_key' => $key,
            'label'          => $label,
            'group_slug'     => 'melk',
            'sort_order'     => 0,
        ] );
        $log[] = "perm:{$key}";
    }
}

mi_ensure_perm( 'melk.investor.manage', 'مدیریت پورتفوی سرمایه‌گذاری ملک' );

if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", 'melk_investor' ) ) ) {
    $wpdb->insert( "{$pre}acl_roles", [
        'slug'        => 'melk_investor',
        'name'        => 'سرمایه‌گذار ملک',
        'description' => 'سرمایه‌گذاران ثروتمند — معیار خرید و کارشناسی',
        'sort_order'  => 18,
        'is_system'   => 1,
    ] );
    $log[] = 'role:melk_investor';
}

$role_id = mi_role_id( 'melk_investor' );
$inv_perms = [ 'melk.view', 'melk.listings.view', 'melk.investor.manage' ];
foreach ( $inv_perms as $pk ) {
    $wpdb->query( $wpdb->prepare(
        "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
        $role_id, $pk
    ) );
}

$super_id = (int) $wpdb->get_var( "SELECT id FROM {$pre}acl_roles WHERE slug='super_admin' LIMIT 1" );
if ( $super_id ) {
    $wpdb->query( $wpdb->prepare(
        "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
        $super_id, 'melk.investor.manage'
    ) );
}

function mi_ensure_user( string $login, string $name ): 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[] = "user:updated:{$login}";
        return $id;
    }
    $max = (int) $wpdb->get_var( "SELECT COALESCE(MAX(ID), 0) FROM {$wpdb->users}" );
    $id  = $max + 1;
    $wpdb->insert( "{$wpdb->users}", [
        'ID'              => $id,
        'user_login'      => $login,
        'user_pass'       => wp_hash_password( $pass ),
        'user_nicename'   => sanitize_title( $login ),
        'user_email'      => $login . '@melk.test',
        'user_registered' => current_time( 'mysql' ),
        'display_name'    => $name,
        'user_status'     => 0,
    ] );
    $log[] = "user:created:{$login}";
    return $id;
}

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

$uid_investor = mi_ensure_user( 'melk_investor_demo', 'دکتر کریم احمدی — سرمایه‌گذار' );
mi_assign_role( $uid_investor, 'melk_investor' );

$uid_agent = (int) $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_login='melk_agent' LIMIT 1" );
if ( ! $uid_agent ) {
    $uid_agent = mi_ensure_user( 'melk_agent', 'مشاور املاک — رضا کریمی' );
    mi_assign_role( $uid_agent, 'agent' );
}

$uid_mun = (int) $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_login='melk_shahrdari' LIMIT 1" );
$uid_reg = (int) $wpdb->get_var( "SELECT ID FROM {$wpdb->users} WHERE user_login='melk_registry' LIMIT 1" );

Melk_Investor::save_profile( $uid_investor, [
    'display_title' => 'دکتر کریم احمدی',
    'wealth_tier'   => 'ultra',
    'bio'           => 'سرمایه‌گذار در زمین‌های مسکونی منطقه ۱ — علاقه‌مند به مشارکت در ساخت با کارشناسی کامل.',
    'phone'         => '09171234567',
] );

$crit_exists = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}melk_investment_criteria WHERE user_id=%d LIMIT 1", $uid_investor
) );

if ( ! $crit_exists ) {
    Melk_Investor::create_criteria( $uid_investor, [
        'title'            => 'زمین منطقه ۱ — محلات ۷ و ۱۰ (حداقل ۱۰۰۰ متر)',
        'deal_types'       => [ 'land_sale', 'partnership' ],
        'property_types'   => [ 'residential_land' ],
        'district_ids'     => [ 1 ],
        'neighborhood_ids' => [ 7, 10 ],
        'min_area_sqm'     => 1000,
        'budget_max'       => 50000000000,
        'notes'            => 'فقط زمین با سند تک‌برگ — در صورت وجود آگهی مناسب اطلاع دهید.',
        'alert_active'     => 1,
    ] );
    $crit_id = (int) $wpdb->insert_id;
    $log[] = "criteria:{$crit_id}";
} else {
    $crit_id = $crit_exists;
}

function mi_upsert_listing( array $row ): int {
    global $wpdb, $pre, $log;
    $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'],
        'title'           => $row['title'],
        'description'     => $row['description'] ?? '',
        'price'           => $row['price'] ?? null,
        'area_sqm'        => $row['area_sqm'] ?? null,
        'district_id'     => $row['district_id'] ?? null,
        'neighborhood_id' => $row['neighborhood_id'] ?? null,
        'status'          => 'active',
        'visibility_mode' => 'network',
        'created_by'      => $row['created_by'],
        'created_by_name' => $row['created_by_name'],
    ];
    if ( $existing ) {
        $wpdb->update( "{$pre}melk_listings", $data, [ 'id' => $existing ] );
        $log[] = "listing:updated:{$key}";
        return $existing;
    }
    $data['listing_key'] = $key;
    $wpdb->insert( "{$pre}melk_listings", $data );
    $id = (int) $wpdb->insert_id;
    $log[] = "listing:created:{$key}";
    return $id;
}

$pub_name = $wpdb->get_var( $wpdb->prepare(
    "SELECT display_name FROM {$wpdb->users} WHERE ID=%d", $uid_agent
) ) ?: 'مشاور املاک';

$listings = [
    [
        'listing_key'     => 'ML-INV-01',
        'deal_type'       => 'land_sale',
        'property_type'   => 'residential_land',
        'title'           => 'زمین ۱۲۰۰ متری — منطقه ۱ محله ۷',
        'description'     => 'زمین مسکونی با سند تک‌برگ، دو بر خیابان، مناسب مشارکت در ساخت.',
        'price'           => 18000000000,
        'area_sqm'        => 1200,
        'district_id'     => 1,
        'neighborhood_id' => 7,
        'created_by'      => $uid_agent,
        'created_by_name' => $pub_name,
    ],
    [
        'listing_key'     => 'ML-INV-02',
        'deal_type'       => 'partnership',
        'property_type'   => 'residential_land',
        'title'           => 'مشارکت در ساخت — زمین ۱۵۰۰ متری محله ۱۰',
        'description'     => 'مالک ۴۰٪ — سازنده ۶۰٪. مجوز ساخت در دست اقدام.',
        'price'           => null,
        'area_sqm'        => 1500,
        'district_id'     => 1,
        'neighborhood_id' => 10,
        'created_by'      => $uid_agent,
        'created_by_name' => $pub_name,
    ],
    [
        'listing_key'     => 'ML-INV-03',
        'deal_type'       => 'land_sale',
        'property_type'   => 'residential_land',
        'title'           => 'زمین ۸۰۰ متری — منطقه ۱ (زیر حد معیار)',
        'description'     => 'این آگهی نباید به سرمایه‌گذار match شود (متراژ کم).',
        'price'           => 9000000000,
        'area_sqm'        => 800,
        'district_id'     => 1,
        'neighborhood_id' => 7,
        'created_by'      => $uid_agent,
        'created_by_name' => $pub_name,
    ],
];

$listing_ids = [];
foreach ( $listings as $l ) {
    $listing_ids[ $l['listing_key'] ] = mi_upsert_listing( $l );
    Melk_Investor::match_listing( $listing_ids[ $l['listing_key'] ] );
}

$match_id = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}melk_listing_matches WHERE investor_user_id=%d AND listing_id=%d LIMIT 1",
    $uid_investor, $listing_ids['ML-INV-01']
) );

$req_exists = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}melk_investor_expert_requests WHERE user_id=%d LIMIT 1", $uid_investor
) );

if ( ! $req_exists && $match_id ) {
    $wpdb->insert( "{$pre}melk_investor_expert_requests", [
        'user_id'        => $uid_investor,
        'listing_id'     => $listing_ids['ML-INV-01'],
        'match_id'       => $match_id,
        'expert_types'   => wp_json_encode( [ 'municipality', 'registry', 'legal' ] ),
        'subject'        => 'بررسی سند و بلامانع شهرداری — زمین ۱۲۰۰ متری محله ۷',
        'description'    => 'لطفاً وضعیت ثبت، محدودیت طرح تفصیلی و هرگونه بدهی شهرداری را اعلام کنید.',
        'status'         => 'answered',
        'expert_user_id' => $uid_reg ?: $uid_mun,
        'response_text'  => "کارشناس ثبت: سند تک‌برگ به نام مالک فعلی — بدون رهن یا توقیف.\n"
            . "کارشناس شهرداری: ملک در بافت مسکونی — طرح تفصیلی منطقه ۱ مجاز به ساخت تا ۵ طبقه.\n"
            . "وکیل حقوقی: قرارداد مشارکت پیشنهادی استاندارد — توصیه به کارشناسی رسمی قبل از امضا.",
        'answered_at'    => current_time( 'mysql' ),
        'created_at'     => gmdate( 'Y-m-d H:i:s', strtotime( '-2 days' ) ),
    ] );
    $log[] = 'expert_request:seeded';

    $wpdb->insert( "{$pre}melk_investor_expert_requests", [
        'user_id'      => $uid_investor,
        'listing_id'   => $listing_ids['ML-INV-02'],
        'match_id'     => null,
        'expert_types' => wp_json_encode( [ 'municipality' ] ),
        'subject'      => 'وضعیت مجوز ساخت — مشارکت محله ۱۰',
        'description'  => 'آیا پروانه ساخت صادر شده یا در دست بررسی است؟',
        'status'       => 'pending',
        'created_at'   => current_time( 'mysql' ),
    ] );
    $log[] = 'expert_request:pending';
}

$matches = Melk_Investor::list_matches( $uid_investor );

echo json_encode( [
    'ok'      => true,
    'message' => 'ماژول سرمایه‌گذار ملک نصب شد',
    'demo'    => [
        'login'    => 'melk_investor_demo',
        'password' => $pass,
        'url'      => '/acc-engine/melk.php',
        'tab'      => 'investor',
    ],
    'matches_count' => count( $matches ),
    'log'     => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
