<?php
require_once __DIR__ . '/classes/Database.php';

$database = new Database();
$conn = $database->getConnection();
if (!$conn) {
    fwrite(STDERR, "Database connection failed. Check config/database.php and make sure MySQL is running.\n");
    exit(1);
}

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function tableExists(PDO $conn, string $table): bool {
    $stmt = $conn->prepare('SHOW TABLES LIKE :table_name');
    $stmt->execute([':table_name' => $table]);
    return (bool)$stmt->fetchColumn();
}

function columnExists(PDO $conn, string $table, string $column): bool {
    if (!tableExists($conn, $table)) {
        return false;
    }
    $stmt = $conn->prepare("SHOW COLUMNS FROM `$table` LIKE :column_name");
    $stmt->execute([':column_name' => $column]);
    return (bool)$stmt->fetchColumn();
}

$before = [];
foreach (['mra_eis_item_product_map', 'mra_eis_product_code_map'] as $table) {
    if (tableExists($conn, $table)) {
        $before[$table] = (int)$conn->query("SELECT COUNT(*) FROM `$table`")->fetchColumn();
    }
}
if (columnExists($conn, 'items', 'eis_site_product_id')) {
    $before['items.eis_site_product_id'] = (int)$conn->query('SELECT COUNT(*) FROM items WHERE eis_site_product_id IS NOT NULL')->fetchColumn();
}

$conn->beginTransaction();
try {
    if (tableExists($conn, 'mra_eis_item_product_map')) {
        $conn->exec('DELETE FROM mra_eis_item_product_map');
    }
    if (tableExists($conn, 'mra_eis_product_code_map')) {
        $conn->exec('DELETE FROM mra_eis_product_code_map');
    }
    if (columnExists($conn, 'items', 'eis_site_product_id')) {
        $conn->exec('UPDATE items SET eis_site_product_id = NULL WHERE eis_site_product_id IS NOT NULL');
    }
    $conn->commit();
} catch (Throwable $e) {
    $conn->rollBack();
    fwrite(STDERR, "Reset failed: " . $e->getMessage() . "\n");
    exit(1);
}

$after = [];
foreach (['mra_eis_item_product_map', 'mra_eis_product_code_map'] as $table) {
    if (tableExists($conn, $table)) {
        $after[$table] = (int)$conn->query("SELECT COUNT(*) FROM `$table`")->fetchColumn();
    }
}
if (columnExists($conn, 'items', 'eis_site_product_id')) {
    $after['items.eis_site_product_id'] = (int)$conn->query('SELECT COUNT(*) FROM items WHERE eis_site_product_id IS NOT NULL')->fetchColumn();
}

echo "EIS product mapping reset complete.\n";
echo "Before:\n";
foreach ($before as $target => $count) {
    echo " - {$target}: {$count}\n";
}
echo "After:\n";
foreach ($after as $target => $count) {
    echo " - {$target}: {$count}\n";
}
echo "Downloaded EIS site products and historical sold item audit mappings were not deleted.\n";