-- SpheriGo panel, zone-map, code login, and module visibility enhancements v26
-- Additive/safe migration. Keep index names short for MySQL compatibility.

ALTER TABLE tenants ADD COLUMN IF NOT EXISTS dashboard_enabled TINYINT(1) NOT NULL DEFAULT 1;
ALTER TABLE tenants ADD COLUMN IF NOT EXISTS vehicles_enabled TINYINT(1) NOT NULL DEFAULT 1;
ALTER TABLE tenants ADD COLUMN IF NOT EXISTS fleet_types_enabled TINYINT(1) NOT NULL DEFAULT 1;
ALTER TABLE tenants ADD COLUMN IF NOT EXISTS finance_enabled TINYINT(1) NOT NULL DEFAULT 1;
ALTER TABLE tenants ADD COLUMN IF NOT EXISTS reports_enabled TINYINT(1) NOT NULL DEFAULT 1;

-- client_code is now generated by backend and globally unique.
-- Run the duplicate check below before applying unique index on old databases:
-- SELECT client_code, COUNT(*) c FROM clients WHERE is_delete=0 GROUP BY client_code HAVING c > 1;
CREATE UNIQUE INDEX IF NOT EXISTS uq_client_code ON clients (client_code);

-- Ensure globally unique staff/storekeeper code with short index key.
DROP INDEX IF EXISTS uq_users_user_code_global ON users;
CREATE UNIQUE INDEX IF NOT EXISTS uq_usr_code ON users (user_code);

CREATE INDEX IF NOT EXISTS idx_ten_mods ON tenants (dashboard_enabled, vehicles_enabled, finance_enabled, reports_enabled);
CREATE INDEX IF NOT EXISTS idx_def_zone_st ON default_zones (status, is_delete);
CREATE INDEX IF NOT EXISTS idx_del_zone_st ON delivery_zones (tenant_id, status, is_delete);
CREATE INDEX IF NOT EXISTS idx_wh_loc_code ON warehouse_locations (tenant_id, warehouse_id, full_code);
