<?php
/**
 * Manual Store Category Fixer V2
 * With Parent Category and Subcategory Support
 */

// 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; background: #f5f5f5; }
.container { max-width: 1600px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
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; z-index: 10; }
tr:nth-child(even) { background-color: #f9f9f9; }
tr:hover { background-color: #e8f5e9; }
.category-select { padding: 5px; width: 180px; font-size: 11px; }
.btn { padding: 8px 16px; margin: 5px; cursor: pointer; background: #4CAF50; color: white; border: none; border-radius: 4px; }
.btn:hover { background: #45a049; }
.btn-save { background: #2196F3; font-size: 16px; padding: 12px 24px; }
.btn-save:hover { background: #0b7dda; }
.filter-section { background: #e8f5e9; padding: 15px; margin: 20px 0; border-radius: 4px; }
.summary { background: #fff3cd; padding: 15px; margin: 20px 0; border-left: 4px solid #ffc107; }
.success { background: #d4edda; padding: 15px; margin: 20px 0; border-left: 4px solid #28a745; color: #155724; }
h1, h2 { color: #333; }
.pagination { margin: 20px 0; text-align: center; }
.pagination a { padding: 8px 12px; margin: 0 2px; background: #4CAF50; color: white; text-decoration: none; border-radius: 4px; }
.pagination a:hover { background: #45a049; }
.pagination .active { background: #2196F3; }
.store-image { width: 35px; height: 35px; object-fit: contain; }
.changed { background-color: #fff3cd !important; }
.info-box { background: #e3f2fd; padding: 15px; margin: 20px 0; border-left: 4px solid #2196F3; }
</style>";

echo "<div class='container'>";
echo "<h1>🏪 Store Category Manager (With Subcategories)</h1>";

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['updates'])) {
    $updates = $_POST['updates'];
    $success_count = 0;
    $error_count = 0;
    
    foreach ($updates as $store_id => $data) {
        $store_id = intval($store_id);
        list($parent_cat, $sub_cat) = explode('|', $data);
        $parent_cat = intval($parent_cat);
        $sub_cat = intval($sub_cat);
        
        // Determine which category to save
        $category_to_save = ($sub_cat > 0) ? $sub_cat : $parent_cat;
        
        try {
            // Update stores table
            $stmt = $connect->prepare("UPDATE stores SET store_category = :category WHERE store_id = :store_id");
            $stmt->execute([':category' => $category_to_save, ':store_id' => $store_id]);
            
            // Update store_categories junction table
            $delete_stmt = $connect->prepare("DELETE FROM store_categories WHERE store_id = :store_id");
            $delete_stmt->execute([':store_id' => $store_id]);
            
            // Insert parent category
            if ($parent_cat > 0) {
                $insert_stmt = $connect->prepare("INSERT INTO store_categories (store_id, category_id) VALUES (:store_id, :category)");
                $insert_stmt->execute([':store_id' => $store_id, ':category' => $parent_cat]);
            }
            
            // Insert subcategory if selected
            if ($sub_cat > 0 && $sub_cat != $parent_cat) {
                $insert_stmt = $connect->prepare("INSERT INTO store_categories (store_id, category_id) VALUES (:store_id, :category)");
                $insert_stmt->execute([':store_id' => $store_id, ':category' => $sub_cat]);
            }
            
            $success_count++;
        } catch (Exception $e) {
            $error_count++;
        }
    }
    
    echo "<div class='success'>";
    echo "<h2>✓ Changes Saved!</h2>";
    echo "<p><strong>Updated:</strong> $success_count stores</p>";
    if ($error_count > 0) {
        echo "<p><strong>Errors:</strong> $error_count</p>";
    }
    echo "</div>";
}

// Get all parent categories
$parent_categories = $connect->query("SELECT category_id, category_title FROM categories WHERE category_status = 1 AND category_parent IS NULL ORDER BY category_title")->fetchAll(PDO::FETCH_ASSOC);

// Get all subcategories
$subcategories_query = $connect->query("SELECT subcategory_id, subcategory_title, subcategory_parent FROM subcategories WHERE subcategory_status = 1 ORDER BY subcategory_title")->fetchAll(PDO::FETCH_ASSOC);
$subcategories_by_parent = [];
foreach ($subcategories_query as $subcat) {
    $subcategories_by_parent[$subcat['subcategory_parent']][] = $subcat;
}

// Pagination
$items_per_page = 30;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $items_per_page;

// Filter by category
$filter_category = isset($_GET['filter_cat']) ? intval($_GET['filter_cat']) : 0;
$filter_sql = $filter_category > 0 ? "AND s.store_category = $filter_category" : "";

// Get total count
$count_query = "SELECT COUNT(*) FROM stores s WHERE s.store_status = 1 $filter_sql";
$total_stores = $connect->query($count_query)->fetchColumn();
$total_pages = ceil($total_stores / $items_per_page);

// Get stores
$query = "SELECT s.store_id, s.store_title, s.store_category, s.store_image, c.category_title,
          GROUP_CONCAT(DISTINCT sc.category_id) as junction_categories
          FROM stores s 
          LEFT JOIN categories c ON s.store_category = c.category_id 
          LEFT JOIN store_categories sc ON s.store_id = sc.store_id
          WHERE s.store_status = 1 $filter_sql
          GROUP BY s.store_id
          ORDER BY s.store_title
          LIMIT $items_per_page OFFSET $offset";
$stores = $connect->query($query)->fetchAll(PDO::FETCH_ASSOC);

// Display info box
echo "<div class='info-box'>";
echo "<h3>📋 How It Works</h3>";
echo "<ul>";
echo "<li><strong>Parent Category:</strong> Main category (e.g., Fashion, Beauty & Health)</li>";
echo "<li><strong>Subcategory:</strong> Optional sub-category under parent (e.g., Clothing under Fashion)</li>";
echo "<li><strong>Save Logic:</strong> If subcategory is selected, it will be saved as the primary category</li>";
echo "<li><strong>Junction Table:</strong> Both parent and subcategory are saved for filtering</li>";
echo "</ul>";
echo "</div>";

// Display filter
echo "<div class='filter-section'>";
echo "<h3>🔍 Filter Stores</h3>";
echo "<form method='GET'>";
echo "<label><strong>Show stores in category:</strong> </label>";
echo "<select name='filter_cat' onchange='this.form.submit()' class='category-select'>";
echo "<option value='0'>All Categories ($total_stores stores)</option>";

foreach ($parent_categories as $cat) {
    $count_query = $connect->prepare("SELECT COUNT(*) FROM stores WHERE store_status = 1 AND store_category = :cat_id");
    $count_query->execute([':cat_id' => $cat['category_id']]);
    $count = $count_query->fetchColumn();
    
    $selected = ($filter_category == $cat['category_id']) ? 'selected' : '';
    $warning = ($cat['category_id'] == 1 && $count > 100) ? ' ⚠️ TOO MANY!' : '';
    echo "<option value='{$cat['category_id']}' $selected>{$cat['category_title']} ($count stores)$warning</option>";
}
echo "</select>";
echo "</form>";
echo "<p><strong>Showing:</strong> " . count($stores) . " stores (Page $page of $total_pages)</p>";
echo "</div>";

// Display stores table
echo "<form method='POST' id='categoryForm'>";
echo "<table>";
echo "<tr>
    <th style='width:50px;'>ID</th>
    <th style='width:50px;'>Image</th>
    <th style='width:200px;'>Store Name</th>
    <th style='width:150px;'>Current Category</th>
    <th style='width:180px;'>Parent Category</th>
    <th style='width:180px;'>Subcategory (Optional)</th>
</tr>";

foreach ($stores as $store) {
    $current_parent = $store['store_category'];
    $junction_cats = $store['junction_categories'] ? explode(',', $store['junction_categories']) : [];
    
    echo "<tr data-store-id='{$store['store_id']}' data-original-cat='{$store['store_category']}'>";
    echo "<td>{$store['store_id']}</td>";
    
    // Store image
    $image_path = "images/{$store['store_image']}";
    if (file_exists($image_path) && $store['store_image'] != 'default-store.png') {
        echo "<td><img src='$image_path' class='store-image' alt='{$store['store_title']}'></td>";
    } else {
        echo "<td>-</td>";
    }
    
    echo "<td><strong>{$store['store_title']}</strong></td>";
    echo "<td>{$store['category_title']}</td>";
    
    // Parent Category Dropdown
    echo "<td>";
    echo "<select name='parent_cat_{$store['store_id']}' id='parent_{$store['store_id']}' class='category-select' onchange='updateSubcategories({$store['store_id']}, this.value); highlightChange(this)'>";
    echo "<option value='0'>-- Select Parent --</option>";
    foreach ($parent_categories as $cat) {
        $selected = ($current_parent == $cat['category_id']) ? 'selected' : '';
        echo "<option value='{$cat['category_id']}' $selected>{$cat['category_title']}</option>";
    }
    echo "</select>";
    echo "</td>";
    
    // Subcategory Dropdown
    echo "<td>";
    echo "<select name='updates[{$store['store_id']}]' id='sub_{$store['store_id']}' class='category-select' onchange='highlightChange(this)'>";
    echo "<option value='{$current_parent}|0'>None</option>";
    // Will be populated by JavaScript
    echo "</select>";
    echo "</td>";
    
    echo "</tr>";
}

echo "</table>";

// Pagination
if ($total_pages > 1) {
    echo "<div class='pagination'>";
    
    if ($page > 1) {
        $prev = $page - 1;
        echo "<a href='?page=$prev&filter_cat=$filter_category'>« Previous</a>";
    }
    
    for ($i = max(1, $page - 5); $i <= min($total_pages, $page + 5); $i++) {
        $active = ($i == $page) ? 'active' : '';
        echo "<a href='?page=$i&filter_cat=$filter_category' class='$active'>$i</a>";
    }
    
    if ($page < $total_pages) {
        $next = $page + 1;
        echo "<a href='?page=$next&filter_cat=$filter_category'>Next »</a>";
    }
    
    echo "</div>";
}

echo "<button type='submit' class='btn btn-save' onclick='return confirm(\"Save changes for " . count($stores) . " stores on this page?\")'>💾 Save All Changes on This Page</button>";
echo "<button type='button' class='btn' onclick='window.location.reload()'>🔄 Reset</button>";
echo "</form>";

echo "</div>";

// JavaScript for subcategory management
echo "<script>
// Subcategory data
const subcategories = " . json_encode($subcategories_by_parent) . ";

function updateSubcategories(storeId, parentId) {
    const subSelect = document.getElementById('sub_' + storeId);
    subSelect.innerHTML = '<option value=\"' + parentId + '|0\">None (Use Parent Only)</option>';
    
    if (subcategories[parentId]) {
        subcategories[parentId].forEach(function(subcat) {
            const option = document.createElement('option');
            option.value = parentId + '|' + subcat.subcategory_id;
            option.textContent = subcat.subcategory_title;
            subSelect.appendChild(option);
        });
    }
}

function highlightChange(select) {
    const row = select.closest('tr');
    const originalCat = row.getAttribute('data-original-cat');
    const parentSelect = row.querySelector('[name^=\"parent_cat_\"]');
    const newCat = parentSelect.value;
    
    if (originalCat != newCat) {
        row.classList.add('changed');
    } else {
        row.classList.remove('changed');
    }
}

// Initialize subcategories on page load
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('[id^=\"parent_\"]').forEach(function(select) {
        const storeId = select.id.replace('parent_', '');
        const parentId = select.value;
        if (parentId > 0) {
            updateSubcategories(storeId, parentId);
        }
    });
});
</script>";

?>
