<?php
require_once 'db/config.php';
$pdo = db();

try {
    // 1. Assign default outlet_id to NULLs
    $pdo->exec("UPDATE _stock_items SET outlet_id = 1 WHERE outlet_id IS NULL");
    $pdo->exec("UPDATE _stock_categories SET outlet_id = 1 WHERE outlet_id IS NULL");
    $pdo->exec("UPDATE _stock_units SET outlet_id = 1 WHERE outlet_id IS NULL");

    // 2. Fix _stock_items index
    // First, drop old unique index if it exists
    try {
        $pdo->exec("ALTER TABLE _stock_items DROP INDEX sku");
    } catch (Exception $e) {
        echo "Note: index 'sku' might not exist or already dropped: " . $e->getMessage() . "\n";
    }
    // Add new unique index (outlet_id, sku)
    $pdo->exec("ALTER TABLE _stock_items ADD UNIQUE KEY outlet_sku (outlet_id, sku)");

    // 3. Fix _stock_categories index
    $pdo->exec("ALTER TABLE _stock_categories ADD UNIQUE KEY outlet_cat_name (outlet_id, name_en)");

    // 4. Fix _stock_units index
    $pdo->exec("ALTER TABLE _stock_units ADD UNIQUE KEY outlet_unit_name (outlet_id, name_en)");

    echo "Database schema updated successfully.\n";
} catch (Exception $e) {
    echo "Error updating database schema: " . $e->getMessage() . "\n";
}
