-- =====================================================================
-- Pharmacy SaaS (multi-tenant) - Database schema v0.1
-- MySQL 8 / MariaDB 10.6+ | InnoDB | utf8mb4
--
-- GOLDEN RULES
-- 1. Every shop-owned table has pharmacy_id (the tenant). Laravel global
--    scope must filter by it automatically. Tests must prove that shop A
--    can never read shop B's rows.
-- 2. pharmacy_id NULL on master tables (generics, units, categories ...)
--    means "global/shared by the whole platform".
-- 3. STOCK is stored in the BASE unit (smallest sellable: piece/tablet)
--    as an integer. Box/strip are just conversion factors. No float errors.
-- 4. stock_movements is the ledger (the truth). batch_stocks is the fast
--    "current balance" table, updated in the same DB transaction.
-- 5. Every batch can sit in MORE THAN ONE rack (batch_stocks row per rack).
-- 6. Money = DECIMAL, never FLOAT. Prices are per BASE unit (4 decimals).
-- =====================================================================

SET NAMES utf8mb4;

-- ---------------------------------------------------------------------
-- A. PLATFORM / TENANCY (you = super admin)
-- ---------------------------------------------------------------------

CREATE TABLE plans (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name            VARCHAR(100) NOT NULL,              -- Free Trial, Basic, Standard, Premium
  price_monthly   DECIMAL(10,2) NOT NULL DEFAULT 0,
  price_yearly    DECIMAL(10,2) NOT NULL DEFAULT 0,
  max_users       INT UNSIGNED NULL,                  -- NULL = unlimited
  max_branches    INT UNSIGNED NULL,
  max_products    INT UNSIGNED NULL,
  features        JSON NULL,                          -- {"reports_advanced":true,"sms":false}
  is_active       TINYINT(1) NOT NULL DEFAULT 1,
  created_at      TIMESTAMP NULL, updated_at TIMESTAMP NULL
) ENGINE=InnoDB;

CREATE TABLE pharmacies (                              -- the TENANT
  id                    BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name                  VARCHAR(150) NOT NULL,
  slug                  VARCHAR(80)  NOT NULL UNIQUE,  -- for subdomain: shopname.yourdomain.com
  owner_name            VARCHAR(120) NOT NULL,
  phone                 VARCHAR(20)  NOT NULL,
  email                 VARCHAR(150) NULL,
  address               VARCHAR(255) NULL,
  division              VARCHAR(60)  NULL,
  district              VARCHAR(60)  NULL,
  upazila               VARCHAR(60)  NULL,
  trade_license_no      VARCHAR(60)  NULL,
  drug_license_no       VARCHAR(60)  NULL,
  status                ENUM('pending','trial','active','suspended','expired') NOT NULL DEFAULT 'pending',
  plan_id               BIGINT UNSIGNED NULL,
  trial_ends_at         DATETIME NULL,
  subscription_ends_at  DATETIME NULL,                 -- after this date: lock (read-only)
  settings              JSON NULL,                     -- currency, invoice footer, language (bn/en), VAT on/off
  approved_by           BIGINT UNSIGNED NULL,          -- super admin user id
  created_at            TIMESTAMP NULL, updated_at TIMESTAMP NULL, deleted_at TIMESTAMP NULL,
  KEY idx_status (status),
  KEY idx_location (division, district, upazila),
  CONSTRAINT fk_ph_plan FOREIGN KEY (plan_id) REFERENCES plans(id)
) ENGINE=InnoDB;

-- Link to your directory (for later: auto-listing + "medicine available nearby")
CREATE TABLE pharmacy_public_profiles (
  pharmacy_id           BIGINT UNSIGNED PRIMARY KEY,
  show_in_directory     TINYINT(1) NOT NULL DEFAULT 0,
  show_stock_search     TINYINT(1) NOT NULL DEFAULT 0, -- shop must opt in before stock is searchable
  opening_hours         JSON NULL,
  latitude              DECIMAL(10,7) NULL,
  longitude             DECIMAL(10,7) NULL,
  directory_listing_id  BIGINT UNSIGNED NULL,          -- id in your directory database
  CONSTRAINT fk_pp_ph FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id)
) ENGINE=InnoDB;

CREATE TABLE branches (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NOT NULL,
  name         VARCHAR(120) NOT NULL,
  address      VARCHAR(255) NULL,
  phone        VARCHAR(20) NULL,
  is_main      TINYINT(1) NOT NULL DEFAULT 0,
  is_active    TINYINT(1) NOT NULL DEFAULT 1,
  created_at   TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  KEY idx_branch_ph (pharmacy_id),
  CONSTRAINT fk_br_ph FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id)
) ENGINE=InnoDB;

CREATE TABLE roles (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NULL,                   -- NULL = system role (super_admin)
  name         VARCHAR(60) NOT NULL,                   -- owner, manager, salesman, accountant
  permissions  JSON NOT NULL,                          -- ["sale.create","purchase.view","stock.adjust",...]
  created_at   TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  KEY idx_role_ph (pharmacy_id),
  CONSTRAINT fk_role_ph FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id)
) ENGINE=InnoDB;

CREATE TABLE users (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id    BIGINT UNSIGNED NULL,                 -- NULL only for platform super admins
  branch_id      BIGINT UNSIGNED NULL,                 -- NULL = can access all branches
  role_id        BIGINT UNSIGNED NOT NULL,
  is_super_admin TINYINT(1) NOT NULL DEFAULT 0,
  name           VARCHAR(120) NOT NULL,
  phone          VARCHAR(20) NULL,
  email          VARCHAR(150) NULL,
  password       VARCHAR(255) NOT NULL,
  is_active      TINYINT(1) NOT NULL DEFAULT 1,
  last_login_at  DATETIME NULL,
  remember_token VARCHAR(100) NULL,
  created_at     TIMESTAMP NULL, updated_at TIMESTAMP NULL, deleted_at TIMESTAMP NULL,
  UNIQUE KEY uq_user_email (email),
  UNIQUE KEY uq_user_phone (phone),
  KEY idx_user_ph (pharmacy_id),
  CONSTRAINT fk_u_ph   FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_u_br   FOREIGN KEY (branch_id)   REFERENCES branches(id),
  CONSTRAINT fk_u_role FOREIGN KEY (role_id)     REFERENCES roles(id)
) ENGINE=InnoDB;

CREATE TABLE subscription_payments (                   -- what shops pay YOU (later)
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id   BIGINT UNSIGNED NOT NULL,
  plan_id       BIGINT UNSIGNED NOT NULL,
  amount        DECIMAL(10,2) NOT NULL,
  method        ENUM('cash','bkash','nagad','rocket','bank','card','free') NOT NULL,
  trx_id        VARCHAR(80) NULL,
  period_start  DATE NOT NULL,
  period_end    DATE NOT NULL,
  status        ENUM('pending','paid','failed','refunded') NOT NULL DEFAULT 'paid',
  note          VARCHAR(255) NULL,
  created_at    TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  KEY idx_sp_ph (pharmacy_id),
  CONSTRAINT fk_sp_ph   FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_sp_plan FOREIGN KEY (plan_id)     REFERENCES plans(id)
) ENGINE=InnoDB;

CREATE TABLE activity_logs (                           -- audit trail (who changed what)
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id   BIGINT UNSIGNED NULL,
  user_id       BIGINT UNSIGNED NULL,
  action        VARCHAR(60) NOT NULL,                  -- created, updated, deleted, login, voided
  subject_type  VARCHAR(80) NULL,
  subject_id    BIGINT UNSIGNED NULL,
  old_values    JSON NULL,
  new_values    JSON NULL,
  ip_address    VARCHAR(45) NULL,
  created_at    TIMESTAMP NULL,
  KEY idx_log_ph_date (pharmacy_id, created_at),
  KEY idx_log_subject (subject_type, subject_id)
) ENGINE=InnoDB;

CREATE TABLE invoice_sequences (                       -- per-shop invoice numbering
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NOT NULL,
  branch_id    BIGINT UNSIGNED NOT NULL,
  doc_type     ENUM('sale','purchase','sale_return','purchase_return') NOT NULL,
  prefix       VARCHAR(10) NOT NULL DEFAULT '',
  last_number  BIGINT UNSIGNED NOT NULL DEFAULT 0,     -- increment with row lock (SELECT ... FOR UPDATE)
  UNIQUE KEY uq_seq (pharmacy_id, branch_id, doc_type)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- B. MASTER DATA
-- ---------------------------------------------------------------------

CREATE TABLE generics (                                -- e.g. Paracetamol, Omeprazole
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NULL,                   -- NULL = global list you maintain
  name         VARCHAR(150) NOT NULL,
  note         VARCHAR(255) NULL,
  created_at   TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  KEY idx_gen_name (name),
  KEY idx_gen_ph (pharmacy_id)
) ENGINE=InnoDB;

CREATE TABLE manufacturers (                           -- company/brand: Square, Beximco, Incepta
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NULL,
  name         VARCHAR(150) NOT NULL,
  created_at   TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  KEY idx_mf_ph (pharmacy_id), KEY idx_mf_name (name)
) ENGINE=InnoDB;

CREATE TABLE product_types (                           -- Tablet, Capsule, Syrup, Injection, Cream...
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NULL,
  name         VARCHAR(80) NOT NULL,
  KEY idx_pt_ph (pharmacy_id)
) ENGINE=InnoDB;

CREATE TABLE categories (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NULL,
  name         VARCHAR(100) NOT NULL,
  KEY idx_cat_ph (pharmacy_id)
) ENGINE=InnoDB;

CREATE TABLE units (                                   -- Piece, Strip, Box, Bottle, Vial
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NULL,
  name         VARCHAR(60) NOT NULL,
  short_name   VARCHAR(20) NULL,
  KEY idx_unit_ph (pharmacy_id)
) ENGINE=InnoDB;

-- RACKS: the main requirement. Shelf, showcase, fridge, controlled cabinet...
CREATE TABLE racks (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NOT NULL,
  branch_id    BIGINT UNSIGNED NOT NULL,
  code         VARCHAR(30) NOT NULL,                   -- A-1, FRIDGE-1, CTRL-1  (shown on POS)
  name         VARCHAR(100) NULL,
  section      VARCHAR(60) NULL,                       -- Front, Back, Store room
  rack_type    ENUM('shelf','showcase','fridge','drawer','controlled','store','unassigned') NOT NULL DEFAULT 'shelf',
  sale_channel ENUM('retail','wholesale','both') NOT NULL DEFAULT 'both', -- which kind of sale this rack serves
  pick_priority TINYINT UNSIGNED NOT NULL DEFAULT 10, -- POS lists racks by this (1 = take from here first)
  note         VARCHAR(255) NULL,
  is_active    TINYINT(1) NOT NULL DEFAULT 1,
  created_at   TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  UNIQUE KEY uq_rack_code (pharmacy_id, branch_id, code),
  CONSTRAINT fk_rack_ph FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_rack_br FOREIGN KEY (branch_id)   REFERENCES branches(id)
) ENGINE=InnoDB;
-- RULE: when a branch is created, auto-create one rack: code 'UNASSIGNED', type 'unassigned'.
-- Stock received without a chosen rack goes there, so rack_id is never NULL.

CREATE TABLE suppliers (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id     BIGINT UNSIGNED NOT NULL,
  name            VARCHAR(150) NOT NULL,
  contact_person  VARCHAR(120) NULL,
  phone           VARCHAR(20) NULL,
  address         VARCHAR(255) NULL,
  opening_due     DECIMAL(14,2) NOT NULL DEFAULT 0,    -- we owe them
  is_active       TINYINT(1) NOT NULL DEFAULT 1,
  created_at      TIMESTAMP NULL, updated_at TIMESTAMP NULL, deleted_at TIMESTAMP NULL,
  KEY idx_sup_ph (pharmacy_id),
  CONSTRAINT fk_sup_ph FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id)
) ENGINE=InnoDB;

CREATE TABLE customers (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id     BIGINT UNSIGNED NOT NULL,
  name            VARCHAR(150) NOT NULL,
  phone           VARCHAR(20) NULL,
  address         VARCHAR(255) NULL,
  customer_type   ENUM('retail','wholesale') NOT NULL DEFAULT 'retail', -- wholesale = other shops/clinics
  credit_limit    DECIMAL(14,2) NOT NULL DEFAULT 0,
  opening_due     DECIMAL(14,2) NOT NULL DEFAULT 0,    -- customer owes us (baki khata)
  is_active       TINYINT(1) NOT NULL DEFAULT 1,
  created_at      TIMESTAMP NULL, updated_at TIMESTAMP NULL, deleted_at TIMESTAMP NULL,
  KEY idx_cus_ph_phone (pharmacy_id, phone),
  CONSTRAINT fk_cus_ph FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id)
) ENGINE=InnoDB;

CREATE TABLE products (
  id                    BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id           BIGINT UNSIGNED NOT NULL,
  name                  VARCHAR(180) NOT NULL,         -- brand name: "Napa Extra"
  strength              VARCHAR(60) NULL,              -- 500 mg, 5 mg/5 ml
  generic_id            BIGINT UNSIGNED NULL,
  manufacturer_id       BIGINT UNSIGNED NULL,
  product_type_id       BIGINT UNSIGNED NULL,
  category_id           BIGINT UNSIGNED NULL,
  product_code          VARCHAR(50) NULL,
  barcode               VARCHAR(64) NULL,
  base_unit_id          BIGINT UNSIGNED NOT NULL,      -- smallest sellable unit (piece)
  default_rack_id       BIGINT UNSIGNED NULL,          -- suggested rack when receiving stock
  vat_percent           DECIMAL(5,2) NOT NULL DEFAULT 0,
  default_discount_pct  DECIMAL(5,2) NOT NULL DEFAULT 0,
  alert_qty             INT UNSIGNED NOT NULL DEFAULT 0, -- low stock level (base units)
  reorder_qty           INT UNSIGNED NOT NULL DEFAULT 0, -- suggested order qty (base units)
  is_controlled         TINYINT(1) NOT NULL DEFAULT 0,   -- drug-control / sleeping pills etc.
  requires_prescription TINYINT(1) NOT NULL DEFAULT 0,
  needs_cold_storage    TINYINT(1) NOT NULL DEFAULT 0,
  description           TEXT NULL,
  image_path            VARCHAR(255) NULL,
  is_active             TINYINT(1) NOT NULL DEFAULT 1,
  created_at            TIMESTAMP NULL, updated_at TIMESTAMP NULL, deleted_at TIMESTAMP NULL,
  KEY idx_prod_ph_name (pharmacy_id, name),
  KEY idx_prod_ph_barcode (pharmacy_id, barcode),
  KEY idx_prod_generic (pharmacy_id, generic_id),
  CONSTRAINT fk_prod_ph   FOREIGN KEY (pharmacy_id)     REFERENCES pharmacies(id),
  CONSTRAINT fk_prod_gen  FOREIGN KEY (generic_id)      REFERENCES generics(id),
  CONSTRAINT fk_prod_mf   FOREIGN KEY (manufacturer_id) REFERENCES manufacturers(id),
  CONSTRAINT fk_prod_pt   FOREIGN KEY (product_type_id) REFERENCES product_types(id),
  CONSTRAINT fk_prod_cat  FOREIGN KEY (category_id)     REFERENCES categories(id),
  CONSTRAINT fk_prod_unit FOREIGN KEY (base_unit_id)    REFERENCES units(id),
  CONSTRAINT fk_prod_rack FOREIGN KEY (default_rack_id) REFERENCES racks(id)
) ENGINE=InnoDB;

-- Unit conversion per product. Example: Napa -> Piece=1, Strip=10, Box=100 (base = piece)
CREATE TABLE product_units (
  id               BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  product_id       BIGINT UNSIGNED NOT NULL,
  unit_id          BIGINT UNSIGNED NOT NULL,
  factor_to_base   INT UNSIGNED NOT NULL,              -- how many base units in this unit
  can_sell         TINYINT(1) NOT NULL DEFAULT 1,
  can_purchase     TINYINT(1) NOT NULL DEFAULT 1,
  UNIQUE KEY uq_pu (product_id, unit_id),
  CONSTRAINT fk_pu_prod FOREIGN KEY (product_id) REFERENCES products(id),
  CONSTRAINT fk_pu_unit FOREIGN KEY (unit_id)    REFERENCES units(id)
) ENGINE=InnoDB;

-- Same product can come from many suppliers
CREATE TABLE product_suppliers (
  product_id       BIGINT UNSIGNED NOT NULL,
  supplier_id      BIGINT UNSIGNED NOT NULL,
  last_price_base  DECIMAL(14,4) NULL,
  last_purchased   DATE NULL,
  PRIMARY KEY (product_id, supplier_id),
  CONSTRAINT fk_ps_prod FOREIGN KEY (product_id)  REFERENCES products(id),
  CONSTRAINT fk_ps_sup  FOREIGN KEY (supplier_id) REFERENCES suppliers(id)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- C. BATCH + STOCK + RACK LOCATION
-- ---------------------------------------------------------------------

CREATE TABLE batches (
  id               BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id      BIGINT UNSIGNED NOT NULL,
  product_id       BIGINT UNSIGNED NOT NULL,
  batch_no         VARCHAR(60) NOT NULL,
  mfg_date         DATE NULL,
  expiry_date      DATE NOT NULL,
  purchase_price   DECIMAL(14,4) NOT NULL,             -- per BASE unit (TP + VAT)
  mrp              DECIMAL(14,4) NOT NULL,             -- per BASE unit (retail price)
  wholesale_price  DECIMAL(14,4) NULL,                 -- per BASE unit; NULL = shop does not wholesale this
  is_active        TINYINT(1) NOT NULL DEFAULT 1,
  created_at       TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  UNIQUE KEY uq_batch (pharmacy_id, product_id, batch_no, expiry_date),
  KEY idx_batch_expiry (pharmacy_id, expiry_date),     -- expiry alerts + FEFO
  CONSTRAINT fk_b_ph   FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_b_prod FOREIGN KEY (product_id)  REFERENCES products(id)
) ENGINE=InnoDB;

-- Current balance: one row per (batch, branch, rack). Multi-rack ready.
CREATE TABLE batch_stocks (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NOT NULL,
  branch_id    BIGINT UNSIGNED NOT NULL,
  product_id   BIGINT UNSIGNED NOT NULL,               -- denormalized for fast search
  batch_id     BIGINT UNSIGNED NOT NULL,
  rack_id      BIGINT UNSIGNED NOT NULL,
  qty_base     INT NOT NULL DEFAULT 0,                 -- must never go below 0 (check in code + DB)
  updated_at   TIMESTAMP NULL,
  UNIQUE KEY uq_bs (batch_id, branch_id, rack_id),
  KEY idx_bs_product (pharmacy_id, branch_id, product_id),
  KEY idx_bs_rack (pharmacy_id, rack_id),
  CONSTRAINT chk_bs_qty CHECK (qty_base >= 0),
  CONSTRAINT fk_bs_ph    FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_bs_br    FOREIGN KEY (branch_id)   REFERENCES branches(id),
  CONSTRAINT fk_bs_prod  FOREIGN KEY (product_id)  REFERENCES products(id),
  CONSTRAINT fk_bs_batch FOREIGN KEY (batch_id)    REFERENCES batches(id),
  CONSTRAINT fk_bs_rack  FOREIGN KEY (rack_id)     REFERENCES racks(id)
) ENGINE=InnoDB;

-- Ledger of every stock change. Never edited or deleted; corrections = new rows.
CREATE TABLE stock_movements (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id    BIGINT UNSIGNED NOT NULL,
  branch_id      BIGINT UNSIGNED NOT NULL,
  product_id     BIGINT UNSIGNED NOT NULL,
  batch_id       BIGINT UNSIGNED NOT NULL,
  rack_id        BIGINT UNSIGNED NOT NULL,
  movement_type  ENUM('opening','purchase','purchase_return','sale','sale_return',
                      'adjust_in','adjust_out','damage','expired','rack_out','rack_in',
                      'branch_out','branch_in') NOT NULL,
  qty_base       INT NOT NULL,                         -- signed: + in, - out
  ref_type       VARCHAR(40) NULL,                     -- purchases, sales, stock_adjustments ...
  ref_id         BIGINT UNSIGNED NULL,
  user_id        BIGINT UNSIGNED NULL,
  note           VARCHAR(255) NULL,
  created_at     TIMESTAMP NULL,
  KEY idx_sm_product (pharmacy_id, product_id, created_at),
  KEY idx_sm_ref (ref_type, ref_id),
  CONSTRAINT fk_sm_ph FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id)
) ENGINE=InnoDB;

-- Moving stock from one rack to another (history of rack changes)
CREATE TABLE rack_transfers (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id   BIGINT UNSIGNED NOT NULL,
  branch_id     BIGINT UNSIGNED NOT NULL,
  batch_id      BIGINT UNSIGNED NOT NULL,
  from_rack_id  BIGINT UNSIGNED NOT NULL,
  to_rack_id    BIGINT UNSIGNED NOT NULL,
  qty_base      INT UNSIGNED NOT NULL,
  user_id       BIGINT UNSIGNED NULL,
  note          VARCHAR(255) NULL,
  created_at    TIMESTAMP NULL,
  KEY idx_rt_ph (pharmacy_id, created_at),
  CONSTRAINT fk_rt_batch FOREIGN KEY (batch_id)     REFERENCES batches(id),
  CONSTRAINT fk_rt_from  FOREIGN KEY (from_rack_id) REFERENCES racks(id),
  CONSTRAINT fk_rt_to    FOREIGN KEY (to_rack_id)   REFERENCES racks(id)
) ENGINE=InnoDB;

-- Damage / expired / stock-audit corrections
CREATE TABLE stock_adjustments (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id   BIGINT UNSIGNED NOT NULL,
  branch_id     BIGINT UNSIGNED NOT NULL,
  reason        ENUM('damage','expired','audit_correction','lost','other') NOT NULL,
  adjusted_on   DATE NOT NULL,
  user_id       BIGINT UNSIGNED NULL,
  note          VARCHAR(255) NULL,
  created_at    TIMESTAMP NULL,
  KEY idx_sa_ph (pharmacy_id, adjusted_on)
) ENGINE=InnoDB;

CREATE TABLE stock_adjustment_items (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  adjustment_id  BIGINT UNSIGNED NOT NULL,
  product_id     BIGINT UNSIGNED NOT NULL,
  batch_id       BIGINT UNSIGNED NOT NULL,
  rack_id        BIGINT UNSIGNED NOT NULL,
  qty_base       INT NOT NULL,                         -- signed
  CONSTRAINT fk_sai_adj FOREIGN KEY (adjustment_id) REFERENCES stock_adjustments(id)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- D. PURCHASE
-- ---------------------------------------------------------------------

CREATE TABLE purchases (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id    BIGINT UNSIGNED NOT NULL,
  branch_id      BIGINT UNSIGNED NOT NULL,
  supplier_id    BIGINT UNSIGNED NOT NULL,
  invoice_no     VARCHAR(40) NOT NULL,                 -- our number (from invoice_sequences)
  supplier_invoice_no VARCHAR(60) NULL,
  purchase_date  DATE NOT NULL,
  subtotal       DECIMAL(14,2) NOT NULL DEFAULT 0,
  discount       DECIMAL(14,2) NOT NULL DEFAULT 0,
  vat            DECIMAL(14,2) NOT NULL DEFAULT 0,
  total          DECIMAL(14,2) NOT NULL DEFAULT 0,
  paid           DECIMAL(14,2) NOT NULL DEFAULT 0,
  due            DECIMAL(14,2) NOT NULL DEFAULT 0,
  status         ENUM('draft','received','void') NOT NULL DEFAULT 'received',
  user_id        BIGINT UNSIGNED NULL,
  note           VARCHAR(255) NULL,
  created_at     TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  UNIQUE KEY uq_pur_inv (pharmacy_id, invoice_no),
  KEY idx_pur_date (pharmacy_id, purchase_date),
  CONSTRAINT fk_pur_ph  FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_pur_sup FOREIGN KEY (supplier_id) REFERENCES suppliers(id)
) ENGINE=InnoDB;

CREATE TABLE purchase_items (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  purchase_id     BIGINT UNSIGNED NOT NULL,
  product_id      BIGINT UNSIGNED NOT NULL,
  batch_id        BIGINT UNSIGNED NOT NULL,            -- created/found at receiving time
  rack_id         BIGINT UNSIGNED NOT NULL,            -- where it was put
  unit_id         BIGINT UNSIGNED NOT NULL,            -- unit entered by user (box/strip)
  qty_entered     INT UNSIGNED NOT NULL,
  qty_base        INT UNSIGNED NOT NULL,               -- qty_entered * factor
  unit_price      DECIMAL(14,4) NOT NULL,              -- per entered unit
  mrp_base        DECIMAL(14,4) NOT NULL,
  discount        DECIMAL(14,2) NOT NULL DEFAULT 0,
  line_total      DECIMAL(14,2) NOT NULL,
  CONSTRAINT fk_pi_pur   FOREIGN KEY (purchase_id) REFERENCES purchases(id),
  CONSTRAINT fk_pi_prod  FOREIGN KEY (product_id)  REFERENCES products(id),
  CONSTRAINT fk_pi_batch FOREIGN KEY (batch_id)    REFERENCES batches(id)
) ENGINE=InnoDB;

CREATE TABLE purchase_returns (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id    BIGINT UNSIGNED NOT NULL,
  branch_id      BIGINT UNSIGNED NOT NULL,
  purchase_id    BIGINT UNSIGNED NULL,
  supplier_id    BIGINT UNSIGNED NOT NULL,
  return_no      VARCHAR(40) NOT NULL,
  return_date    DATE NOT NULL,
  total          DECIMAL(14,2) NOT NULL DEFAULT 0,
  reason         VARCHAR(255) NULL,
  user_id        BIGINT UNSIGNED NULL,
  created_at     TIMESTAMP NULL,
  UNIQUE KEY uq_pr_no (pharmacy_id, return_no)
) ENGINE=InnoDB;

CREATE TABLE purchase_return_items (
  id                 BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  purchase_return_id BIGINT UNSIGNED NOT NULL,
  product_id         BIGINT UNSIGNED NOT NULL,
  batch_id           BIGINT UNSIGNED NOT NULL,
  rack_id            BIGINT UNSIGNED NOT NULL,
  qty_base           INT UNSIGNED NOT NULL,
  unit_price_base    DECIMAL(14,4) NOT NULL,
  line_total         DECIMAL(14,2) NOT NULL,
  CONSTRAINT fk_pri_ret FOREIGN KEY (purchase_return_id) REFERENCES purchase_returns(id)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- E. SALES (POS)
-- ---------------------------------------------------------------------

CREATE TABLE sales (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id     BIGINT UNSIGNED NOT NULL,
  branch_id       BIGINT UNSIGNED NOT NULL,
  invoice_no      VARCHAR(40) NOT NULL,
  customer_id     BIGINT UNSIGNED NULL,                -- NULL = walk-in
  sale_type       ENUM('retail','wholesale') NOT NULL DEFAULT 'retail', -- decides price (mrp vs wholesale_price) and rack order
  sale_date       DATETIME NOT NULL,
  subtotal        DECIMAL(14,2) NOT NULL DEFAULT 0,
  discount        DECIMAL(14,2) NOT NULL DEFAULT 0,
  vat             DECIMAL(14,2) NOT NULL DEFAULT 0,
  total           DECIMAL(14,2) NOT NULL DEFAULT 0,
  paid            DECIMAL(14,2) NOT NULL DEFAULT 0,
  due             DECIMAL(14,2) NOT NULL DEFAULT 0,
  payment_status  ENUM('paid','partial','due') NOT NULL DEFAULT 'paid',
  doctor_name     VARCHAR(120) NULL,
  prescription_no VARCHAR(60) NULL,
  status          ENUM('completed','void') NOT NULL DEFAULT 'completed',
  user_id         BIGINT UNSIGNED NULL,                -- salesman
  note            VARCHAR(255) NULL,
  created_at      TIMESTAMP NULL, updated_at TIMESTAMP NULL,
  UNIQUE KEY uq_sale_inv (pharmacy_id, invoice_no),
  KEY idx_sale_date (pharmacy_id, branch_id, sale_date),
  KEY idx_sale_cus (pharmacy_id, customer_id),
  CONSTRAINT fk_sale_ph  FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
  CONSTRAINT fk_sale_cus FOREIGN KEY (customer_id) REFERENCES customers(id)
) ENGINE=InnoDB;

CREATE TABLE sale_items (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  sale_id         BIGINT UNSIGNED NOT NULL,
  product_id      BIGINT UNSIGNED NOT NULL,
  batch_id        BIGINT UNSIGNED NOT NULL,            -- chosen by FEFO (earliest expiry first)
  rack_id         BIGINT UNSIGNED NOT NULL,            -- rack the stock was taken from
  unit_id         BIGINT UNSIGNED NOT NULL,            -- unit sold (strip/piece/box)
  qty_entered     INT UNSIGNED NOT NULL,
  qty_base        INT UNSIGNED NOT NULL,
  unit_price      DECIMAL(14,4) NOT NULL,              -- per entered unit (selling)
  cost_price_base DECIMAL(14,4) NOT NULL,              -- batch cost at sale time => accurate profit
  discount        DECIMAL(14,2) NOT NULL DEFAULT 0,
  vat             DECIMAL(14,2) NOT NULL DEFAULT 0,
  line_total      DECIMAL(14,2) NOT NULL,
  KEY idx_si_sale (sale_id),
  KEY idx_si_product (product_id),
  CONSTRAINT fk_si_sale  FOREIGN KEY (sale_id)    REFERENCES sales(id),
  CONSTRAINT fk_si_prod  FOREIGN KEY (product_id) REFERENCES products(id),
  CONSTRAINT fk_si_batch FOREIGN KEY (batch_id)   REFERENCES batches(id)
) ENGINE=InnoDB;
-- One cart line can be split into several sale_items rows when one batch is not enough.

CREATE TABLE sale_returns (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id     BIGINT UNSIGNED NOT NULL,
  branch_id       BIGINT UNSIGNED NOT NULL,
  sale_id         BIGINT UNSIGNED NOT NULL,
  return_no       VARCHAR(40) NOT NULL,
  return_date     DATETIME NOT NULL,
  refund_amount   DECIMAL(14,2) NOT NULL DEFAULT 0,
  reason          VARCHAR(255) NULL,
  user_id         BIGINT UNSIGNED NULL,
  created_at      TIMESTAMP NULL,
  UNIQUE KEY uq_sr_no (pharmacy_id, return_no)
) ENGINE=InnoDB;

CREATE TABLE sale_return_items (
  id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  sale_return_id  BIGINT UNSIGNED NOT NULL,
  sale_item_id    BIGINT UNSIGNED NOT NULL,
  product_id      BIGINT UNSIGNED NOT NULL,
  batch_id        BIGINT UNSIGNED NOT NULL,
  rack_id         BIGINT UNSIGNED NOT NULL,
  qty_base        INT UNSIGNED NOT NULL,
  refund_line     DECIMAL(14,2) NOT NULL,
  restock         TINYINT(1) NOT NULL DEFAULT 1,       -- 0 = damaged, do not put back on shelf
  CONSTRAINT fk_sri_ret FOREIGN KEY (sale_return_id) REFERENCES sale_returns(id)
) ENGINE=InnoDB;

-- Drug-control register: separate log for controlled medicines
CREATE TABLE controlled_drug_log (
  id               BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id      BIGINT UNSIGNED NOT NULL,
  sale_item_id     BIGINT UNSIGNED NOT NULL,
  product_id       BIGINT UNSIGNED NOT NULL,
  batch_id         BIGINT UNSIGNED NOT NULL,
  qty_base         INT UNSIGNED NOT NULL,
  buyer_name       VARCHAR(120) NULL,
  buyer_phone      VARCHAR(20) NULL,
  doctor_name      VARCHAR(120) NULL,
  prescription_no  VARCHAR(60) NULL,
  created_at       TIMESTAMP NULL,
  KEY idx_cdl_ph (pharmacy_id, created_at)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- F. MONEY: payments, expenses
-- ---------------------------------------------------------------------

CREATE TABLE payments (                                -- every taka in/out against a sale or purchase
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id   BIGINT UNSIGNED NOT NULL,
  branch_id     BIGINT UNSIGNED NOT NULL,
  direction     ENUM('in','out') NOT NULL,             -- in = from customer, out = to supplier
  party_type    ENUM('customer','supplier') NOT NULL,
  party_id      BIGINT UNSIGNED NULL,
  ref_type      ENUM('sale','purchase','sale_return','purchase_return','due_collection','opening') NOT NULL,
  ref_id        BIGINT UNSIGNED NULL,
  method        ENUM('cash','bkash','nagad','rocket','card','bank') NOT NULL DEFAULT 'cash',
  amount        DECIMAL(14,2) NOT NULL,
  trx_id        VARCHAR(80) NULL,
  paid_at       DATETIME NOT NULL,
  user_id       BIGINT UNSIGNED NULL,
  note          VARCHAR(255) NULL,
  created_at    TIMESTAMP NULL,
  KEY idx_pay_date (pharmacy_id, paid_at),
  KEY idx_pay_party (pharmacy_id, party_type, party_id),
  KEY idx_pay_ref (ref_type, ref_id)
) ENGINE=InnoDB;

CREATE TABLE expense_categories (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NOT NULL,
  name         VARCHAR(100) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE expenses (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  pharmacy_id  BIGINT UNSIGNED NOT NULL,
  branch_id    BIGINT UNSIGNED NOT NULL,
  category_id  BIGINT UNSIGNED NOT NULL,
  amount       DECIMAL(14,2) NOT NULL,
  expense_date DATE NOT NULL,
  method       ENUM('cash','bkash','nagad','rocket','card','bank') NOT NULL DEFAULT 'cash',
  note         VARCHAR(255) NULL,
  user_id      BIGINT UNSIGNED NULL,
  created_at   TIMESTAMP NULL,
  KEY idx_exp_date (pharmacy_id, expense_date)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- G. USEFUL QUERIES (examples to keep in mind while coding)
-- ---------------------------------------------------------------------
-- 1) Where is this medicine? (show on POS next to the name)
--    SELECT r.code, b.batch_no, b.expiry_date, bs.qty_base
--    FROM batch_stocks bs
--    JOIN racks r ON r.id = bs.rack_id
--    JOIN batches b ON b.id = bs.batch_id
--    WHERE bs.pharmacy_id = :ph AND bs.branch_id = :br AND bs.product_id = :p AND bs.qty_base > 0
--    ORDER BY b.expiry_date ASC;                        -- FEFO order
--
-- 2) Alternatives with same generic (and their racks)
--    SELECT p.name, p.strength, r.code, SUM(bs.qty_base) qty
--    FROM products p
--    JOIN batch_stocks bs ON bs.product_id = p.id AND bs.qty_base > 0
--    JOIN racks r ON r.id = bs.rack_id
--    WHERE p.pharmacy_id = :ph AND p.generic_id = :generic
--    GROUP BY p.id, r.id;
--
-- 3) Expiring within 90 days
--    SELECT * FROM batches b JOIN batch_stocks bs ON bs.batch_id = b.id
--    WHERE b.pharmacy_id = :ph AND bs.qty_base > 0
--      AND b.expiry_date <= DATE_ADD(CURDATE(), INTERVAL 90 DAY);
--
-- 4) Low stock: SUM(qty_base) per product < products.alert_qty
