<?php
/**
 * Manual Store Categorization
 * Categorize ALL stores that are currently in wrong categories
 */

require './config.php';
require './functions.php';

$connect = connect($database);

// Get all categories
$categories = $connect->query("SELECT * FROM categories ORDER BY category_id")->fetchAll(PDO::FETCH_ASSOC);

// Get all subcategories grouped by parent
$subcategories = $connect->query("SELECT s.*, c.category_title as parent_name 
                                  FROM subcategories s 
                                  LEFT JOIN categories c ON s.subcategory_parent = c.category_id 
                                  ORDER BY s.subcategory_parent, s.subcategory_title")->fetchAll(PDO::FETCH_ASSOC);

// Group subcategories by parent
$subcatsByParent = [];
foreach ($subcategories as $sub) {
    if (!isset($subcatsByParent[$sub['subcategory_parent']])) {
        $subcatsByParent[$sub['subcategory_parent']] = [];
    }
    $subcatsByParent[$sub['subcategory_parent']][] = $sub;
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Categorize All Stores</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
        .container { max-width: 1600px; margin: 0 auto; background: white; padding: 40px; border-radius: 8px; }
        h1 { color: #ed174f; margin-bottom: 20px; }
        h2 { color: #333; margin: 30px 0 15px 0; border-bottom: 2px solid #ed174f; padding-bottom: 10px; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 10px; text-align: left; border: 1px solid #ddd; font-size: 13px; }
        th { background: #ed174f; color: white; position: sticky; top: 0; }
        select { padding: 8px; border: 1px solid #ddd; border-radius: 4px; width: 100%; }
        .btn { display: inline-block; padding: 15px 30px; background: #ed174f; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; font-weight: bold; margin: 20px 0; }
        .btn:hover { background: #c41340; }
        .success { background: #d4edda; color: #155724; padding: 20px; border-radius: 8px; margin: 20px 0; }
        .info { background: #d1ecf1; color: #0c5460; padding: 20px; border-radius: 8px; margin: 20px 0; }
        .filter-section { background: #f9f9f9; padding: 20px; border-radius: 8px; margin: 20px 0; }
        .filter-btn { padding: 10px 20px; margin: 5px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer; }
        .filter-btn.active { background: #ed174f; }
        .store-row { transition: background 0.3s; }
        .store-row:hover { background: #f5f5f5; }
        .subcat-checkboxes { display: none; margin-top: 10px; padding: 10px; background: #f9f9f9; border-radius: 4px; }
        .subcat-checkboxes.show { display: block; }
        .subcat-checkboxes label { display: block; margin: 5px 0; cursor: pointer; }
        .subcat-checkboxes input[type="checkbox"] { margin-right: 8px; }
        .subcat-toggle { color: #ed174f; cursor: pointer; font-size: 12px; text-decoration: underline; margin-top: 5px; display: inline-block; }
    </style>
    <script>
        // Store subcategories data
        const subcategoriesByParent = <?php echo json_encode($subcatsByParent); ?>;
        
        function filterStores(categoryId) {
            const rows = document.querySelectorAll('.store-row');
            const buttons = document.querySelectorAll('.filter-btn');
            
            buttons.forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');
            
            rows.forEach(row => {
                if (categoryId === 'all' || row.dataset.category == categoryId) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }
        
        function selectAll(categoryId) {
            const selects = document.querySelectorAll('.store-row[data-category="' + categoryId + '"] select.category-select');
            selects.forEach(select => {
                select.value = categoryId;
                updateSubcategories(select);
            });
        }
        
        function updateSubcategories(selectElement) {
            const storeId = selectElement.dataset.storeId;
            const categoryId = selectElement.value;
            const subcatContainer = document.getElementById('subcat-' + storeId);
            
            // Clear existing subcategories
            subcatContainer.innerHTML = '';
            
            // Add subcategories for selected parent category
            if (subcategoriesByParent[categoryId]) {
                subcategoriesByParent[categoryId].forEach(subcat => {
                    const label = document.createElement('label');
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.name = 'subcategories[' + storeId + '][]';
                    checkbox.value = subcat.subcategory_id;
                    
                    label.appendChild(checkbox);
                    label.appendChild(document.createTextNode(' ' + subcat.subcategory_title));
                    subcatContainer.appendChild(label);
                });
            }
            
            if (subcatContainer.innerHTML === '') {
                subcatContainer.innerHTML = '<em style="color: #999;">No subcategories available</em>';
            }
        }
        
        function toggleSubcategories(storeId) {
            const container = document.getElementById('subcat-' + storeId);
            container.classList.toggle('show');
        }
    </script>
</head>
<body>
<div class="container">
    <h1>📝 Categorize All Stores</h1>

<?php

if (!isset($_POST['save'])) {
    // Show all stores with category selection
    $allStores = $connect->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 
                                  ORDER BY s.store_title")->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<div class='info'>";
    echo "<h3>📋 Instructions:</h3>";
    echo "<ol style='margin: 15px 0 0 20px; line-height: 2;'>";
    echo "<li>Review each store below</li>";
    echo "<li>Select the correct <strong>Primary Category</strong> from the dropdown</li>";
    echo "<li>Click <strong>'+ Subcategories'</strong> to assign subcategories (optional)</li>";
    echo "<li>Check the subcategories that apply to each store</li>";
    echo "<li>Use filter buttons to view stores by current category</li>";
    echo "<li>Click 'Save All Changes' when done</li>";
    echo "</ol>";
    echo "<p style='margin-top: 15px;'><strong>Note:</strong> Subcategories should match the primary category (e.g., Fashion stores → Clothing, Footwear)</p>";
    echo "</div>";
    
    // Filter buttons
    echo "<div class='filter-section'>";
    echo "<h3>Filter by Current Category:</h3>";
    echo "<button class='filter-btn active' onclick='filterStores(\"all\")'>All Stores (" . count($allStores) . ")</button>";
    foreach ($categories as $cat) {
        $count = count(array_filter($allStores, function($s) use ($cat) { return $s['store_category'] == $cat['category_id']; }));
        echo "<button class='filter-btn' onclick='filterStores({$cat['category_id']})'>{$cat['category_title']} ($count)</button>";
    }
    echo "</div>";
    
    // Quick assign buttons
    echo "<div class='filter-section'>";
    echo "<h3>Quick Assign:</h3>";
    echo "<p>Select all visible stores and assign them to:</p>";
    foreach ($categories as $cat) {
        echo "<button class='filter-btn' onclick='selectAll({$cat['category_id']})''>All → {$cat['category_title']}</button>";
    }
    echo "</div>";
    
    echo "<form method='post'>";
    echo "<table>";
    echo "<tr>";
    echo "<th style='width: 40px;'>#</th>";
    echo "<th style='width: 250px;'>Store Name</th>";
    echo "<th style='width: 180px;'>Current Category</th>";
    echo "<th style='width: 200px;'>Primary Category</th>";
    echo "<th style='width: 300px;'>Subcategories</th>";
    echo "</tr>";
    
    $index = 1;
    foreach ($allStores as $store) {
        // Get current subcategory assignments
        $currentSubcats = $connect->prepare("SELECT category_id FROM store_categories WHERE store_id = ?");
        $currentSubcats->execute([$store['store_id']]);
        $currentSubcatIds = $currentSubcats->fetchAll(PDO::FETCH_COLUMN);
        
        echo "<tr class='store-row' data-category='{$store['store_category']}'>";
        echo "<td>$index</td>";
        echo "<td><strong>{$store['store_title']}</strong></td>";
        echo "<td>{$store['category_title']}</td>";
        echo "<td>";
        echo "<select name='category[{$store['store_id']}]' class='category-select' data-store-id='{$store['store_id']}' onchange='updateSubcategories(this)'>";
        foreach ($categories as $cat) {
            $selected = ($cat['category_id'] == $store['store_category']) ? 'selected' : '';
            echo "<option value='{$cat['category_id']}' $selected>{$cat['category_title']}</option>";
        }
        echo "</select>";
        echo "</td>";
        echo "<td>";
        echo "<a class='subcat-toggle' onclick='toggleSubcategories({$store['store_id']})'>+ Subcategories</a>";
        echo "<div id='subcat-{$store['store_id']}' class='subcat-checkboxes'>";
        
        // Show subcategories for current parent category
        if (isset($subcatsByParent[$store['store_category']])) {
            foreach ($subcatsByParent[$store['store_category']] as $subcat) {
                $checked = in_array($subcat['subcategory_id'], $currentSubcatIds) ? 'checked' : '';
                echo "<label>";
                echo "<input type='checkbox' name='subcategories[{$store['store_id']}][]' value='{$subcat['subcategory_id']}' $checked>";
                echo " {$subcat['subcategory_title']}";
                echo "</label>";
            }
        } else {
            echo "<em style='color: #999;'>No subcategories available</em>";
        }
        
        echo "</div>";
        echo "</td>";
        echo "</tr>";
        $index++;
    }
    
    echo "</table>";
    
    echo "<button type='submit' name='save' class='btn'>💾 Save All Changes</button>";
    echo "</form>";
    
} else {
    // Save changes
    echo "<h2>💾 Saving Changes...</h2>";
    
    try {
        $connect->beginTransaction();
        
        $updated = 0;
        $unchanged = 0;
        $subcatsUpdated = 0;
        
        echo "<table>";
        echo "<tr><th>Store ID</th><th>Primary Category</th><th>Subcategories</th><th>Status</th></tr>";
        
        foreach ($_POST['category'] as $storeId => $categoryId) {
            // Get current category
            $current = $connect->prepare("SELECT store_category FROM stores WHERE store_id = ?");
            $current->execute([$storeId]);
            $currentCat = $current->fetch()['store_category'];
            
            $status = [];
            
            // Update primary category if changed
            if ($currentCat != $categoryId) {
                $stmt = $connect->prepare("UPDATE stores SET store_category = ? WHERE store_id = ?");
                $stmt->execute([$categoryId, $storeId]);
                $status[] = "Primary updated";
                $updated++;
            } else {
                $unchanged++;
            }
            
            // Update subcategories
            // First, delete existing subcategory assignments
            $deleteStmt = $connect->prepare("DELETE FROM store_categories WHERE store_id = ?");
            $deleteStmt->execute([$storeId]);
            
            // Then, insert new subcategory assignments
            $subcatCount = 0;
            if (isset($_POST['subcategories'][$storeId]) && is_array($_POST['subcategories'][$storeId])) {
                foreach ($_POST['subcategories'][$storeId] as $subcatId) {
                    $insertStmt = $connect->prepare("INSERT INTO store_categories (store_id, category_id) VALUES (?, ?)");
                    $insertStmt->execute([$storeId, $subcatId]);
                    $subcatCount++;
                }
                $status[] = "$subcatCount subcategories";
                $subcatsUpdated++;
            }
            
            if (!empty($status)) {
                echo "<tr>";
                echo "<td>$storeId</td>";
                echo "<td>$categoryId</td>";
                echo "<td>$subcatCount</td>";
                echo "<td>✅ " . implode(', ', $status) . "</td>";
                echo "</tr>";
            }
        }
        
        echo "</table>";
        
        $connect->commit();
        
        echo "<div class='success'>";
        echo "<h3>✅ Changes Saved Successfully!</h3>";
        echo "<p><strong>Primary categories updated:</strong> $updated stores</p>";
        echo "<p><strong>Primary categories unchanged:</strong> $unchanged stores</p>";
        echo "<p><strong>Stores with subcategories assigned:</strong> $subcatsUpdated stores</p>";
        echo "</div>";
        
        echo "<div class='info'>";
        echo "<h3>📋 Next Steps:</h3>";
        echo "<ol style='margin: 15px 0 0 20px; line-height: 2;'>";
        echo "<li><strong>Clear browser cache:</strong> Ctrl+Shift+Delete</li>";
        echo "<li><strong>Clear server cache:</strong> <a href='clear_all_cache.php'>Run cache clear</a></li>";
        echo "<li><strong>Test category pages:</strong>";
        echo "<ul style='margin: 10px 0 0 20px;'>";
        echo "<li><a href='/category/beauty-health' target='_blank'>Beauty & Health</a></li>";
        echo "<li><a href='/category/fashion' target='_blank'>Fashion</a></li>";
        echo "</ul>";
        echo "</li>";
        echo "<li><strong>Test subcategory pages</strong> (if you assigned any)</li>";
        echo "<li><strong>Run verification:</strong> <a href='diagnose_categories.php'>Diagnose Categories</a></li>";
        echo "</ol>";
        echo "</div>";
        
    } catch (Exception $e) {
        $connect->rollBack();
        echo "<div class='error'>";
        echo "<h3>❌ Error</h3>";
        echo "<p>" . $e->getMessage() . "</p>";
        echo "</div>";
    }
}

?>

</div>
</body>
</html>
