<?php
/**
 * Analyze ALL Store Categories
 * Find all stores that might be in wrong categories
 */

// Suppress deprecation warnings
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
ini_set('display_errors', 1);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/functions.php';

$connect = connect();
if (!$connect) die("Database connection failed");

echo "<style>
body { font-family: Arial, sans-serif; margin: 20px; }
table { border-collapse: collapse; width: 100%; margin: 20px 0; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #4CAF50; color: white; position: sticky; top: 0; }
tr:nth-child(even) { background-color: #f2f2f2; }
.wrong { background-color: #ffcccc !important; }
.maybe { background-color: #ffffcc !important; }
.btn { padding: 10px 20px; margin: 10px 5px; cursor: pointer; background: #4CAF50; color: white; border: none; }
h1, h2 { color: #333; }
.summary { background: #e8f5e9; padding: 15px; margin: 20px 0; border-left: 4px solid #4CAF50; }
</style>";

echo "<h1>Complete Store Category Analysis</h1>";

// Get all categories
$categories = $connect->query("SELECT category_id, category_title FROM categories WHERE category_status = 1 ORDER BY category_title")->fetchAll(PDO::FETCH_ASSOC);
$category_map = [];
foreach ($categories as $cat) {
    $category_map[$cat['category_id']] = $cat['category_title'];
}

// Category keywords for auto-detection
$category_keywords = [
    2 => ['fashion', 'clothing', 'apparel', 'jeans', 'wear', 'shirt', 'dress', 'footwear', 'shoes', 'sneakers', 'boots', 'sandals', 'ethnic', 'saree', 'kurta', 'lehenga', 'blazer', 'jacket', 'coat', 'pants', 'trousers', 'shorts', 'skirt', 'lingerie', 'innerwear', 'bra', 'panty', 'underwear', 'socks', 'tie', 'belt', 'scarf', 'shawl', 'handbag', 'purse', 'wallet', 'backpack', 'luggage', 'sunglasses', 'watch', 'jewelry', 'jewellery', 'ring', 'necklace', 'bracelet', 'earring'],
    7 => ['electronics', 'mobile', 'phone', 'laptop', 'computer', 'tablet', 'headphone', 'earphone', 'speaker', 'camera', 'smartwatch', 'fitness band', 'charger', 'cable', 'adapter', 'powerbank', 'mouse', 'keyboard', 'monitor', 'printer', 'scanner', 'router', 'modem', 'wifi', 'bluetooth', 'usb', 'hard drive', 'ssd', 'ram', 'processor', 'graphics card', 'gaming', 'console', 'playstation', 'xbox', 'nintendo'],
    1 => ['beauty', 'health', 'skincare', 'makeup', 'cosmetic', 'perfume', 'fragrance', 'shampoo', 'conditioner', 'soap', 'lotion', 'cream', 'serum', 'face wash', 'moisturizer', 'sunscreen', 'lipstick', 'foundation', 'mascara', 'eyeliner', 'nail polish', 'hair oil', 'hair color', 'hair spray', 'deodorant', 'body wash', 'body lotion', 'face mask', 'scrub', 'toner', 'cleanser', 'vitamin', 'supplement', 'protein', 'wellness', 'fitness', 'yoga', 'gym', 'medicine', 'pharmacy', 'ayurvedic', 'herbal', 'organic'],
    4 => ['travel', 'hotel', 'flight', 'airline', 'booking', 'vacation', 'holiday', 'tour', 'trip', 'resort', 'accommodation', 'hostel', 'airbnb', 'bus', 'train', 'cab', 'taxi', 'rental', 'cruise', 'visa', 'passport'],
    11 => ['food', 'restaurant', 'cafe', 'pizza', 'burger', 'sandwich', 'snack', 'beverage', 'drink', 'coffee', 'tea', 'juice', 'grocery', 'supermarket', 'bakery', 'sweets', 'chocolate', 'candy', 'ice cream', 'dairy', 'milk', 'cheese', 'butter', 'oil', 'spice', 'masala', 'rice', 'flour', 'dal', 'pulses', 'nuts', 'dry fruits'],
    15 => ['telecom', 'mobile recharge', 'dth', 'broadband', 'internet', 'sim', 'prepaid', 'postpaid', 'data pack', 'talktime'],
    3 => ['home', 'furniture', 'decor', 'kitchen', 'appliance', 'bed', 'sofa', 'table', 'chair', 'mattress', 'pillow', 'curtain', 'carpet', 'rug', 'lamp', 'light', 'fan', 'ac', 'refrigerator', 'washing machine', 'microwave', 'oven', 'mixer', 'grinder', 'cooker', 'utensil', 'cookware', 'dinnerware', 'cutlery'],
    13 => ['personal care', 'grooming', 'shaving', 'razor', 'trimmer', 'beard', 'hair removal', 'wax', 'epilator', 'toothbrush', 'toothpaste', 'mouthwash', 'dental', 'oral care', 'hygiene', 'sanitary', 'pad', 'tampon', 'diaper', 'baby care', 'baby product'],
];

// Get all stores
$query = "SELECT s.store_id, s.store_title, s.store_category, c.category_title 
          FROM stores s 
          LEFT JOIN categories c ON s.store_category = c.category_id 
          WHERE s.store_status = 1 
          ORDER BY s.store_category, s.store_title";
$stores = $connect->query($query)->fetchAll(PDO::FETCH_ASSOC);

// Analyze each store
$mismatches = [];
$suggestions = [];

foreach ($stores as $store) {
    $store_name_lower = strtolower($store['store_title']);
    $current_category = $store['store_category'];
    $suggested_category = null;
    $confidence = 'low';
    
    // Check against keywords
    foreach ($category_keywords as $cat_id => $keywords) {
        foreach ($keywords as $keyword) {
            if (strpos($store_name_lower, $keyword) !== false) {
                if ($cat_id != $current_category) {
                    $suggested_category = $cat_id;
                    $confidence = 'high';
                    break 2;
                }
            }
        }
    }
    
    if ($suggested_category) {
        $mismatches[] = [
            'store_id' => $store['store_id'],
            'store_title' => $store['store_title'],
            'current_category' => $current_category,
            'current_category_name' => $store['category_title'],
            'suggested_category' => $suggested_category,
            'suggested_category_name' => $category_map[$suggested_category],
            'confidence' => $confidence
        ];
    }
}

// Display summary
echo "<div class='summary'>";
echo "<h2>Summary</h2>";
echo "<p><strong>Total Active Stores:</strong> " . count($stores) . "</p>";
echo "<p><strong>Potential Mismatches Found:</strong> " . count($mismatches) . "</p>";

// Count by current category
$category_counts = [];
foreach ($stores as $store) {
    $cat_id = $store['store_category'];
    if (!isset($category_counts[$cat_id])) {
        $category_counts[$cat_id] = 0;
    }
    $category_counts[$cat_id]++;
}

echo "<h3>Current Distribution:</h3><ul>";
foreach ($category_counts as $cat_id => $count) {
    $cat_name = isset($category_map[$cat_id]) ? $category_map[$cat_id] : 'Unknown';
    $warning = ($cat_id == 1 && $count > 100) ? ' <strong style="color:red;">(TOO MANY!)</strong>' : '';
    echo "<li>$cat_name: $count stores$warning</li>";
}
echo "</ul></div>";

// Display mismatches
if (count($mismatches) > 0) {
    echo "<h2>Stores That May Need Category Changes (" . count($mismatches) . ")</h2>";
    echo "<form method='POST' action='bulk_fix_categories.php'>";
    echo "<table>";
    echo "<tr>
        <th><input type='checkbox' id='selectAll' onclick='toggleAll(this)'></th>
        <th>Store ID</th>
        <th>Store Name</th>
        <th>Current Category</th>
        <th>Suggested Category</th>
        <th>Confidence</th>
    </tr>";
    
    foreach ($mismatches as $mismatch) {
        $row_class = ($mismatch['confidence'] == 'high') ? 'wrong' : 'maybe';
        echo "<tr class='$row_class'>";
        echo "<td><input type='checkbox' name='fix[]' value='{$mismatch['store_id']}:{$mismatch['suggested_category']}' checked></td>";
        echo "<td>{$mismatch['store_id']}</td>";
        echo "<td>{$mismatch['store_title']}</td>";
        echo "<td>{$mismatch['current_category_name']}</td>";
        echo "<td>{$mismatch['suggested_category_name']}</td>";
        echo "<td>{$mismatch['confidence']}</td>";
        echo "</tr>";
    }
    
    echo "</table>";
    echo "<button type='submit' class='btn'>Fix Selected Stores</button>";
    echo "</form>";
    
    echo "<script>
    function toggleAll(source) {
        var checkboxes = document.querySelectorAll('input[name=\"fix[]\"]');
        for(var i=0; i<checkboxes.length; i++) {
            checkboxes[i].checked = source.checked;
        }
    }
    </script>";
} else {
    echo "<div class='summary'><h2>✓ All stores appear to be correctly categorized!</h2></div>";
}

?>
