<?php
/**
 * نصب پورتال تأمین‌کننده HVAC — جداول، نقش، مجوز
 * php run-service-supplier-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;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}svc_supplier_profiles (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL,
    company_name VARCHAR(200) NOT NULL DEFAULT '',
    contact_name VARCHAR(120) NOT NULL DEFAULT '',
    phone VARCHAR(30) NOT NULL DEFAULT '',
    email VARCHAR(120) NOT NULL DEFAULT '',
    address VARCHAR(255) NOT NULL DEFAULT '',
    city VARCHAR(80) NOT NULL DEFAULT '',
    description TEXT NULL,
    is_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),
    UNIQUE KEY user_id (user_id)
) {$charset}" );

$wpdb->query( "CREATE TABLE IF NOT EXISTS {$pre}svc_supplier_catalog (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    supplier_user_id BIGINT UNSIGNED NOT NULL,
    item_type VARCHAR(20) NOT NULL DEFAULT 'part',
    name VARCHAR(200) NOT NULL DEFAULT '',
    sku VARCHAR(100) NOT NULL DEFAULT '',
    description TEXT NULL,
    unit VARCHAR(30) NOT NULL DEFAULT 'عدد',
    brand VARCHAR(80) NOT NULL DEFAULT '',
    model VARCHAR(80) NOT NULL DEFAULT '',
    price DECIMAL(15,2) NOT NULL DEFAULT 0,
    stock_qty INT NOT NULL DEFAULT 0,
    in_stock TINYINT(1) NOT NULL DEFAULT 1,
    lead_days INT NOT NULL DEFAULT 3,
    is_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 supplier_user_id (supplier_user_id),
    KEY sku (sku),
    KEY item_type (item_type)
) {$charset}" );

$perms = [
    [ 'service.supplier.panel', 'پنل تأمین‌کننده', 'service', 'supplier', 'panel' ],
    [ 'service.supplier.catalog', 'مدیریت کاتالوگ تأمین‌کننده', 'service', 'supplier', 'catalog' ],
];
foreach ( $perms as [ $key, $label, $module, $resource, $action ] ) {
    $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,
            'module'         => $module,
            'resource'       => $resource,
            'action'         => $action,
            'is_system'      => 1,
        ] );
    }
}

$role_id = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}acl_roles WHERE slug = %s", 'service_supplier'
) );
if ( ! $role_id ) {
    $wpdb->insert( "{$pre}acl_roles", [
        'slug'        => 'service_supplier',
        'name'        => 'تأمین‌کننده خدمات',
        'description' => 'مدیریت کاتالوگ و سفارشات قطعات HVAC',
        'is_system'   => 1,
    ] );
    $role_id = (int) $wpdb->insert_id;
}

$role_perms = [ 'service.supplier.panel', 'service.supplier.catalog' ];
foreach ( $role_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 ) {
    foreach ( array_merge( $role_perms, [ 'service.view' ] ) as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)",
            $super_id, $pk
        ) );
    }
}

update_option( 'acc_engine_db_version', '18.0' );

echo json_encode( [
    'success' => true,
    'db_version' => '18.0',
    'tables' => [ 'svc_supplier_profiles', 'svc_supplier_catalog' ],
    'role_id' => $role_id,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
