<?php
/**
 * پر کردن انبار آمار بلوک‌ها (gis_block_stats) — منطقه‌به‌منطقه (۱..۱۲).
 * بدون DISTINCT سنگین؛ هر منطقه یک INSERT...SELECT با ایندکس district_id.
 * http://chat.local/wp-content/plugins/acc-engine/run-rebuild-stats.php?key=run2024
 */
if ( ( $_GET['key'] ?? '' ) !== 'run2024' ) die('کلید اشتباه');

require_once dirname(__FILE__) . '/../../../wp-load.php';
global $wpdb;
set_time_limit(900);
ini_set('memory_limit', '512M');
$pre = $wpdb->prefix;

if (ob_get_level()) ob_end_clean();
ob_implicit_flush(true);
echo str_repeat(' ', 4096); // وادار کردن مرورگر به نمایش زودهنگام

echo '<!DOCTYPE html><html dir="rtl"><head><meta charset="utf-8">
<style>
  body{font-family:monospace;padding:24px;background:#0f172a;color:#e2e8f0;font-size:14px;line-height:2}
  h2{color:#7c3aed}
  .bar-wrap{background:#1e293b;border-radius:8px;height:24px;width:100%;margin:10px 0}
  .bar{background:linear-gradient(90deg,#7c3aed,#a78bfa);height:24px;border-radius:8px;width:0%;transition:width .2s}
  .ok{color:#4ade80} .num{color:#a78bfa;font-weight:bold} .err{color:#f87171}
  table{border-collapse:collapse;margin-top:16px} td,th{border:1px solid #334155;padding:6px 14px}
  th{background:#1e293b}
</style></head><body>';
echo '<h2>🏭 پر کردن انبار آمار بلوک‌ها (منطقه‌به‌منطقه)</h2>';
echo '<div class="bar-wrap"><div class="bar" id="bar"></div></div>';
echo '<p id="status">⏳ پاک کردن جدول...</p>';
flush();

$wpdb->query("TRUNCATE TABLE {$pre}gis_block_stats");

$cols = "(block_code, district_id, neighborhood_id, layer_id,
          total_parcels, cnt_building, cnt_apartment, cnt_shop, cnt_land_only,
          status_active, status_prospect, status_completed, status_suspended,
          center_lat, center_lng, updated_at)";

$t0 = microtime(true);
$total_blocks = 0;
$rows_report  = [];

for ($d = 1; $d <= 12; $d++) {
    $sql = $wpdb->prepare(
        "INSERT INTO {$pre}gis_block_stats {$cols}
         SELECT
            p.block_code, MAX(p.district_id), MAX(p.neighborhood_id), MAX(p.LayerID),
            COUNT(*),
            SUM(p.bld_count  > 0), SUM(p.apt_count > 0), SUM(p.shop_count > 0),
            SUM(p.bld_count = 0 AND p.apt_count = 0 AND p.shop_count = 0),
            SUM(p.status = 'active'), SUM(p.status = 'prospect'),
            SUM(p.status = 'completed'), SUM(p.status = 'suspended'),
            AVG(p.lat), AVG(p.lng), NOW()
         FROM {$pre}gis_parcels p
         WHERE p.status <> 'archived'
           AND p.district_id = %d
           AND p.block_code IS NOT NULL AND p.block_code <> ''
         GROUP BY p.block_code",
        $d
    );

    $r = $wpdb->query($sql);
    if ($r === false) {
        echo "<p class='err'>❌ خطا در منطقه {$d}: " . esc_html($wpdb->last_error) . "</p>";
        flush();
        break;
    }

    $blocks = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$pre}gis_block_stats WHERE district_id = %d", $d
    ) );
    $total_blocks += $blocks;
    $rows_report[] = [$d, $blocks];

    $pct     = round($d / 12 * 100);
    $elapsed = round(microtime(true) - $t0, 1);
    echo "<script>
        document.getElementById('bar').style.width='{$pct}%';
        document.getElementById('status').textContent='✅ منطقه {$d}/۱۲ → {$blocks} بلوک  |  مجموع: {$total_blocks}  |  ⏱ {$elapsed}s';
    </script>";
    flush();
}

/* bump نسخه کش داشبورد */
$ver = (int) get_option('acc_gis_dashboard_ver', 1);
update_option('acc_gis_dashboard_ver', $ver + 1, false);

$parcels = (int) $wpdb->get_var("SELECT SUM(total_parcels) FROM {$pre}gis_block_stats");
$sec     = round(microtime(true) - $t0, 1);

echo "<script>document.getElementById('bar').style.width='100%';</script>";
echo "<h3 class='ok'>✅ انبار پر شد — <span class='num'>" . number_format($total_blocks) . "</span> بلوک، "
   . number_format($parcels) . " پارسل، در {$sec} ثانیه</h3>";

echo '<table><tr><th>منطقه</th><th>بلوک</th></tr>';
foreach ($rows_report as $rr) {
    echo '<tr><td>' . $rr[0] . '</td><td>' . number_format($rr[1]) . '</td></tr>';
}
echo '</table>';

echo '<p style="margin-top:24px;color:#fb923c">⚠️ بعد از موفقیت، این فایل را حذف کنید.</p>';
echo '</body></html>';
