#!/usr/bin/env python3
import sys
path = '/var/www/runmystore/products.php'
with open(path, 'r', encoding='utf-8') as f:
    code = f.read()

changes = 0

# 1. SQL: добави sold_30d и days_no_sale
old1 = "(SELECT COUNT(*) FROM products ch WHERE ch.parent_id=p.id AND ch.tenant_id=p.tenant_id AND ch.is_active=1) AS variant_count"
new1 = """(SELECT COUNT(*) FROM products ch WHERE ch.parent_id=p.id AND ch.tenant_id=p.tenant_id AND ch.is_active=1) AS variant_count,
           COALESCE((SELECT SUM(si.quantity) FROM sale_items si JOIN sales sl ON sl.id=si.sale_id WHERE si.product_id=p.id AND sl.tenant_id=p.tenant_id AND sl.status='completed' AND sl.created_at>=DATE_SUB(NOW(),INTERVAL 30 DAY)),0) AS sold_30d,
           DATEDIFF(NOW(),COALESCE((SELECT MAX(sl.created_at) FROM sale_items si JOIN sales sl ON sl.id=si.sale_id WHERE si.product_id=p.id AND sl.tenant_id=p.tenant_id AND sl.status='completed'),p.created_at)) AS days_no_sale"""
if old1 in code:
    code = code.replace(old1, new1); changes += 1; print("1. SQL sold_30d+days_no_sale OK")
else:
    print("1. SKIP - not found")

# 2. cnt_hot, cnt_zombie, capital
old2 = "$cnt_low = 0; $cnt_out = 0;\nforeach ($all_products as $p) {\n    if ($p['total_stock'] == 0) $cnt_out++;\n    elseif ($p['min_qty'] > 0 && $p['total_stock'] <= $p['min_qty']) $cnt_low++;\n}"
new2 = """$cnt_low = 0; $cnt_out = 0; $cnt_hot = 0; $cnt_zombie = 0;
foreach ($all_products as $p) {
    if ($p['total_stock'] == 0) $cnt_out++;
    elseif ($p['min_qty'] > 0 && $p['total_stock'] <= $p['min_qty']) $cnt_low++;
    if (($p['sold_30d'] ?? 0) > 10) $cnt_hot++;
    if (($p['days_no_sale'] ?? 0) > 30 && $p['total_stock'] > 0) $cnt_zombie++;
}
$capital = DB::run("SELECT COALESCE(SUM(i.quantity*p.cost_price),0) FROM inventory i JOIN products p ON p.id=i.product_id WHERE i.tenant_id=?", [$tenant_id])->fetchColumn();"""
if old2 in code:
    code = code.replace(old2, new2); changes += 1; print("2. cnt_hot+zombie+capital OK")
else:
    print("2. SKIP - not found")

# 3. hot/zombie filters
old3 = "elseif ($filter === 'out') $products = array_values(array_filter($all_products, fn($p) => $p['total_stock'] == 0));\nelse $products = $all_products;"
new3 = """elseif ($filter === 'out') $products = array_values(array_filter($all_products, fn($p) => $p['total_stock'] == 0));
elseif ($filter === 'hot') $products = array_values(array_filter($all_products, fn($p) => ($p['sold_30d'] ?? 0) > 10));
elseif ($filter === 'zombie') $products = array_values(array_filter($all_products, fn($p) => ($p['days_no_sale'] ?? 0) > 30 && $p['total_stock'] > 0));
else $products = $all_products;"""
if old3 in code:
    code = code.replace(old3, new3); changes += 1; print("3. hot/zombie filters OK")
else:
    print("3. SKIP - not found")

# 4. Capital badge
old4 = '<h1 class="page-title">Артикули</h1>'
new4 = """<h1 class="page-title">Артикули</h1>
    <span style="font-size:11px;font-weight:700;color:#a5b4fc;background:rgba(99,102,241,.1);border:1px solid rgba(99,102,241,.2);border-radius:20px;padding:4px 10px">\\xf0\\x9f\\x92\\xb0 \\xe2\\x82\\xac<?= number_format($capital,0,',',' ') ?></span>"""
if old4 in code:
    badge = '<h1 class="page-title">\xd0\x90\xd1\x80\xd1\x82\xd0\xb8\xd0\xba\xd1\x83\xd0\xbb\xd0\xb8</h1>'
    new_badge = badge + '\n    <span style="font-size:11px;font-weight:700;color:#a5b4fc;background:rgba(99,102,241,.1);border:1px solid rgba(99,102,241,.2);border-radius:20px;padding:4px 10px">\xf0\x9f\x92\xb0 \xe2\x82\xac<?= number_format($capital,0,\',\',\' \') ?></span>'
    code = code.replace(old4, old4 + '\n    <span style="font-size:11px;font-weight:700;color:#a5b4fc;background:rgba(99,102,241,.1);border:1px solid rgba(99,102,241,.2);border-radius:20px;padding:4px 10px">💰 €<?= number_format($capital,0,\',\',\' \') ?></span>', 1)
    changes += 1; print("4. Capital badge OK")
else:
    print("4. SKIP - not found")

# 5. Hot/Zombie tabs
old5 = """<button class="ftab <?= $filter==='out'?'active':'' ?>" onclick="setFilter('out')">Изчерпани <span class="cnt <?= $cnt_out>0?'d':'' ?>"><?= $cnt_out ?></span></button>"""
new5 = old5 + """
    <button class="ftab <?= $filter==='hot'?'active':'' ?>" onclick="setFilter('hot')">🔥 Хит <span class="cnt"><?= $cnt_hot ?></span></button>
    <button class="ftab <?= $filter==='zombie'?'active':'' ?>" onclick="setFilter('zombie')">❄️ Застояли <span class="cnt"><?= $cnt_zombie ?></span></button>"""
if old5 in code:
    code = code.replace(old5, new5, 1); changes += 1; print("5. Hot/Zombie tabs OK")
else:
    print("5. SKIP - not found")

# 6. Hot/Zombie tags on cards
old6 = """<?php if($p['supplier_name']): ?><span class="tag ts"><?= htmlspecialchars($p['supplier_name']) ?></span><?php endif; ?>"""
new6 = """<?php if(($p['sold_30d'] ?? 0) > 10): ?><span class="tag" style="color:#f59e0b;background:rgba(245,158,11,.1);border-color:rgba(245,158,11,.2)">🔥 Хит</span><?php endif; ?>
      <?php if(($p['days_no_sale'] ?? 0) > 30 && $qty > 0): ?><span class="tag" style="color:#6b7280;background:rgba(107,114,128,.08);border-color:rgba(107,114,128,.15)">❄️ <?= $p['days_no_sale'] ?>д</span><?php endif; ?>
      <?php if($p['supplier_name']): ?><span class="tag ts"><?= htmlspecialchars($p['supplier_name']) ?></span><?php endif; ?>"""
if old6 in code:
    code = code.replace(old6, new6, 1); changes += 1; print("6. Hot/Zombie card tags OK")
else:
    print("6. SKIP - not found")

with open(path, 'w', encoding='utf-8') as f:
    f.write(code)
print(f"\nDone: {changes}/6 patches applied")
