<?php
/**
 * Manual Store Category Fixer
 * Review and manually assign correct categories to stores
 */

// 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: 1400px; 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: 13px; }
th, td { border: 1px solid #ddd; padding: 10px; 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: 200px; font-size: 12px; }
.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; }
.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: 40px; height: 40px; object-fit: contain; }
.changed { background-color: #fff3cd !important; }
</style>";

echo "<div class='container'>";
echo "<h1>Manual Store Category Manager</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 => $category_id) {
        $store_id = intval($store_id);
        $category_id = intval($category_id);
        
        try {
            // Update stores table
            $stmt = $connect->prepare("UPDATE stores SET store_category = :category WHERE store_id = :store_id");
            $stmt->execute([':category' => $category_id, ':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_stmt = $connect->prepare("INSERT INTO store_categories (store_id, category_id) VALUES (:store_id, :category)");
            $insert_stmt->execute([':store_id' => $store_id, ':category' => $category_id]);
            
            $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 categories
$categories = $connect->query("SELECT category_id, category_title FROM categories WHERE category_status = 1 ORDER BY category_title")->fetchAll(PDO::FETCH_ASSOC);

// Pagination
$items_per_page = 50;
$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 
          FROM stores s 
          LEFT JOIN categories c ON s.store_category = c.category_id 
          WHERE s.store_status = 1 $filter_sql
          ORDER BY s.store_title
          LIMIT $items_per_page OFFSET $offset";
$stores = $connect->query($query)->fetchAll(PDO::FETCH_ASSOC);

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

foreach ($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' : '';
    echo "<option value='{$cat['category_id']}' $selected>{$cat['category_title']} ($count stores)</option>";
}
echo "</select>";
echo "</form>";
echo "</div>";

// Display summary
echo "<div class='summary'>";
echo "<h3>Instructions</h3>";
echo "<ol>";
echo "<li>Review each store and select the correct category from the dropdown</li>";
echo "<li>Changed rows will be highlighted in yellow</li>";
echo "<li>Click 'Save Changes' at the bottom when done</li>";
echo "<li>Process stores in batches using the pagination</li>";
echo "</ol>";
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>ID</th>
    <th>Image</th>
    <th>Store Name</th>
    <th>Current Category</th>
    <th>Change To</th>
</tr>";

foreach ($stores as $store) {
    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>";
    echo "<td>";
    echo "<select name='updates[{$store['store_id']}]' class='category-select' onchange='highlightChange(this)'>";
    
    foreach ($categories as $cat) {
        $selected = ($store['store_category'] == $cat['category_id']) ? 'selected' : '';
        echo "<option value='{$cat['category_id']}' $selected>{$cat['category_title']}</option>";
    }
    
    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 this page?\")'>💾 Save Changes</button>";
echo "<button type='button' class='btn' onclick='window.location.reload()'>🔄 Reset</button>";
echo "</form>";

echo "</div>";

// JavaScript for highlighting changes
echo "<script>
function highlightChange(select) {
    var row = select.closest('tr');
    var originalCat = row.getAttribute('data-original-cat');
    var newCat = select.value;
    
    if (originalCat != newCat) {
        row.classList.add('changed');
    } else {
        row.classList.remove('changed');
    }
}
</script>";

?>
