<?php
/**
 * نصب ماژول مالیات و حقوق ملک + مشاور AI
 * C:\xampp\php\php.exe run-melk-advisory-install.php
 */
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;

$pre     = $wpdb->prefix;
$pass    = 'Melk1234';
$log     = [];
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';

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

require_once ACC_PATH . 'includes/helpers/melk-advisory-knowledge.php';

$tables = [
    "CREATE TABLE IF NOT EXISTS {$pre}melk_advisory_sessions (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        topic VARCHAR(20) NOT NULL DEFAULT 'both',
        title VARCHAR(200) NULL,
        case_id BIGINT UNSIGNED NULL,
        listing_id BIGINT UNSIGNED NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'open',
        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)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}melk_advisory_messages (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        session_id BIGINT UNSIGNED NOT NULL,
        role VARCHAR(20) NOT NULL,
        body MEDIUMTEXT NOT NULL,
        engine VARCHAR(20) NULL,
        model VARCHAR(80) NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_session (session_id)
    ) {$charset}",
];

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

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

ma_ensure_perm( 'melk.advisory.use', 'استفاده از مشاور مالیات و حقوق ملک' );

if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", 'melk_tax_legal' ) ) ) {
    $wpdb->insert( "{$pre}acl_roles", [
        'slug' => 'melk_tax_legal', 'name' => 'مشاور مالیات و حقوق',
        'description' => 'دسترسی به بانک قوانین و مشاور AI ملک',
        'sort_order' => 19, 'is_system' => 1,
    ] );
    $log[] = 'role:melk_tax_legal';
}

$role_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", 'melk_tax_legal' ) );
$perms   = [ 'melk.view', 'melk.advisory.use', 'melk.listings.view' ];
foreach ( $perms as $pk ) {
    $wpdb->query( $wpdb->prepare(
        "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)", $role_id, $pk
    ) );
}

$grant_roles = [ 'agent', 'legal', 'finance', 'melk_investor', 'melk_coordinator', 'district_lead', 'melk_specialist' ];
foreach ( $grant_roles as $slug ) {
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $slug ) );
    if ( $rid ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
            $rid, 'melk.advisory.use'
        ) );
    }
}

$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.advisory.use'
    ) );
}

if ( get_option( 'acc_melk_ai_enabled', null ) === null ) {
    update_option( 'acc_melk_ai_enabled', '1' );
    $log[] = 'opt:acc_melk_ai_enabled';
}

function ma_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 ] );
        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:{$login}";
    return $id;
}

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

$uid = ma_ensure_user( 'melk_advisory_demo', 'دکتر سارا رضایی — مشاور مالیات و حقوق' );
ma_assign_role( $uid, 'melk_tax_legal' );

require_once ACC_PATH . 'includes/helpers/melk-advisory.php';
require_once ACC_PATH . 'includes/helpers/melk-advisory-ai.php';

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

if ( ! $demo_session ) {
    $sid = Melk_Advisory::create_session( $uid, [
        'topic' => 'both',
        'title' => 'مالیات فروش زمین منطقه ۱',
    ] );
    Melk_Advisory::add_message( $sid, 'user', 'مالیات فروش زمین ۱۲۰۰ متری در منطقه ۱ چه مواردی دارد؟', 'user' );
    Melk_Advisory::add_message( $sid, 'assistant', Melk_Advisory_AI::rule_based_reply(
        'مالیات فروش زمین ۱۲۰۰ متری',
        'tax',
        [ 'district_id' => 1, 'area_sqm' => 1200, 'deal_type' => 'land_sale' ]
    )['reply'], 'rules' );
    $log[] = "demo_session:{$sid}";
}

echo json_encode( [
    'ok'      => true,
    'message' => 'ماژول مالیات و حقوق ملک نصب شد',
    'stats'   => [
        'tax_rules'   => count( Melk_Advisory_Knowledge::tax_rules() ),
        'legal_topics'=> count( Melk_Advisory_Knowledge::legal_topics() ),
    ],
    'demo'    => [
        'login'    => 'melk_advisory_demo',
        'password' => $pass,
        'url'      => '/acc-engine/melk.php',
        'tab'      => 'advisory',
    ],
    'log'     => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
