<?php
include_once('./_common.php');

if ($is_guest) {
    alert('판매자센터만 이용가능합니다.', APMS_PARTNER_URL . '/login.php');
}

if ($is_admin !== 'super') {
    alert('최고관리자만 실행할 수 있습니다.', APMS_PARTNER_URL);
}

@set_time_limit(0);

$item_table = $g5['g5_shop_item_table'];

$dry_run = isset($_GET['dry_run']) ? (int)$_GET['dry_run'] : 1; // 기본은 dry-run
$apply = isset($_GET['apply']) ? (int)$_GET['apply'] : 0;
$with_backup = isset($_GET['with_backup']) ? (int)$_GET['with_backup'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 0;
$owner_id = isset($_GET['owner_id']) ? trim((string)$_GET['owner_id']) : '';
$mode = isset($_GET['mode']) ? strtolower(trim((string)$_GET['mode'])) : 'auto_day_only_bug';
$it_ids_raw = isset($_GET['it_ids']) ? trim((string)$_GET['it_ids']) : '';

if ($apply === 1) {
    $dry_run = 0;
}

$allowed_modes = array('auto_day_only_bug', 'normalize_at_least_one');
if (!in_array($mode, $allowed_modes, true)) {
    $mode = 'auto_day_only_bug';
}

$where = array();
$where[] = "(coalesce(it_spec_sales_type, '') <> 'vpn-mall')";
$where[] = "(it_name like 'RPC-%' or it_spec_sales_type like '원격제어%' or ca_id like '10%' or ca_id2 like '10%' or ca_id3 like '10%')";

if ($owner_id !== '') {
    $owner_id_sql = sql_real_escape_string($owner_id);
    $where[] = "(pt_id = '{$owner_id_sql}' or it_spec_partner_id = '{$owner_id_sql}')";
}

if ($it_ids_raw !== '') {
    $ids = preg_split('/[^0-9A-Za-z_\-]+/', $it_ids_raw);
    $ids_clean = array();
    for ($i = 0; $i < count($ids); $i++) {
        $id = trim((string)$ids[$i]);
        if ($id === '') {
            continue;
        }
        $ids_clean[] = "'" . sql_real_escape_string($id) . "'";
    }
    if (count($ids_clean) > 0) {
        $where[] = "it_id in (" . implode(',', $ids_clean) . ")";
    }
}

if ($mode === 'auto_day_only_bug') {
    // 증상 기반 보정:
    // - 1시간만 허용으로 저장되어 있으나
    // - 최소구매시간이 24시간 이상인 경우(사실상 1일 이상 판매 의도)
    // => day만 허용으로 보정
    $where[] = "coalesce(it_is_hour_sale, '0') = '1'";
    $where[] = "coalesce(it_1, '0') <> '1'";
    $where[] = "coalesce(it_2, '0') <> '1'";
    $where[] = "coalesce(it_3, '0') <> '1'";
    $where[] = "coalesce(it_7, '0') <> '1'";
    $where[] = "coalesce(it_buy_min_qty, 0) >= 24";
} else {
    // 최소 1개도 선택되지 않은 비정상 데이터 보정 (day 기본 허용)
    $where[] = "coalesce(it_is_hour_sale, '0') <> '1'";
    $where[] = "coalesce(it_1, '0') <> '1'";
    $where[] = "coalesce(it_2, '0') <> '1'";
    $where[] = "coalesce(it_3, '0') <> '1'";
    $where[] = "coalesce(it_7, '0') <> '1'";
}

$where_sql = implode(' and ', $where);
$limit_sql = ($limit > 0) ? " limit {$limit}" : '';

$preview_sql = "
    select
        it_id,
        it_name,
        pt_id,
        it_spec_partner_id,
        it_spec_sales_type,
        it_is_hour_sale,
        it_1,
        it_2,
        it_3,
        it_7,
        it_buy_min_qty,
        it_buy_max_qty,
        it_update_time
    from {$item_table}
    where {$where_sql}
    order by it_update_time desc, it_id desc
    {$limit_sql}
";

$result = sql_query($preview_sql);
$rows = array();
while ($row = sql_fetch_array($result)) {
    $rows[] = $row;
}

$target_count = count($rows);

header('Content-Type: text/plain; charset=utf-8');

echo "=== RPC Allowed Pricing Plan Migration ===\n";
echo "time       : " . G5_TIME_YMDHIS . "\n";
echo "table      : {$item_table}\n";
echo "mode       : {$mode}\n";
echo "dry_run    : {$dry_run}\n";
echo "apply      : {$apply}\n";
echo "with_backup: {$with_backup}\n";
echo "owner_id   : " . ($owner_id !== '' ? $owner_id : '-') . "\n";
echo "it_ids     : " . ($it_ids_raw !== '' ? $it_ids_raw : '-') . "\n";
echo "limit      : " . ($limit > 0 ? $limit : 'none') . "\n";
echo "targets    : {$target_count}\n";

if ($target_count < 1) {
    echo "\nNo target rows found. Nothing to do.\n";
    exit;
}

echo "\n--- Sample (up to 30 rows) ---\n";
$sample_max = min(30, $target_count);
for ($i = 0; $i < $sample_max; $i++) {
    $r = $rows[$i];
    echo sprintf(
        "[%d] it_id=%s | plans(hour/day/month/year/usage)=%s/%s/%s/%s/%s | min=%s | owner=%s\n",
        $i + 1,
        $r['it_id'],
        $r['it_is_hour_sale'],
        $r['it_1'],
        $r['it_2'],
        $r['it_3'],
        $r['it_7'],
        $r['it_buy_min_qty'],
        ($r['pt_id'] !== '' ? $r['pt_id'] : $r['it_spec_partner_id'])
    );
}

if ($dry_run === 1 || $apply !== 1) {
    echo "\n[DRY-RUN] No data changed.\n";
    echo "\n실행 가이드:\n";
    echo "1) 우선 dry-run 확인 (기본): ?dry_run=1\n";
    echo "2) 기본 버그 보정 적용: ?apply=1&mode=auto_day_only_bug&with_backup=1\n";
    echo "3) 최소 1개 미선택 보정: ?apply=1&mode=normalize_at_least_one&with_backup=1\n";
    echo "4) 특정 품번만 적용: ?apply=1&it_ids=10756,10757\n";
    echo "5) 특정 판매자만 적용: ?apply=1&owner_id=셀러ID\n";
    echo "6) 일부만 시험 적용: ?apply=1&limit=100\n";
    exit;
}

$backup_table = '';
if ($with_backup === 1) {
    $backup_table = $item_table . '_rpc_plan_bak_' . date('YmdHis');

    $sql_create_backup = "create table {$backup_table} like {$item_table}";
    sql_query($sql_create_backup);

    $sql_insert_backup = "
        insert into {$backup_table}
        select *
        from {$item_table}
        where {$where_sql}
        {$limit_sql}
    ";
    sql_query($sql_insert_backup);

    $backup_cnt_row = sql_fetch("select count(*) as cnt from {$backup_table}");
    $backup_cnt = (int)$backup_cnt_row['cnt'];

    echo "\nbackup_table: {$backup_table}\n";
    echo "backup_rows : {$backup_cnt}\n";
}

if ($mode === 'auto_day_only_bug') {
    $update_sql = "
        update {$item_table}
           set it_is_hour_sale = '0',
               it_1 = '1',
               it_2 = '0',
               it_3 = '0',
               it_7 = '0',
               it_update_time = '" . G5_TIME_YMDHIS . "'
         where {$where_sql}
         {$limit_sql}
    ";
} else {
    $update_sql = "
        update {$item_table}
           set it_1 = '1',
               it_update_time = '" . G5_TIME_YMDHIS . "'
         where {$where_sql}
         {$limit_sql}
    ";
}

sql_query($update_sql);
$changed = sql_fetch("select row_count() as cnt");
$changed_cnt = (int)$changed['cnt'];

echo "\nupdated_rows: {$changed_cnt}\n";

if ($backup_table !== '') {
    echo "\n--- Rollback SQL (필요시) ---\n";
    echo "update {$item_table} a\n";
    echo "join {$backup_table} b on a.it_id = b.it_id\n";
    echo "   set a.it_is_hour_sale = b.it_is_hour_sale,\n";
    echo "       a.it_1 = b.it_1,\n";
    echo "       a.it_2 = b.it_2,\n";
    echo "       a.it_3 = b.it_3,\n";
    echo "       a.it_7 = b.it_7,\n";
    echo "       a.it_update_time = b.it_update_time;\n";
}

echo "\nDone.\n";
