<?php
/**
 * Simple Store Category Fix Script
 * Run this file once to fix all misassigned store categories
 */

// 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("ERROR: Could not connect to database. Check config.php\n");
}

echo "=== Store Category Fix Script ===\n\n";

// Define stores that need fixing
$fixes = [
    // Fashion stores (category 2)
    ['id' => 6, 'name' => 'Blackberrys', 'category' => 2, 'category_name' => 'Fashion'],
    ['id' => 21, 'name' => 'Go Colors', 'category' => 2, 'category_name' => 'Fashion'],
    ['id' => 40, 'name' => 'Montecarlo', 'category' => 2, 'category_name' => 'Fashion'],
    ['id' => 106, 'name' => 'House of Masaba', 'category' => 2, 'category_name' => 'Fashion'],
    
    // Electronics stores (category 7)
    ['id' => 99, 'name' => 'Boat', 'category' => 7, 'category_name' => 'Electronics'],
    
    // Beauty stores (category 1)
    ['id' => 100, 'name' => 'Innisfree', 'category' => 1, 'category_name' => 'Beauty & Health'],
];

$success_count = 0;
$error_count = 0;

foreach ($fixes as $fix) {
    try {
        // Update stores table
        $stmt = $connect->prepare("UPDATE stores SET store_category = :category WHERE store_id = :store_id");
        $stmt->execute([
            ':category' => $fix['category'],
            ':store_id' => $fix['id']
        ]);
        
        // Delete old category associations
        $delete_stmt = $connect->prepare("DELETE FROM store_categories WHERE store_id = :store_id");
        $delete_stmt->execute([':store_id' => $fix['id']]);
        
        // Insert new category association
        $insert_stmt = $connect->prepare("INSERT INTO store_categories (store_id, category_id) VALUES (:store_id, :category)");
        $insert_stmt->execute([
            ':store_id' => $fix['id'],
            ':category' => $fix['category']
        ]);
        
        echo "✓ Fixed: {$fix['name']} (ID: {$fix['id']}) → {$fix['category_name']}\n";
        $success_count++;
        
    } catch (Exception $e) {
        echo "✗ Error fixing {$fix['name']}: " . $e->getMessage() . "\n";
        $error_count++;
    }
}

echo "\n=== Summary ===\n";
echo "Successfully fixed: $success_count stores\n";
echo "Errors: $error_count\n";

if ($error_count === 0) {
    echo "\n✓ All store categories have been fixed!\n";
    echo "Visit your website to verify the changes.\n";
} else {
    echo "\n⚠ Some errors occurred. Please check the messages above.\n";
}

?>
