-- =====================================================================
-- Pharmacy SaaS - Schema PATCH  v0.2 -> v0.3
-- Run AFTER v0.1 + v0.2 patch.  (MySQL 8 / MariaDB 10.6+)
-- Reason: owner decisions
--   1. VAT is added on top of the product price; the shop cannot switch it,
--      only the platform super admin can turn it on/off per pharmacy.
--   2. Wholesale price = purchase price + a markup % that the SHOP decides.
--   3. SMS / bKash / Nagad integrations come later (nothing to change now).
--   4. One owner can run MORE THAN ONE pharmacy.
-- =====================================================================

SET NAMES utf8mb4;

-- ---------------------------------------------------------------------
-- 1. VAT  (admin-controlled)
-- ---------------------------------------------------------------------
-- vat_enabled is written ONLY by super-admin screens (policy + test in code).
-- When 0: every sale/purchase VAT is 0, whatever products.vat_percent says.
-- When 1: VAT = line net amount * products.vat_percent / 100, added on top.
ALTER TABLE pharmacies
  ADD COLUMN vat_enabled     TINYINT(1)   NOT NULL DEFAULT 0 AFTER subscription_ends_at,
  ADD COLUMN vat_enabled_by  BIGINT UNSIGNED NULL AFTER vat_enabled,   -- super admin who switched it
  ADD COLUMN vat_enabled_at  DATETIME NULL AFTER vat_enabled_by;

-- sale_items.vat / purchases.vat already snapshot the VAT amount at sale time,
-- so later changes to vat_enabled or vat_percent never rewrite old invoices.
ALTER TABLE sale_items
  ADD COLUMN vat_percent_applied DECIMAL(5,2) NOT NULL DEFAULT 0 AFTER vat;

-- ---------------------------------------------------------------------
-- 2. WHOLESALE  (shop-controlled markup over purchase price)
-- ---------------------------------------------------------------------
-- Priority when a batch is received:
--   products.wholesale_markup_pct  ->  else pharmacies.default_wholesale_markup_pct  ->  else NULL (no wholesale)
-- batches.wholesale_price = purchase_price * (1 + pct/100), rounded to 4 decimals,
-- stored as a snapshot per batch and still editable by the shop afterwards.
ALTER TABLE pharmacies
  ADD COLUMN default_wholesale_markup_pct DECIMAL(6,2) NULL AFTER vat_enabled_at;
ALTER TABLE products
  ADD COLUMN wholesale_markup_pct DECIMAL(6,2) NULL AFTER default_discount_pct;
ALTER TABLE batches
  ADD CONSTRAINT chk_b_wprice CHECK (wholesale_price IS NULL OR wholesale_price >= 0);

-- ---------------------------------------------------------------------
-- 3. MULTI-PHARMACY OWNERS
--    A user is now a GLOBAL account (one email/phone). Membership in a
--    pharmacy lives in pharmacy_user. The shop in use is chosen at login
--    (shop switcher) and kept in the session.
-- ---------------------------------------------------------------------
CREATE TABLE pharmacy_user (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  user_id      BIGINT UNSIGNED NOT NULL,
  pharmacy_id  BIGINT UNSIGNED NOT NULL,
  role_id      BIGINT UNSIGNED NOT NULL,               -- role inside THAT pharmacy
  branch_id    BIGINT UNSIGNED NULL,                   -- NULL = all branches of that pharmacy
  is_owner     TINYINT(1) NOT NULL DEFAULT 0,
  is_active    TINYINT(1) NOT NULL DEFAULT 1,
  created_at   TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  UNIQUE KEY uq_pu_user_ph (user_id, pharmacy_id),
  KEY idx_pu_ph (pharmacy_id),
  CONSTRAINT fk_pu_user   FOREIGN KEY (user_id)     REFERENCES users(id),
  CONSTRAINT fk_pu_ph     FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_pu_role   FOREIGN KEY (role_id)     REFERENCES roles(id),
  CONSTRAINT fk_pu_branch FOREIGN KEY (branch_id)   REFERENCES branches(id)
) ENGINE=InnoDB;

-- Carry over existing memberships from v0.1 users.pharmacy_id / role_id / branch_id
INSERT INTO pharmacy_user (user_id, pharmacy_id, role_id, branch_id, is_owner, is_active, created_at, updated_at)
SELECT u.id, u.pharmacy_id, u.role_id, u.branch_id, 0, u.is_active, NOW(), NOW()
FROM users u
WHERE u.pharmacy_id IS NOT NULL AND u.is_super_admin = 0;

-- users.pharmacy_id / branch_id / role_id are now legacy. Keep them nullable so the
-- app can drop them in a later migration once nothing reads them.
ALTER TABLE users
  MODIFY role_id BIGINT UNSIGNED NULL,
  ADD COLUMN last_pharmacy_id BIGINT UNSIGNED NULL AFTER last_login_at,   -- shop opened last time
  ADD CONSTRAINT fk_u_lastph FOREIGN KEY (last_pharmacy_id) REFERENCES pharmacies(id);

-- Who owns the pharmacy (billing contact). The owner also has an is_owner=1 pharmacy_user row.
ALTER TABLE pharmacies
  ADD COLUMN owner_user_id BIGINT UNSIGNED NULL AFTER owner_name,
  ADD CONSTRAINT fk_ph_owner FOREIGN KEY (owner_user_id) REFERENCES users(id);

-- Subscription stays PER PHARMACY (each shop has its own plan, trial and lock date).
-- Optional later: plans.max_pharmacies_per_owner to cap how many shops one owner may open.
ALTER TABLE plans
  ADD COLUMN max_pharmacies_per_owner INT UNSIGNED NULL AFTER max_branches;  -- NULL = unlimited

-- RULES (enforce in code):
--  * Tenant scope uses the pharmacy chosen in the session, never users.pharmacy_id.
--  * On every request verify a pharmacy_user row (is_active=1) exists for (auth user, session pharmacy).
--  * Roles/permissions are read from pharmacy_user.role_id for the current shop.
--  * Rows of shop A must never become visible in shop B even for the same owner: the owner
--    switches shop, the global scope changes. Reports across all shops = a separate, explicit
--    "owner dashboard" that loops over the owner's pharmacies.
--  * Only super admin may write pharmacies.vat_enabled.
