<?php
/**
 * Оновлений щоденний автономний звіт ZooBox в Telegram
 * З фільтрацією ботів, сканерів, технічних запитів та сесій власника
 * Час запуску в cron: щодня о 09:45
 */

define('DOING_CRON', true);

// Підключення WordPress / WooCommerce (якщо є)
$wp_load = '/var/www/chd2295874/www/zoobox.com.ua/wp-load.php';
if (file_exists($wp_load)) {
    require_once $wp_load;
}

$bot_token = '8558380975:AAHdAMm9GFhFLs7mdD_x8zRJh30g0a1mwYA';
$chat_id = '848752933';

// Період: останні 24 години
$now = time();
$window_hours = 24;
$start_ts = $now - ($window_hours * 3600);

// IP-адреси власника та серверів для виключення
$owner_ips = [
    '188.163.30.195',
    '78.137.3.127',
    '31.43.155.101',
    '107.172.238.82',
    '127.0.0.1',
    '176.111.33.20'
];

// Відомі сигнатури ботів у User-Agent
$bot_signatures = [
    'googlebot'           => 'Googlebot 🤖',
    'google-inspection'   => 'Google Search Console 🔍',
    'googleother'         => 'GoogleOther 🤖',
    'google-xrawler'      => 'Google Merchant Feed 🛍️',
    'google-read-aloud'   => 'Google Read-Aloud 📱',
    'mediapartners-google'=> 'Google AdSense/Media 🤖',
    'bingbot'             => 'Bingbot 🤖',
    'bingpreview'         => 'Bing Preview 🤖',
    'yandex'              => 'Yandex Bot 🤖',
    'duckduckbot'         => 'DuckDuckGo 🤖',
    'baiduspider'         => 'Baidu 🤖',
    'semrush'             => 'Semrush (SEO) 🔍',
    'ahrefs'              => 'Ahrefs (SEO) 🔍',
    'mj12bot'             => 'Majestic Bot 🤖',
    'dotbot'              => 'DotBot 🤖',
    'petalbot'            => 'PetalBot (Huawei) 🤖',
    'bytespider'          => 'ByteSpider (TikTok) 🤖',
    'applebot'            => 'Applebot 🤖',
    'facebookexternalhit' => 'Facebook / Meta 📱',
    'meta-webindexer'     => 'Facebook / Meta 📱',
    'telegrambot'         => 'Telegram Preview 📱',
    'viber'               => 'Viber Preview 📱',
    'whatsapp'            => 'WhatsApp Preview 📱',
    'twitterbot'          => 'Twitter/X Bot 📱',
    'slackbot'            => 'Slack Bot 📱',
    'curl'                => 'cURL ⚙️',
    'python'              => 'Python Script ⚙️',
    'wget'                => 'Wget ⚙️',
    'headlesschrome'      => 'Headless Chrome 🤖',
    'puppeteer'           => 'Puppeteer/Scraper 🤖',
    'playwright'          => 'Playwright/Scraper 🤖',
    'cms-checker'         => 'CMS Checker 🔍',
    'builtwith'           => 'BuiltWith 🔍',
    'dataprovider'        => 'DataProvider 🔍',
    'certsignal'          => 'CertSignal 🔒',
    'fossick'             => 'FossickBot 🤖'
];

// Шляхи пошуку вразливостей (сканери)
$scanner_paths = [
    '/backup', '/bk', '/bc', '/old', '/home', '/main', '/test', '/tmp',
    '/sql', '/dump', '/wordpress', '/phpinfo', '.env', '.git', '.svn',
    'wp-config', 'setup.php', 'xmlrpc.php', 'install.php', 'eval-stdin',
    'solr', 'actuator', 'alfa', 'wso', 'shell', 'axis2', 'phpunit',
    'cgi-bin', 'webdav', 'phpmyadmin', 'pma', '/wp-login.php'
];

// Технічні / службові файли
$technical_paths = [
    '/robots.txt', '/google-feed.xml', '/sitemap.xml', '/sitemap_index.xml',
    '/post-sitemap.xml', '/product-sitemap.xml', '/category-sitemap.xml',
    '/page-sitemap.xml', '/ads.txt', '/favicon.ico'
];

// Пошук лог-файлів
$log_dir = '/var/www/chd2295874/logs';
$log_files = [];
if (is_dir($log_dir)) {
    $main_log = $log_dir . '/zoobox.com.ua.access.log';
    if (file_exists($main_log)) {
        $log_files[] = $main_log;
    }
    // Ротовані логи
    $rot_files = glob($log_dir . '/zoobox.com.ua.access.log*');
    if ($rot_files) {
        foreach ($rot_files as $rf) {
            if ($rf !== $main_log && filemtime($rf) >= $start_ts - 86400) {
                $log_files[] = $rf;
            }
        }
    }
}

// Якщо запущено на локалі або VPS без доступу до Cityhost логів
if (empty($log_files)) {
    if (file_exists('/tmp/v_report.txt')) {
        $log_files[] = '/tmp/v_report.txt';
    } elseif (file_exists(__DIR__ . '/v_report.txt')) {
        $log_files[] = __DIR__ . '/v_report.txt';
    }
}

if (empty($log_files)) {
    exit("No log files found.\n");
}

// Парсинг логів
$bot_hits = [];
$googlebot_pages = [];
$scanner_hits = 0;
$owner_hits = 0;
$tech_hits = 0;
$sessions = [];

foreach ($log_files as $file_path) {
    $lines = [];
    if (substr($file_path, -3) === '.gz' && function_exists('gzfile')) {
        $lines = gzfile($file_path);
    } else {
        $lines = file($file_path);
    }
    if (!$lines) continue;

    foreach ($lines as $line) {
        if (!preg_match('/^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) ([^ "]+) [^"]*" (\d+) (\d+) "([^"]*)" "([^"]*)"/', $line, $m)) {
            continue;
        }

        $ip = $m[1];
        $time_str = $m[2];
        $method = $m[3];
        $url = $m[4];
        $status = (int)$m[5];
        $ref = $m[7];
        $ua = $m[8];

        // Перевірка часу (вікно 24 години)
        $dt = DateTime::createFromFormat('d/M/Y:H:i:s O', $time_str);
        $ts = $dt ? $dt->getTimestamp() : 0;
        
        // Фільтр за часом: якщо файл v_report.txt використовується як тест, відсікаємо старіші ніж 24г від останнього запису
        if ($ts && $ts < $start_ts) {
            // Для реального часу перевіряємо $start_ts
            // Але якщо логи від позавчора, враховуємо це
            continue;
        }

        // Власник сайту або внутрішні cron-запити
        if (in_array($ip, $owner_ips, true) || strpos($ua, 'WordPress') !== false) {
            $owner_hits++;
            continue;
        }

        $ua_lower = strtolower($ua);
        $url_lower = strtolower($url);

        // Перевірка ботів за User-Agent
        $found_bot = null;
        foreach ($bot_signatures as $sig => $label) {
            if (strpos($ua_lower, $sig) !== false) {
                $found_bot = $label;
                break;
            }
        }
        if (!$found_bot && (strpos($ua_lower, 'bot') !== false || strpos($ua_lower, 'crawler') !== false || strpos($ua_lower, 'spider') !== false)) {
            $found_bot = 'Інші боти 🤖';
        }

        if ($found_bot) {
            $bot_hits[$found_bot] = ($bot_hits[$found_bot] ?? 0) + 1;
            if (strpos($ua_lower, 'googlebot') !== false && $status === 200) {
                if (!preg_match('/\.(xml|txt|ico|png|jpg|css|js)$/i', $url)) {
                    $clean_url = urldecode(urldecode($url));
                    $googlebot_pages[$clean_url] = ($googlebot_pages[$clean_url] ?? 0) + 1;
                }
            }
            continue;
        }

        // Перевірка сканерів вразливостей за URL
        $is_scanner = false;
        foreach ($scanner_paths as $sp) {
            if (strpos($url_lower, $sp) !== false) {
                $is_scanner = true;
                break;
            }
        }
        if ($is_scanner) {
            $scanner_hits++;
            $sessions[$ip]['is_scanner'] = true;
            continue;
        }

        // Перевірка технічних файлів
        $is_tech = false;
        foreach ($technical_paths as $tp) {
            if ($url_lower === $tp || strpos($url_lower, $tp) === 0) {
                $is_tech = true;
                break;
            }
        }
        if ($is_tech) {
            $tech_hits++;
            continue;
        }

        // Статичний файл
        $is_static = preg_match('/\.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|webp)(\?.*)?$/i', $url);

        if (!isset($sessions[$ip]['requests'])) {
            $sessions[$ip]['requests'] = [];
        }

        $sessions[$ip]['requests'][] = [
            'time' => $time_str,
            'ts' => $ts,
            'method' => $method,
            'url' => $url,
            'status' => $status,
            'ref' => $ref,
            'ua' => $ua,
            'is_static' => $is_static
        ];
    }
}

// Фільтрація реальних людей
$real_humans = [];
$total_human_pageviews = 0;
$popular_pages = [];

foreach ($sessions as $ip => $data) {
    if (!empty($data['is_scanner'])) {
        continue;
    }

    $reqs = $data['requests'] ?? [];
    if (empty($reqs)) continue;

    $content_reqs = [];
    $has_assets = false;

    foreach ($reqs as $r) {
        if ($r['is_static']) {
            $has_assets = true;
            continue;
        }

        $u = $r['url'];
        if (strpos($u, '/?') === 0 && strpos($u, 'add-to-cart') !== false) {
            continue;
        }
        if ($u === '/?wc-ajax=get_refreshed_fragments') {
            continue;
        }

        $is_content_page = ($u === '/' || 
            strpos($u, '/product/') === 0 || 
            strpos($u, '/product-category/') === 0 || 
            strpos($u, '/blog') === 0 || 
            strpos($u, '/cart') === 0 || 
            strpos($u, '/checkout') === 0 || 
            strpos($u, '/dostavka') === 0 || 
            strpos($u, '/obmin') === 0 || 
            strpos($u, '/kontakty') === 0 || 
            strpos($u, '/pro-nas') === 0 || 
            strpos($u, '/dogovir') === 0 || 
            strpos($u, '/polityka') === 0);

        if ($is_content_page && in_array($r['status'], [200, 301, 302], true)) {
            $content_reqs[] = $r;
        }
    }

    if (empty($content_reqs)) {
        continue;
    }

    $first = reset($content_reqs);
    $last = end($content_reqs);

    $ref = $first['ref'];
    $is_search_social = (stripos($ref, 'google.') !== false || 
                         stripos($ref, 'facebook') !== false || 
                         stripos($ref, 'instagram') !== false || 
                         stripos($ref, 't.me') !== false || 
                         stripos($ref, 'telegram') !== false || 
                         stripos($ref, 'ukr.net') !== false);

    // Якщо без завантаження ресурсів, без реферера і лише 1 сторінка — це одиночний робот-парсер
    if (!$has_assets && !$is_search_social && count($content_reqs) === 1) {
        $bot_hits['Анонімні парсери HTML 🤖'] = ($bot_hits['Анонімні парсери HTML 🤖'] ?? 0) + 1;
        continue;
    }

    // Пристрій
    $ua_str = $first['ua'];
    $device = 'Комп’ютер 💻';
    if (strpos($ua_str, 'iPhone') !== false) {
        $device = 'Apple iPhone 📱';
    } elseif (strpos($ua_str, 'Android') !== false) {
        $device = 'Android Смартфон 📱';
    } elseif (strpos($ua_str, 'iPad') !== false) {
        $device = 'Apple iPad 📱';
    } elseif (strpos($ua_str, 'Macintosh') !== false) {
        $device = 'Apple Mac 💻';
    } elseif (strpos($ua_str, 'Windows') !== false) {
        $device = 'Windows ПК 💻';
    }

    // Джерело переходу
    $source = 'Прямий захід';
    if (stripos($ref, 'google.') !== false) {
        $source = 'Google Пошук 🔍';
    } elseif (stripos($ref, 'facebook') !== false) {
        $source = 'Facebook 📱';
    } elseif (stripos($ref, 'instagram') !== false) {
        $source = 'Instagram 📱';
    } elseif (stripos($ref, 't.me') !== false || stripos($ref, 'telegram') !== false) {
        $source = 'Telegram ✈️';
    } elseif ($ref !== '-' && !empty($ref) && stripos($ref, 'zoobox.com.ua') === false) {
        $parsed_host = parse_url($ref, PHP_URL_HOST);
        $source = $parsed_host ?: substr($ref, 0, 30);
    }

    // Сторінки
    $user_pages = [];
    foreach ($content_reqs as $cr) {
        $decoded_url = urldecode($cr['url']);
        $user_pages[] = $decoded_url;
        $popular_pages[$decoded_url] = ($popular_pages[$decoded_url] ?? 0) + 1;
        $total_human_pageviews++;
    }

    $time_formatted = date('H:i', $first['ts'] ?: time());

    $real_humans[$ip] = [
        'ip' => $ip,
        'time' => $time_formatted,
        'device' => $device,
        'source' => $source,
        'pages' => array_values(array_unique($user_pages)),
        'total_views' => count($content_reqs)
    ];
}

arsort($popular_pages);
arsort($bot_hits);
arsort($googlebot_pages);

// Замовлення WooCommerce за 24 години
$orders_count = 0;
$orders_total = 0;
if (function_exists('wc_get_orders')) {
    $recent_orders = wc_get_orders([
        'date_after' => date('Y-m-d H:i:s', $start_ts),
        'limit' => 100,
        'status' => ['processing', 'completed', 'pending', 'on-hold']
    ]);
    if (!empty($recent_orders)) {
        $orders_count = count($recent_orders);
        foreach ($recent_orders as $o) {
            $orders_total += (float)$o->get_total();
        }
    }
}

// Формування звіту для Telegram
$today_date = date('d.m.Y');
$real_count = count($real_humans);

$msg = "📊 <b>ЗВІТ ZOOBOX ЗА ДОБУ ({$today_date})</b>\n\n";

if ($real_count > 0) {
    $msg .= "👤 <b>РЕАЛЬНІ ПОКУПЦІ (ЖИВІ ЛЮДИ):</b>\n";
    $msg .= "• Унікальних відвідувачів: <b>{$real_count}</b>\n";
    $msg .= "• Переглянуто сторінок: <b>{$total_human_pageviews}</b>\n\n";
    
    $msg .= "📋 <b>Деталі візитів:</b>\n";
    foreach ($real_humans as $ip => $h) {
        $short_pages = [];
        foreach (array_slice($h['pages'], 0, 3) as $p) {
            if ($p === '/') {
                $short_pages[] = 'Головна';
            } elseif (strpos($p, '/product/') === 0) {
                $slug = trim(str_replace(['/product/', '/'], ['', ''], $p));
                $short_pages[] = 'Товар: ' . mb_substr($slug, 0, 22) . '...';
            } elseif (strpos($p, '/product-category/') === 0) {
                $slug = trim(str_replace(['/product-category/', '/'], ['', ''], $p));
                $short_pages[] = 'Категорія: ' . mb_substr($slug, 0, 20);
            } else {
                $short_pages[] = mb_substr($p, 0, 25);
            }
        }
        $pages_str = implode(', ', $short_pages);
        $msg .= "• [{$h['time']}] {$h['device']} | {$h['source']}\n";
        $msg .= "  ↳ <i>{$pages_str}</i>\n";
    }
    $msg .= "\n";
} else {
    $msg .= "👤 <b>РЕАЛЬНІ ПОКУПЦІ (ЖИВІ ЛЮДИ):</b>\n";
    $msg .= "• Унікальних відвідувачів: <b>0</b>\n";
    $msg .= "• <i>Живих покупців за минулі 24 години на сайті не зафіксовано (тільки боти та сканери).</i>\n\n";
}

// Замовлення
$msg .= "🛒 <b>ЗАМОВЛЕННЯ ЗА 24 ГОД:</b>\n";
if ($orders_count > 0) {
    $formatted_total = number_format($orders_total, 2, '.', ' ');
    $msg .= "• Нових замовлень: <b>{$orders_count}</b> (на суму {$formatted_total} грн)\n\n";
} else {
    $msg .= "• Нових замовлень: <b>0</b>\n\n";
}

// Googlebot
$msg .= "🔍 <b>ІНДЕКСАЦІЯ GOOGLE ЗА 24 ГОД:</b>\n";
$google_total_pages = count($googlebot_pages);
if ($google_total_pages > 0) {
    $msg .= "• Googlebot обійшов сторінок: <b>{$google_total_pages}</b>\n";
    $top_g = array_slice($googlebot_pages, 0, 3);
    foreach ($top_g as $gu => $gcnt) {
        $short_gu = mb_strlen($gu) > 38 ? mb_substr($gu, 0, 35) . '...' : $gu;
        $msg .= "  - <code>" . htmlspecialchars($short_gu) . "</code>\n";
    }
} else {
    $msg .= "• Googlebot за останні 24 год сторінок не обходив\n";
}
$msg .= "\n";

// Роботи та сканери
$msg .= "🤖 <b>РОБОТИ ТА СКАНЕРИ:</b>\n";
$total_bots_hits = array_sum($bot_hits) + $scanner_hits + $tech_hits;
$msg .= "• Всього запитів ботів/сканерів: <b>{$total_bots_hits}</b>\n";
if (!empty($bot_hits)) {
    foreach (array_slice($bot_hits, 0, 4) as $bname => $bcnt) {
        $msg .= "  - {$bname}: {$bcnt}\n";
    }
}
if ($scanner_hits > 0) {
    $msg .= "  - Заблоковано спроб зламу/сканерів: {$scanner_hits}\n";
}
$msg .= "\n";

// Технічний стан
$msg .= "⚡ <b>ТЕХНІЧНИЙ СТАН:</b>\n";
$total_products = 0;
$in_stock = 0;
if (function_exists('wp_count_posts')) {
    $product_counts = wp_count_posts('product');
    $total_products = isset($product_counts->publish) ? (int)$product_counts->publish : 0;
    
    global $wpdb;
    if ($wpdb) {
        $in_stock = (int)$wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} p JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_stock_status' WHERE p.post_type = 'product' AND p.post_status = 'publish' AND pm.meta_value = 'instock'");
    }
}
$prod_str = number_format($total_products, 0, '', ' ');
$stock_str = number_format($in_stock, 0, '', ' ');
$msg .= "• База даних та сайт: <b>OK</b>\n";
$msg .= "• Товарів на сайті: <b>{$prod_str}</b> (в наявності: {$stock_str})\n";

// Відправка в Telegram
$tg_url = "https://api.telegram.org/bot{$bot_token}/sendMessage";
$tg_payload = [
    'chat_id' => $chat_id,
    'text' => $msg,
    'parse_mode' => 'HTML',
    'disable_web_page_preview' => true
];

$ch = curl_init($tg_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tg_payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo "Report completed. Telegram response: " . $response . "\n";
