<?php
// usage:
//   php __CRON/cron_native_vpn_purchase_backfill_cli.php
//   php __CRON/cron_native_vpn_purchase_backfill_cli.php --limit=100
//   php __CRON/cron_native_vpn_purchase_backfill_cli.php --od_id=2026041011223344
//   php __CRON/cron_native_vpn_purchase_backfill_cli.php --mb_id=comviewers
//   php __CRON/cron_native_vpn_purchase_backfill_cli.php --it_id=10687
//   php __CRON/cron_native_vpn_purchase_backfill_cli.php --native-only
//   php __CRON/cron_native_vpn_purchase_backfill_cli.php --apply-fix --limit=50

@chdir(__DIR__ . '/..');

include_once(__DIR__ . '/../_common.php');
include_once(G5_PATH . '/mylib/_common.php');

$limit = 100;
$applyFix = false;
$onlyOdId = '';
$onlyMbId = '';
$onlyItId = '';
$nativeOnly = false;

foreach ($argv as $arg) {
    if (strpos($arg, '--limit=') === 0) {
        $v = (int)substr($arg, 8);
        if ($v > 0) {
            $limit = $v;
        }
        continue;
    }
    if (strpos($arg, '--od_id=') === 0) {
        $onlyOdId = trim((string)substr($arg, 8));
        continue;
    }
    if (strpos($arg, '--mb_id=') === 0) {
        $onlyMbId = trim((string)substr($arg, 8));
        continue;
    }
    if (strpos($arg, '--it_id=') === 0) {
        $onlyItId = trim((string)substr($arg, 8));
        continue;
    }
    if ($arg === '--native-only') {
        $nativeOnly = true;
        continue;
    }
    if ($arg === '--apply-fix') {
        $applyFix = true;
        continue;
    }
}

if (!isset($g5['g5_shop_cart_table'], $g5['g5_shop_order_table'], $g5['g5_shop_item_table'], $g5['g5_shop_cart_for_extension_of_period_table'])) {
    echo json_encode(array(
        'ok' => false,
        'error' => 'missing_required_tables',
        'ts' => date('Y-m-d H:i:s')
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
    exit(1);
}

if (!function_exists('vpnlink_native_purchase_sync_postpaid_tables')) {
    echo json_encode(array(
        'ok' => false,
        'error' => 'missing_sync_function',
        'hint' => 'vpnlink_native_purchase_sync_postpaid_tables not found in mylib/_common.php',
        'ts' => date('Y-m-d H:i:s')
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
    exit(1);
}

$where = array();
$where[] = "c.ct_select='1'";
$where[] = "c.ct_status IN ('입금','완료')";
$where[] = "(i.ca_id LIKE '30%' OR i.ca_id2 LIKE '30%' OR i.ca_id3 LIKE '30%' OR i.it_name LIKE 'VPN-%' OR i.it_name LIKE 'IKEv2%')";

if ($onlyOdId !== '') {
    $where[] = "c.od_id='" . sql_escape_string($onlyOdId) . "'";
}
if ($onlyMbId !== '') {
    $where[] = "c.mb_id='" . sql_escape_string($onlyMbId) . "'";
}
if ($onlyItId !== '') {
    $where[] = "c.it_id='" . sql_escape_string($onlyItId) . "'";
}
if ($nativeOnly) {
    $where[] = "(o.od_memo LIKE '%native_vpn_purchase%' OR o.od_shop_memo LIKE '%native_vpn_purchase%')";
}

$sql = "SELECT
            c.ct_id, c.od_id, c.it_id, c.mb_id, c.pt_id, c.ct_status, c.ct_select, c.pt_datetime,
            c.ct_qty, c.ct_qty_hour, c.ct_qty_for_extension_of_period, c.ct_qty_hour_for_extension_of_period,
            c.extension_of_period_date, c.extension_of_period_to_datetime, c.extension_of_period_price,
            i.it_name, i.it_soldout, i.it_spec_from_datetime, i.it_spec_to_datetime, i.it_spec_buyer_mb_id,
            i.it_spec_buyer_mb_name,
            o.od_status, o.od_settle_case, o.od_time, o.od_memo, o.od_shop_memo
        FROM {$g5['g5_shop_cart_table']} c
        LEFT JOIN {$g5['g5_shop_item_table']} i ON c.it_id = i.it_id
        LEFT JOIN {$g5['g5_shop_order_table']} o ON c.od_id = o.od_id
        WHERE " . implode(' AND ', $where) . "
        ORDER BY c.ct_id DESC
        LIMIT " . (int)$limit;

$res = sql_query($sql, false);

$checkedRows = 0;
$issueRows = 0;
$issuesByOrder = array();
$ordersToFix = array();

for ($i = 0; $row = sql_fetch_array($res); $i++) {
    if (!is_array($row)) {
        continue;
    }

    $checkedRows++;

    $odId = trim((string)$row['od_id']);
    $itId = trim((string)$row['it_id']);
    $mbId = trim((string)$row['mb_id']);
    if ($odId === '' || $itId === '' || $mbId === '') {
        continue;
    }

    $rowIssues = array();

    $ext = sql_fetch("SELECT ct_id
                     FROM {$g5['g5_shop_cart_for_extension_of_period_table']}
                     WHERE od_id='" . sql_escape_string($odId) . "'
                       AND it_id='" . sql_escape_string($itId) . "'
                       AND mb_id='" . sql_escape_string($mbId) . "'
                     ORDER BY ct_id DESC
                     LIMIT 1", false);
    if (!is_array($ext) || empty($ext['ct_id'])) {
        $rowIssues[] = 'extension_row_missing';
    }

    $itSoldout = isset($row['it_soldout']) ? (int)$row['it_soldout'] : 0;
    if ($itSoldout !== 1) {
        $rowIssues[] = 'item_not_soldout';
    }

    $fromDt = trim((string)$row['it_spec_from_datetime']);
    $toDt = trim((string)$row['it_spec_to_datetime']);
    if ($fromDt === '' || $fromDt === '0000-00-00 00:00:00') {
        $rowIssues[] = 'item_spec_from_missing';
    }
    if ($toDt === '' || $toDt === '0000-00-00 00:00:00') {
        $rowIssues[] = 'item_spec_to_missing';
    }

    $buyerMbId = trim((string)$row['it_spec_buyer_mb_id']);
    if ($buyerMbId !== $mbId) {
        $rowIssues[] = 'item_buyer_mismatch';
    }

    $extDate = trim((string)$row['extension_of_period_date']);
    $extToDate = trim((string)$row['extension_of_period_to_datetime']);
    if ($extDate === '' || $extDate === '0000-00-00 00:00:00') {
        $rowIssues[] = 'cart_extension_date_missing';
    }
    if ($extToDate === '' || $extToDate === '0000-00-00 00:00:00') {
        $rowIssues[] = 'cart_extension_to_missing';
    }

    if (count($rowIssues) < 1) {
        continue;
    }

    $issueRows++;

    $orderKey = $odId . '|' . $mbId;
    if (!isset($issuesByOrder[$orderKey])) {
        $issuesByOrder[$orderKey] = array(
            'od_id' => $odId,
            'mb_id' => $mbId,
            'rows' => array(),
            'issue_types' => array()
        );
    }

    foreach ($rowIssues as $t) {
        $issuesByOrder[$orderKey]['issue_types'][$t] = true;
    }

    $issuesByOrder[$orderKey]['rows'][] = array(
        'ct_id' => (int)$row['ct_id'],
        'it_id' => $itId,
        'it_name' => trim((string)$row['it_name']),
        'ct_status' => trim((string)$row['ct_status']),
        'pt_datetime' => trim((string)$row['pt_datetime']),
        'issues' => $rowIssues
    );

    $ordersToFix[$orderKey] = array('od_id' => $odId, 'mb_id' => $mbId);
}

$fixTried = 0;
$fixSuccess = 0;
$fixFailed = 0;
$fixResults = array();

if ($applyFix && count($ordersToFix) > 0) {
    foreach ($ordersToFix as $orderKey => $keyInfo) {
        $fixTried++;

        $odId = $keyInfo['od_id'];
        $mbId = $keyInfo['mb_id'];
        $member = get_member($mbId);

        $ret = vpnlink_native_purchase_sync_postpaid_tables($odId, $mbId, $member);
        if (!empty($ret['ok'])) {
            $fixSuccess++;
        } else {
            $fixFailed++;
        }

        $fixResults[] = array(
            'od_id' => $odId,
            'mb_id' => $mbId,
            'result' => $ret
        );
    }
}

$outRows = array();
foreach ($issuesByOrder as $orderKey => $v) {
    $issueTypes = array_keys($v['issue_types']);
    sort($issueTypes);
    $outRows[] = array(
        'od_id' => $v['od_id'],
        'mb_id' => $v['mb_id'],
        'issue_types' => $issueTypes,
        'rows' => $v['rows']
    );
}

echo json_encode(array(
    'ok' => true,
    'apply_fix' => $applyFix,
    'native_only' => $nativeOnly,
    'filters' => array(
        'limit' => $limit,
        'od_id' => $onlyOdId,
        'mb_id' => $onlyMbId,
        'it_id' => $onlyItId
    ),
    'checked_rows' => $checkedRows,
    'issue_rows' => $issueRows,
    'issue_orders' => count($outRows),
    'fix_tried' => $fixTried,
    'fix_success' => $fixSuccess,
    'fix_failed' => $fixFailed,
    'rows' => $outRows,
    'fix_results' => $fixResults,
    'ts' => date('Y-m-d H:i:s')
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
