<?php
/**
 * Store Category Fix Script
 * This script helps identify and fix store category assignments
 */

// Enable error reporting (suppress deprecation warnings from third-party libraries)
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
ini_set('display_errors', 1);

// Include required files
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/functions.php';

// Establish database connection
$connect = connect();

if (!$connect) {
    die("<h1>Database Connection Error</h1><p>Could not connect to the database. Please check your config.php settings.</p>");
}

echo "<h1>Store Category Fix Tool</h1>";
echo "<style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    table { border-collapse: collapse; width: 100%; margin: 20px 0; }
    th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
    th { background-color: #4CAF50; color: white; }
    tr:nth-child(even) { background-color: #f2f2f2; }
    .error { color: red; font-weight: bold; }
    .success { color: green; font-weight: bold; }
    .warning { color: orange; font-weight: bold; }
    .btn { padding: 10px 20px; margin: 10px 5px; cursor: pointer; }
    .btn-fix { background-color: #4CAF50; color: white; border: none; }
    .btn-check { background-color: #008CBA; color: white; border: none; }
</style>";

// Get action
$action = isset($_GET['action']) ? $_GET['action'] : 'check';

if ($action === 'fix' && isset($_GET['store_id']) && isset($_GET['category_id'])) {
    // Fix individual store
    $store_id = intval($_GET['store_id']);
    $category_id = intval($_GET['category_id']);
    
    try {
        // Update stores table
        $stmt = $connect->prepare("UPDATE stores SET store_category = :category_id WHERE store_id = :store_id");
        $stmt->execute([':category_id' => $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_id)");
        $insert_stmt->execute([':store_id' => $store_id, ':category_id' => $category_id]);
        
        echo "<p class='success'>✓ Store ID $store_id updated to category ID $category_id</p>";
    } catch (Exception $e) {
        echo "<p class='error'>✗ Error: " . $e->getMessage() . "</p>";
    }
}

if ($action === 'fix_all') {
    // Fashion brands that should be in category 2 (Fashion)
    $fashion_stores = [
        6 => 'Blackberrys',
        21 => 'Go Colors',
        40 => 'Montecarlo',
        106 => 'House of Masaba'
    ];
    
    // Electronics/Accessories stores that need fixing
    $electronics_stores = [
        99 => 'Boat'  // Currently in Fashion, should be Electronics (7)
    ];
    
    // Beauty stores that need fixing
    $beauty_stores = [
        100 => 'Innisfree'  // Currently in Fashion, should be Beauty & Health (1)
    ];
    
    echo "<h2>Fixing Store Categories...</h2>";
    
    // Fix Fashion stores
    foreach ($fashion_stores as $store_id => $store_name) {
        try {
            $stmt = $connect->prepare("UPDATE stores SET store_category = 2 WHERE store_id = :store_id");
            $stmt->execute([':store_id' => $store_id]);
            
            $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, 2)");
            $insert_stmt->execute([':store_id' => $store_id]);
            
            echo "<p class='success'>✓ Fixed: $store_name (ID: $store_id) → Fashion</p>";
        } catch (Exception $e) {
            echo "<p class='error'>✗ Error fixing $store_name: " . $e->getMessage() . "</p>";
        }
    }
    
    // Fix Electronics stores
    foreach ($electronics_stores as $store_id => $store_name) {
        try {
            $stmt = $connect->prepare("UPDATE stores SET store_category = 7 WHERE store_id = :store_id");
            $stmt->execute([':store_id' => $store_id]);
            
            $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, 7)");
            $insert_stmt->execute([':store_id' => $store_id]);
            
            echo "<p class='success'>✓ Fixed: $store_name (ID: $store_id) → Electronics</p>";
        } catch (Exception $e) {
            echo "<p class='error'>✗ Error fixing $store_name: " . $e->getMessage() . "</p>";
        }
    }
    
    // Fix Beauty stores
    foreach ($beauty_stores as $store_id => $store_name) {
        try {
            $stmt = $connect->prepare("UPDATE stores SET store_category = 1 WHERE store_id = :store_id");
            $stmt->execute([':store_id' => $store_id]);
            
            $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, 1)");
            $insert_stmt->execute([':store_id' => $store_id]);
            
            echo "<p class='success'>✓ Fixed: $store_name (ID: $store_id) → Beauty & Health</p>";
        } catch (Exception $e) {
            echo "<p class='error'>✗ Error fixing $store_name: " . $e->getMessage() . "</p>";
        }
    }
    
    echo "<p class='success'><strong>All fixes applied!</strong></p>";
    echo "<p><a href='fix_store_categories.php'>Check Results</a></p>";
    exit;
}

// Display current status
echo "<h2>Current Store Category Assignments</h2>";

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

$category_map = [];
foreach ($categories as $cat) {
    $category_map[$cat['category_id']] = $cat['category_title'];
}

// Get all stores with their categories
$query = "SELECT 
    s.store_id,
    s.store_title,
    s.store_category,
    s.store_status,
    c.category_title as legacy_category,
    GROUP_CONCAT(DISTINCT c2.category_title SEPARATOR ', ') as junction_categories,
    GROUP_CONCAT(DISTINCT sc.category_id SEPARATOR ', ') as junction_category_ids
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
LEFT JOIN categories c2 ON sc.category_id = c2.category_id
WHERE s.store_status = 1
GROUP BY s.store_id
ORDER BY s.store_title";

$stores = $connect->query($query)->fetchAll(PDO::FETCH_ASSOC);

// Count stores per 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>Category Distribution</h3>";
echo "<table>";
echo "<tr><th>Category</th><th>Store Count</th></tr>";
foreach ($category_map as $cat_id => $cat_name) {
    $count = isset($category_counts[$cat_id]) ? $category_counts[$cat_id] : 0;
    $class = ($cat_id == 1 && $count > 20) ? 'warning' : '';
    echo "<tr class='$class'><td>$cat_name (ID: $cat_id)</td><td>$count</td></tr>";
}
echo "</table>";

echo "<h3>All Stores</h3>";
echo "<table>";
echo "<tr>
    <th>Store ID</th>
    <th>Store Name</th>
    <th>Legacy Category</th>
    <th>Junction Table Categories</th>
    <th>Status</th>
    <th>Action</th>
</tr>";

foreach ($stores as $store) {
    $status = '';
    $action_btn = '';
    
    // Check if it's a fashion brand in wrong category
    $fashion_keywords = ['fashion', 'clothing', 'jeans', 'apparel', 'wear', 'colors'];
    $is_fashion = false;
    foreach ($fashion_keywords as $keyword) {
        if (stripos($store['store_title'], $keyword) !== false) {
            $is_fashion = true;
            break;
        }
    }
    
    // Known fashion brands
    $known_fashion = ['Blackberrys', 'Mufti', 'Pepe Jeans', 'Myntra', 'Bata', 'Marks and Spencer', 'Kindlife', 'Nuawomen', 'Go Colors', 'Montecarlo', 'House of Masaba', 'Vero Moda', 'Decathlon', 'Uniqlo', 'Peter England', 'Zivame', 'Bliss Club', 'Ajio', 'Tata Cliq', 'Tata Neu'];
    if (in_array($store['store_title'], $known_fashion)) {
        $is_fashion = true;
    }
    
    if ($is_fashion && $store['store_category'] != 2) {
        $status = "<span class='error'>⚠ Should be in Fashion</span>";
        $action_btn = "<a href='?action=fix&store_id={$store['store_id']}&category_id=2' class='btn btn-fix'>Fix → Fashion</a>";
    } else {
        $status = "<span class='success'>✓ OK</span>";
    }
    
    echo "<tr>";
    echo "<td>{$store['store_id']}</td>";
    echo "<td>{$store['store_title']}</td>";
    echo "<td>{$store['legacy_category']}</td>";
    echo "<td>{$store['junction_categories']}</td>";
    echo "<td>$status</td>";
    echo "<td>$action_btn</td>";
    echo "</tr>";
}

echo "</table>";

echo "<h3>Quick Actions</h3>";
echo "<a href='?action=fix_all' class='btn btn-fix' onclick='return confirm(\"Fix all misassigned fashion stores?\")'>Fix All Fashion Stores</a>";
echo "<a href='?action=check' class='btn btn-check'>Refresh</a>";

echo "<hr>";
echo "<h3>Manual Category Assignment</h3>";
echo "<form method='GET'>";
echo "<input type='hidden' name='action' value='fix'>";
echo "Store ID: <input type='number' name='store_id' required>";
echo " Category ID: <select name='category_id'>";
foreach ($category_map as $cat_id => $cat_name) {
    echo "<option value='$cat_id'>$cat_name</option>";
}
echo "</select>";
echo " <button type='submit' class='btn btn-fix'>Update</button>";
echo "</form>";

?>
