# Master Backend & Saree ERP System Plan (Two-Stage Architecture)
*(AI Coding Agent & Project Owner Blueprint — Backend & ERP Specification)*

**Project:** Aangina — Bangladesh Saree E-Commerce & Business ERP System  
**Selected Technology Stack:** **PHP 8.2+ (Laravel 11)** + **MySQL / MariaDB** + **Blade + Tailwind CSS (Strictly Mapped to 12 `:root` Variables) + Alpine.js + Vite** (Storefront) + **FilamentPHP / Livewire 3** (Admin & ERP Dashboard)  
**Target Hosting:** **cPanel Hosting** (LiteSpeed + PHP OPcache, with zero-code-change upgrade path to VPS later)  
**Frontend Reference Folder:** `../frontend/` (All 15 Frontend Storefront specification files)

---

## 1. Master Project Execution Roadmap (How Frontend, Backend & ERP Connect)

To keep development clean, fast, and risk-free, the entire project is divided into **Phase A (Frontend)** followed by **Phase B in Two Stages (Stage 1: Website Backend → Stage 2: Full ERP System)**:

```text
================================================================================
PHASE A: FRONTEND STOREFRONT BUILD (Folder: /frontend)
================================================================================
Build all 9 Frontend steps (Homepage, /sarees Hub, Category/Collection Grids,
Quick View, PDP with Weave Zoom, Cart Drawer, 1-Page Guest COD Checkout, Policy
Pages) using the 12 CSS Variables + central storeConfig & mock sareesData.
                                      ↓
================================================================================
PHASE B — STAGE 1: WEBSITE BACKEND, CMS & LIVE ORDER NOTIFICATIONS (This Plan)
================================================================================
Connect MySQL Database, Dynamic :root Theme Token Engine, Saree & Category CRUD
(with auto-WebP 3:4 image optimizer), Guest COD & Express Buy Order Pipeline
(#ANG-XXXX), Instant Live Order Alerts (Dashboard Sound + Telegram Mobile Push),
Automated Customer Emails, and Review Moderation.
                                      ↓
================================================================================
PHASE B — STAGE 2: AANGINA SAREE ERP SYSTEM (Built on Stage 1 Foundation)
================================================================================
Expand the Admin Panel into a full Business ERP: Weaver/Supplier Ledger,
Weaving Cost & Batch Purchasing, SKU Barcode Printing, Manual Order Desk (for
Facebook/WhatsApp/Phone orders), 1-Click Courier API (Steadfast/Pathao/RedX),
COD Cash Reconciliation, Expense Tracking, Net Profit Accounting & Staff Roles.
```

> [!IMPORTANT]
> **Smart Database Rule (Zero Re-Work Between Stage 1 and Stage 2):**  
> During **Stage 1**, the core `products` and `orders` database tables will already include nullable ERP-ready columns (such as `cost_price_bdt`, `weaver_id`, `order_source`, and `courier_tracking_code`). This guarantees that when we start **Stage 2 (ERP)**, we never have to rewrite or break the Stage 1 website backend.

---

## 2. Why Laravel (PHP) + Tailwind CSS (`:root` Tokens) + Livewire/Filament Is the Ideal Architecture

1. **Fastest Loading Speed on cPanel (`< 50ms – 80ms` TTFB):**
   * Runs natively on cPanel's LiteSpeed + PHP OPcache with **zero cold-start delays** (unlike Node.js Passenger processes that go to sleep when idle).
2. **Tiny Mobile Footprint (`~10 KB` Tailwind CSS + `~15 KB` Alpine.js) for Bangladesh 3G/4G Networks:**
   * The customer storefront uses server-rendered **Laravel Blade** + **Tailwind CSS strictly mapped to the 12 `:root` CSS Variables** (with default Tailwind color palettes disabled) + **Alpine.js (`~15 KB`)**, delivering instant page loads, live Admin re-theming without rebuilding CSS, and native **Facebook / Messenger / WhatsApp Open Graph (`og:`) previews**.
3. **Real-Time Live Order Notifications on Shared cPanel:**
   * Combines **In-Dashboard Live Popups + Audio Chime (`🔔`)** (via Pusher Free Tier / Livewire Polling) with **Instant Telegram Bot / Mobile Push Alerts** (`< 1 second` delivery to your phone even when your PC is off).
4. **Enterprise-Grade Built-In Security:**
   * Native protection against SQL Injection, XSS, CSRF, malicious image uploads, and fake Guest COD order spam (via IP & BD mobile rate-limiting).

---

## 3. STAGE 1: Core Website Backend & Storefront Admin CMS

Stage 1 powers every dynamic feature promised in the 15 frontend specification files, replacing `storeConfig`, `categoriesData`, and `sareesData` with a live MySQL database and an intuitive Admin Dashboard (`/admin`).

### Module 1.1 — Dynamic Theme & Store Configuration (`store_settings`)
Directly powers `global_color_typography_design_plan.md`, `global_header_and_footer_plan.md`, and `future_admin_controls_and_dynamic_frontend_notes.md`:
* **Live 12 CSS Token Theme Editor (`Appearance → Theme Settings`):**
  * 10 Color Pickers (`--bg-main`, `--bg-surface`, `--brand-primary`, `--brand-accent`, `--text-primary`, `--text-muted`, `--text-light`, `--border-subtle`, `--state-success`, `--state-error`) + 2 Google Font Selectors (`--font-heading`, `--font-body`).
  * **Built-In Contrast Guard:** Automatically checks contrast ratios (e.g., `--text-primary` on `--brand-accent` and `--text-light` on `--brand-primary`) and warns the admin if any pairing drops below `4.5 : 1`.
  * **1-Click Reset:** *"Reset to Default Aangina Brand Palette"* button restores the exact verified values from `global_color_typography_design_plan.md`.
* **Header & Navigation Mode Switcher:**
  * 1-Click toggle between **`MODE_A` (Flat Direct Saree Category Bar)** and **`MODE_B` (Minimal Boutique Bar)**.
  * Top Announcement Bar toggle (`enabled: true/false`) and customizable text.
* **Delivery Charges & Store Contact Settings:**
  * Inside Dhaka charge (`BDT 70`) & timeline (`2 – 3 Business Days`).
  * Outside Dhaka charge (`BDT 130`) & timeline (`3 – 5 Business Days`).
  * Helpline phone, WhatsApp number, Facebook Messenger URL, support hours, email, social links, and Floating Chat Widget toggle.

### Module 1.2 — Homepage & Editorial Banner Manager (`homepage_sections`)
Directly powers `homepage_layout_and_section_flow_plan.md`:
* **Hero Slider Manager (1–3 Slides):**
  * Separate upload slots for **Desktop `4:3` Landscape (`1600 × 1200px`)** and **Mobile `4:5` Uncropped Portrait (`1080 × 1350px`)**, plus Eyebrow label, H1 Headline, Subtitle, CTA text, and destination link.
* **Festive & Bridal Spotlight Banner:**
  * Dual `3:4` collage images, eyebrow, heading, story copy, CTA button, and visibility toggle.
* **Most Loved (Best Sellers) Control:**
  * Switch between **`AUTOMATIC`** (auto-sorted by `salesCount`) and **`MANUAL`** (hand-picked sarees).
* **4 Non-Overlapping Budget Tiles:**
  * Editable labels, subtexts, and BDT min/max brackets (`Under BDT 2,500`, `BDT 2,500 – 4,999`, `BDT 5,000 – 9,999`, `BDT 10,000 & Above`).

### Module 1.3 — 2-Level Category & Curated Collection Manager (`categories` & `collections`)
Directly powers `all_sarees_category_showcase_plan.md`, `single_category_view_all_page_plan.md`, and `collection_and_utility_pages_plan.md`:
* **Future-Proof 2-Level Hierarchy:**
  * **Level 1 (`parent_department`):** Defaults to `Sarees` now; ready to activate `Salwar Kameez`, `Kurtis`, `Dupattas`, and `Jewelry` later.
  * **Level 2 (`categories`):** *Jamdani, Muslin, Katan, Silk, Cotton, Tangail, etc.*
* **Category Fields:**
  * `name`, `short_name` (for pills/menubar), `slug`, `display_order` (drag-and-drop row ordering for `/sarees`), `show_in_header_mode_a`, `cover_image` (`3:4` portrait), `description`, and `default_care_instructions`.
* **Automatic Empty-Category Protection:**
  * Any category with `0` active products is automatically hidden from the storefront navigation, `/sarees` hub rows, and filter dropdowns.

### Module 1.4 — Saree Catalog, Standardized Specs & Smart Image Pipeline (`products`)
Directly powers `product_details_page_pdp_plan.md` and `quick_view_modal_page_plan.md`:
* **Core Product Data:**
  * `title`, `slug`, `sku` (auto-generated or custom, e.g., `ANG-JM-104`), `category_id`, `collections` checkboxes (`new-arrivals`, `festive-edit`, `best-sellers`).
  * `price_bdt` (whole integer) and optional `old_price_bdt` (automatically computes `floor((old - price) / old * 100)` for `-X%` card badges and `SAVE X%` PDP pills, and automatically includes discounted sarees in `/collections/offers`).
  * `stock_qty` and `in_stock` status (shows `"Only X left in stock"` when `1–3`; moves item to the end of category grids with `SOLD OUT` badge when `0`).
* **Standardized Saree Specifications (Dropdowns + Custom Override):**
  * Uses the exact filter taxonomy from `global_ui_components_and_content_standards.md`:
    * `fabric` (e.g., *80-Count Pure Cotton Jamdani*)
    * `length` (default: *12 Haat (5.5 Meters)*) & `width` (default: *47 Inches*)
    * `blouse_piece` (*With Blouse Piece* | *Without Blouse Piece*) + `blouse_piece_detail` (*Included (1 Yard Unstitched)*)
    * `work_type` (*Handloom / Tant, Zari Work, Embroidered, Karchupi, Printed, Plain / Solid*)
    * `color_family` (*Red, Maroon, Pink / Pastel, Yellow / Mustard, Green, Blue, White / Off-White, Black, Gold / Champagne, Multi-Color*)
    * `aanchal_style`, `occasion` (multi-select), `origin` (*Made in Bangladesh*), and optional `care_instructions` override.
* **Automated `3:4` Image Upload & WebP Optimization Pipeline:**
  * Drag-and-drop multi-image uploader (`Image 1: Front Drape`, `Image 2: Aanchal Closeup` for card hover/1st tap, `Image 3: Border/Weave`, `Image 4: Blouse Piece`, `Image 5: Full View`).
  * **Server-Side Auto-Processing:** On upload, the backend strips EXIF/script metadata, enforces the **`3:4` aspect ratio**, and generates:
    1. **High-Res Weave Zoom Image (`1200 × 1600px` WebP)** for PDP `2.5×` magnifier & mobile pinch-to-zoom lightbox.
    2. **Card & Slider Image (`600 × 800px` WebP)** for fast grid/slider loading.
    3. **Mini Thumbnail (`180 × 240px` WebP)** for Cart Drawer, Checkout, and PDP thumbnail strip.
    4. **Social Share Card (`1200 × 630px` OG Image)** for Facebook, Messenger, and WhatsApp link previews.

### Module 1.5 — Guest COD Checkout, Phone-Verified Stock Deduction & Coupon Engine (`orders`, `order_call_logs` & `coupons`)
Directly powers `cart_and_checkout_flow_plan.md` and the **Bangladesh Phone-Verification Order Workflow**:

* **1. Visitor Places Order (`Status: Pending Call Verification` — Stock NOT Deducted Yet):**
  * Handles both **Full Cart Checkout** and **Express Buy (`ORDER NOW`)** (preserving untouched items in the shopper's bag while supporting the 1-tap `"+ Add them to this order"` merge).
  * Validates 11-digit BD mobile numbers (`01[3-9]XXXXXXXX`), 64 Bangladesh Districts, Delivery Zone (`Inside Dhaka BDT 70` vs `Outside Dhaka BDT 130`), and **Optional Email Address**.
  * **No Stock Deduction on Checkout Submit:** When the visitor clicks `CONFIRM ORDER` on the website, the order is saved in the backend as **`Pending Verification`**, and **`stock_qty` is NOT deducted yet** (preventing unverified or accidental guest orders from locking up saree inventory).
  * *(Admin Warning Badge: If two different visitors place unverified orders for the last `1` piece of the same saree, the Admin Order screen highlights `"⚠️ 2 Pending Orders competing for 1 remaining stock"` so the operations person knows right away).*

* **2. Automatic Customer Previous History & Notes on Every Order Screen (Matched by Mobile or Email):**
  * Because the storefront uses Guest Checkout, the backend automatically links every order to a unified customer record by matching the visitor's **11-digit Mobile Number OR Email Address**.
  * Whenever an operations person opens an order in `/admin`, a **"Customer Previous History & Notes" Panel** is displayed automatically right beside the order:
    * **Customer Summary Badge:** Shows whether she is a **`New First-Time Buyer`** or **`Repeat Customer — 4 Previous Orders (3 Delivered, 1 Returned, 0 Cancelled) • Total Spent: BDT 18,500`**.
    * **Previous Orders Table:** Lists all past orders matched by that mobile number or email (`#ANG-XXXX`, Order Date, Sarees Ordered, Status, and who confirmed it).
    * **Past Notes, Complaints & Call History:** Immediately shows any previous notes, delivery preferences, or complaints logged under this customer's phone/email (with **Staff Name** + **Timestamp**), plus a visual alert badge if the customer has a prior complaint or parcel refusal note.

* **3. Individual Operations Staff Login & Phone Call Logging (`order_call_logs`):**
  * **Individual Staff Accounts in Stage 1:** Every operations team member logs into `/admin` with their **own unique username and password** (`users` table).
  * **Call Action & Note Logging:** The operations person calls the visitor's mobile number to verify the order and records a **Call Note** (e.g., *"Spoke with customer, confirmed Dhanmondi address"* or *"Did not pick up on 1st call, will retry"*).
  * **Automatic Staff & Timestamp Stamp:** Every call log entry automatically records:
    * **Who Called:** `called_by_user_id` (Operations Person's Name & Username — auto-captured from login session, cannot be faked).
    * **Call Time:** `called_at` (Exact Date & Timestamp, e.g., `28 Oct 2026, 10:32:15 PM`).
    * **Call Outcome & Note:** `call_status` (`Confirmed by Phone`, `No Answer / Busy`, `Requested Later Delivery`, `Cancelled by Customer`) + `operator_note`.

* **4. Operations Clicks `"Confirm Order"` → Stock Deducts + Confirmation Stamp:**
  * Once the customer confirms over the phone, the operations person clicks **`✓ Confirm Order`** in the backend.
  * **At That Exact Moment:**
    1. **Stock Is Deducted (`stock_qty - ordered_qty`):** Uses an atomic database lock (`SELECT ... FOR UPDATE`) to deduct the saree quantity from `products.stock_qty` (if stock became `0`, updates `in_stock = false` on the website immediately) and marks `is_stock_deducted = true`.
    2. **Confirmation Audit Stamp:** Permanently records on the order:
       * **Confirmed By:** `confirmed_by_user_id` (Operations Person's Name & Username).
       * **Confirmed At:** `confirmed_at` (Exact Date & Timestamp of confirmation).
       * **Confirmation Call Note:** Attached directly to the order timeline.
    3. *(Restock Safety Rule: If an already-confirmed order is later `Cancelled` or `Returned` after stock was deducted, cancelling/returning it in the backend automatically adds the quantity back to `stock_qty` and logs who cancelled it).*

* **5. Promo / Coupon Code Manager (`coupons`):**
  * Create percentage (`EID10` → `10% OFF`) or fixed BDT (`WELCOME200` → `BDT 200 OFF`) coupons with minimum order amount, start/expiry dates, and total usage limits.

### Module 1.6 — Instant Customer Lookup Search Bar & Complaint / Support Note System (`customers` & `customer_notes`)
Built into **Stage 1** so your operations team can immediately assist any buyer who calls your helpline:

* **1. Top Global Search Bar (Search by Mobile Number, Email, or Order ID `#ANG-XXXX`):**
  * Located permanently at the top of the `/admin` header.
  * When a buyer calls your helpline asking *"What is my order status?"* or has an issue, the operations person types the caller's **Mobile Number (`017XXXXXXXX`)** or **Email Address** (`name@email.com`).
  * In `< 1 second`, the backend opens the **Customer 360° Lookup Screen** matching that phone or email.

* **2. Exact Live Order Status & History View (For Incoming Support Calls):**
  * **Active / Current Orders Box (Pinned Top):** Shows the exact real-time status of the caller's current order (`Pending Verification` → `Confirmed by [Staff Name] at [Time]` → `Packed` → `Shipped via [Courier Name] + Consignment ID & Live Tracking Link` → `Delivered`), ordered sarees, delivery address, and total COD payable—so the operator can give the buyer 100% accurate information on the call.
  * **Complete Past Order History:** Lists every previous order placed using that mobile number or email (`Delivered`, `Returned`, `Exchanged`, `Cancelled`), along with all call logs from those orders.

* **3. Customer Notes, Complaints & Special Behavior Log (`customer_notes`):**
  * While speaking with the customer, the operations person can add a permanent note directly to the customer's profile (matched by phone/email):
    * **Note Type Tag:** `[⚠️ Complaint / Issue]` | `[🔄 Exchange / Return Request]` | `[📍 Delivery Preference]` | `[⭐ VIP / Good Buyer]` | `[🚫 Fake / Refused Parcel Warning]` | `[📝 General Note]`
    * **Note Text:** Detailed description of what the customer said or requested, or what action was taken.
    * **Automatic Staff & Time Stamp:** Automatically records **Who Wrote the Note (`created_by_user_id` — Staff Name & Username)** and **Exact Date & Time (`created_at`)**.
  * **Automatic Future Alert:** Whenever that same customer places a new order on the website in the future (using the same mobile number or email), all of her past notes and complaint tags automatically appear inside the new order's backend view before the operations person even calls her!

### Module 1.7 — Live Order Notification Engine & Customer Email Automation
* **3-Channel Instant Live Order Notification (Works on cPanel):**
  1. **Live Admin Dashboard Popup + Sound (`🔔`):** When an order is placed, any open Admin/ERP browser tab plays a notification chime, increments the topbar badge, and displays a toast banner with a 1-click link to the order.
  2. **Instant Telegram Bot Mobile Alert (`< 1 Second`):** Sends a formatted message directly to your phone's Telegram app with Order ID (`#ANG-1048`), Customer Name, Tap-to-Call Phone Link (`017XXXXXXXX`), Address, Saree photo/SKU, Total COD Payable, and a direct `[Open Order in Admin]` button.
  3. **Web Push Notification:** Native browser push notification for Android/Desktop.
* **Customer Email Automation (When Optional Email Is Provided):**
  * **Trigger 1 — Order Placed:** Immediately dispatches a branded HTML **Order Confirmation Receipt** (`#ANG-1048`, itemized sarees, delivery address, and COD amount to keep ready).
  * **Trigger 2 — Order Marked `Shipped`:** Automatically sends a **Your Saree Has Shipped!** email containing the courier name and live tracking button.

### Module 1.8 — Customer Reviews, Photo Moderation & Policy/Inquiry Manager
Directly powers `reviews_chat_and_social_sharing_plan.md` and `collection_and_utility_pages_plan.md`:
* **Verified Buyer Review System:**
  * When a guest submits the `"Write a Review"` modal on the PDP with their **Mobile Number or Order ID**, the backend automatically checks the `orders` table. If a matching order exists, the review is marked **`✓ Verified Buyer`**.
  * Uploaded customer drape photos (`4:5`) are sanitized and converted to `.webp`.
  * Admin can **Approve**, **Pin to Homepage ("Customer Drape Stories")**, or **Delete** spam reviews in 1 click.
* **Policy Pages & Contact Inbox:**
  * Rich-text editor in Admin for `/about`, `/shipping-policy`, `/cod-policy`, `/exchange-policy`, and `/saree-care-guide` (with dynamic shortcodes for Inside/Outside Dhaka delivery rates).
  * Inbox for `/contact` form inquiries with `Unread / Replied` status.

---

## 4. STAGE 2: Aangina Saree ERP System (Second Stage Expansion)

Once Stage 1 (Website & Storefront Backend) is live and running smoothly, we unlock **Stage 2** inside the exact same `/admin` panel—turning your website backend into a complete **Bangladesh Saree Business ERP**.

### ERP Module 2.1 — Weaver / Artisan & Supplier Management (`weavers` & `purchase_orders`)
* **Weaver / Mahajan Directory:**
  * Store profiles for your weavers and suppliers (e.g., *Narayanganj Jamdani Master Weavers, Tangail Tant Artisans, Mirpur Benarasi/Katan Looms, Rajshahi Silk Suppliers*) with phone, address, specialization, and payment terms.
* **Purchase Orders & Weaving Batch Tracker:**
  * Record incoming saree batches from weavers (`Purchase Order #PO-2026-01`).
  * Automatically increases product `stock_qty` when a batch is marked `Received` and updates each saree's **Unit Cost Price (`cost_price_bdt`)**.
* **Weaver Payment & Due Ledger:**
  * Track **Total Weaving Bill**, **Advance Given (Dadan)**, **Partial Payments (Cash/bKash/Bank)**, and **Remaining Balance Due** per weaver.

### ERP Module 2.2 — Smart Inventory, Stock Audit Ledger & SKU Barcode Printing
* **Complete Stock Movement Ledger (`stock_movements`):**
  * Every single stock change is logged with timestamp, staff user, and reason:
    * `+ Stock In (Purchase Batch)`
    * `− Website Order (#ANG-XXXX)`
    * `− Manual Order (Facebook / WhatsApp / Showroom)`
    * `+ Customer Return / Exchange Restock`
    * `− Damaged / QC Reject / Promotional Gift`
* **1-Click Printable Saree Tag & Barcode Generator:**
  * Select any batch of sarees in the ERP and print thermal or A4 **Saree Hang Tags / Stickers** containing:
    * Brand Logo (`Aangina`), Saree Title, SKU (`ANG-JM-104`), Barcode / QR Code, Fabric, and Price (`BDT 4,500`).

### ERP Module 2.3 — Omnichannel Order Desk / POS (Facebook, WhatsApp & Phone Orders)
Many Bangladeshi customers send a screenshot on **WhatsApp** or **Facebook Messenger** and say *"Please book this saree for me."*
* **Fast 30-Second Manual Order Screen:**
  * Staff selects `Order Source`: `Website` | `Facebook Page` | `WhatsApp` | `Instagram` | `Phone Call` | `Offline/Showroom`.
  * **Auto-Fill Returning Customer CRM:** Typing the customer's 11-digit mobile number automatically fills her Name, District, Area, and Detailed Address from past orders, and shows her lifetime order count (e.g., `★ Repeat Customer — 4 Delivered Orders, 0 Returns`).
  * **BD Courier Fraud / Return History Check:** Checks the mobile number's past delivery vs. return ratio so your team knows if a high-value COD order needs an extra confirmation call before dispatch.
  * Deducts stock from the exact same inventory so a saree sold on WhatsApp immediately shows as updated/sold-out on the website.

### ERP Module 2.4 — 1-Click Bangladesh Courier Integration & Invoice Printing
* **Native API Integration with Top BD Couriers:**
  * **Steadfast Courier API**
  * **Pathao Courier API**
  * **RedX Courier API**
* **1-Click & Bulk Dispatch Workflow:**
  * Filter orders by `Confirmed` → select orders → click **`Send to Steadfast / Pathao`**.
  * The ERP automatically sends Receiver Name, Phone, Address, District, COD Amount (`BDT 4,570`), and Order ID (`#ANG-1048`) to the courier API.
  * Saves the returned **Consignment ID & Tracking Link**, switches order status to `Shipped`, and triggers the customer's tracking email automatically.
  * **Live Courier Webhook / Status Sync:** Automatically updates order status in your ERP when the courier marks the parcel as `Delivered`, `Partial Delivered`, or `Returned`.
* **Branded Thermal & A4 Invoice / Packing Slip Printer:**
  * Prints clean COD invoices showing the Aangina header, `#ANG-1048` barcode, courier consignment ID, itemized sarees (`SKU + Rack/Fold location`), and the **"Check Parcel in Front of Delivery Rider"** notice.

### ERP Module 2.5 — COD Cash Reconciliation, Expense Tracker & Net Profit Accounting
* **Courier COD Reconciliation Ledger (`courier_settlements`):**
  * Solves one of the biggest headaches in BD e-commerce: tracking whether the courier has paid out every delivered order!
  * Shows:
    * ** Cash Pending with Courier:** Orders marked `Delivered` but not yet settled into your bank/bKash.
    * **Settled COD Batch:** Match courier payout sheets against order IDs, automatically deducting courier delivery fees (`BDT 70 / 130`) and COD charges (`1%`).
* **Business Expense Tracker (`expenses`):**
  * Record operational expenses by category: *Facebook/Instagram Ad Spend, Packaging Boxes & Poly, Model Photoshoot, Staff Salaries, Utilities/Rent, Courier Return Fees*.
* **Real-Time Owner Profit, Retention & Analytics Dashboard:**
  * **Gross Revenue** (Delivered Orders)
  * `−` **Cost of Sarees Sold (COGS)** (calculated automatically from each saree's `cost_price_bdt`)
  * `−` **Courier & Delivery Costs**
  * `−` **Operating & Marketing Expenses**
  * `=` **Net Profit (BDT) & Profit Margin (%)** — filterable by Today, This Week, This Month, Eid Season, or Custom Date Range, plus **Top Selling Saree Categories** (`Jamdani` vs `Muslin` vs `Katan`).
  * **Repeat Customer & Repeat Order Retention Analytics (Any Date Range or All-Time):**
    * **Repeat Order Qty & %:** Exact count and percentage of orders placed by returning buyers vs. first-time buyers (`orders.is_repeat_order = true`, `orders.customer_order_sequence >= 2`).
    * **Repeat Customer Number & %:** Exact count and percentage of unique customers who have ordered `2+` times (`customers.total_orders_count >= 2` or `customers.delivered_count >= 2`).
    * **Customer Loyalty Breakdown:** 1st-time buyers vs. 2nd-time vs. `3+` VIP buyers, Average Customer Lifetime Value (`lifetime_spent_bdt`), and average days between repeat purchases (`first_order_at` → `last_order_at`).

### ERP Module 2.6 — Staff Roles, Permissions & Activity Audit Log
* **Role-Based Access Control (RBAC):**
  1. **Owner / Super Admin:** Full access to everything including Weaving Cost Price, Supplier Ledger, Net Profit Reports, and Theme/System Settings.
  2. **Catalog & Inventory Manager:** Can add/edit sarees, upload photos, print barcodes, and manage stock, but cannot view net profit reports.
  3. **Order Moderator / Support Executive:** Can view/confirm orders, create Facebook/WhatsApp manual orders, book couriers, print invoices, and reply to customer inquiries (**Cost Prices and Profit Reports are completely hidden**).
* **Staff Activity Log:** Tracks who confirmed an order, who edited stock, or who applied a manual discount.

---

## 5. Master Database Schema Overview (Unified Stage 1 + Stage 2 Tables)

```mermaid
erDiagram
    CATEGORIES ||--o{ PRODUCTS : contains
    WEAVERS ||--o{ PRODUCTS : supplies
    WEAVERS ||--o{ PURCHASE_ORDERS : receives
    WEAVERS ||--o{ WEAVER_PAYMENTS : paid_via
    PRODUCTS ||--o{ PRODUCT_IMAGES : has
    PRODUCTS ||--o{ STOCK_MOVEMENTS : logs
    PRODUCTS ||--o{ REVIEWS : receives
    CUSTOMERS ||--o{ ORDERS : places
    CUSTOMERS ||--o{ CUSTOMER_NOTES : has_notes
    USERS ||--o{ CUSTOMER_NOTES : writes_note
    USERS ||--o{ ORDER_CALL_LOGS : logs_call
    USERS ||--o{ ORDERS : confirms_order
    ORDERS ||--o{ ORDER_CALL_LOGS : has_call_history
    ORDERS ||--|{ ORDER_ITEMS : includes
    PRODUCTS ||--o{ ORDER_ITEMS : ordered_in
    COUPONS ||--o{ ORDERS : discounts
    COURIER_SETTLEMENTS ||--o{ ORDERS : reconciles
```

### Core Database Tables List
| Table Name | Built In | Purpose |
| :--- | :--- | :--- |
| `store_settings` | **Stage 1** | Key-value & JSON store for the 12 `:root` CSS tokens, Header Mode (`MODE_A`/`MODE_B`), delivery rates (`70`/`130`), contact info, and homepage blocks. |
| `categories` | **Stage 1** | 2-level category hierarchy (`parent_department`, `slug`, `name`, `display_order`, `cover_image`, `default_care_instructions`). |
| `collections` | **Stage 1** | Curated collections (`new-arrivals`, `festive-edit`, `offers`, `best-sellers`) & pivot table `collection_product`. |
| `products` | **Stage 1** *(+ Stage 2 cols)* | Saree catalog (`sku`, `slug`, `title`, `price_bdt`, `old_price_bdt`, `cost_price_bdt` *[ERP]*, `weaver_id` *[ERP]*, `stock_qty`, `sales_count`, `specs` JSON + indexed filter columns `color_family`, `blouse_piece`, `work_type`). |
| `product_images` | **Stage 1** | Ordered `3:4` saree gallery images (`url_zoom`, `url_card`, `url_thumb`, `alt_text`, `sort_order`). |
| `customers` | **Stage 1 & 2** | Auto-indexed by 11-digit `phone` AND `email` (`name`, `phone`, `email`, `district`, `area`, `address`, `total_orders_count`, `delivered_count`, `returned_count`, `cancelled_count`, `lifetime_spent_bdt`, `first_order_at`, `last_order_at`). |
| `customer_notes` | **Stage 1** | Permanent customer notes & complaints (`customer_id`, `order_id` *[optional]*, `note_type` *[`complaint`, `exchange`, `delivery_pref`, `vip`, `warning`, `general`]*, `note_text`, `created_by_user_id` *[Staff ID]*, `created_at` *[Timestamp]*). |
| `orders` | **Stage 1** *(+ Stage 2 cols)* | Order records (`order_number` `#ANG-XXXX`, `customer_id`, `customer_order_sequence` *[1st, 2nd, 3rd... order]*, `is_repeat_order` *[boolean]*, `order_source` *[Website/FB/WA]*, `delivery_zone`, `subtotal_bdt`, `discount_bdt`, `delivery_charge_bdt`, `total_payable_bdt`, `total_cost_bdt` *[ERP]*, `status` *[`pending_verification` → `confirmed` → `shipped` → `delivered`]*, `is_stock_deducted` *[boolean]*, `confirmed_by_user_id` *[Staff ID]*, `confirmed_at` *[Timestamp]*, `courier_name` *[ERP]*, `courier_consignment_id` *[ERP]*, `courier_tracking_url`, `cod_settled` *[ERP]*). |
| `order_call_logs` | **Stage 1** | Phone verification call log (`order_id`, `called_by_user_id` *[Staff username/ID]*, `called_at` *[Exact Call Timestamp]*, `call_outcome` *[`confirmed`, `no_answer`, `busy`, `call_later`, `cancelled`]*, `operator_note` *[Call discussion note]*). |
| `order_items` | **Stage 1** | Line items (`order_id`, `product_id`, `sku_snapshot`, `title_snapshot`, `unit_price_bdt`, `unit_cost_bdt` *[ERP]*, `qty`, `line_total_bdt`). |
| `coupons` | **Stage 1** | Promo codes (`code`, `type`, `value`, `min_order_bdt`, `usage_limit`, `used_count`, `expires_at`, `is_active`). |
| `reviews` | **Stage 1** | Customer reviews (`product_id`, `order_id`, `reviewer_name`, `city`, `phone_private`, `rating`, `comment`, `photo_url`, `is_verified_buyer`, `is_approved`, `is_featured_home`). |
| `inquiries` | **Stage 1** | Contact form messages (`name`, `phone`, `email`, `message`, `status`). |
| `weavers` | **Stage 2 (ERP)** | Artisan/supplier profiles (`name`, `phone`, `location`, `specialty`, `total_billed_bdt`, `total_paid_bdt`, `balance_due_bdt`). |
| `purchase_orders` | **Stage 2 (ERP)** | Incoming saree stock batches & items (`po_number`, `weaver_id`, `total_cost_bdt`, `status`, `received_at`). |
| `stock_movements` | **Stage 2 (ERP)** | Full inventory audit log (`product_id`, `qty_change`, `type`, `reference_id`, `user_id`, `note`). |
| `courier_settlements`| **Stage 2 (ERP)** | COD payout reconciliation batches (`courier_name`, `settlement_date`, `total_collected_bdt`, `courier_fee_bdt`, `net_received_bdt`). |
| `expenses` | **Stage 2 (ERP)** | Business expense ledger (`category`, `title`, `amount_bdt`, `expense_date`, `payment_method`, `receipt_url`). |
| `users` & `activity_logs` | **Stage 1 & 2** | Individual Staff & Admin logins (`username`, `name`, `password`, `role` *[`owner`, `manager`, `operations`]*), tracking who called, who confirmed orders, and all backend actions. |

---

## 6. cPanel Hosting & Security Architecture

1. **Secure cPanel Directory Layout:**
   * All core Laravel application files, `.env` credentials, and ERP logic sit **outside** `public_html` (e.g., `/home/cpaneluser/aangina_core/`), while only the public assets and `index.php` entry point sit in `public_html`. This makes `.env` and backend source files 100% impossible to access from the web.
2. **cPanel Cron Job (1 Entry):**
   * A single standard cPanel Cron Job (`* * * * * php /home/user/aangina_core/artisan schedule:run`) handles background tasks: sending queued emails, syncing courier delivery statuses, and creating automated daily database backups.
3. **1-Click Backup Manager Inside Admin:**
   * Includes a button in `/admin` to download a full SQL backup of all products, orders, customer records, and ERP ledgers to your PC anytime.
4. **Seamless VPS Migration Ready:**
   * Whenever your daily order volume outgrows shared cPanel hosting, the entire Laravel + MySQL folder moves to any VPS (e.g., CloudPanel / Laravel Forge) in under 20 minutes with **zero code modifications**.

---

## 7. Step-by-Step Backend Implementation Order (When Phase B Starts)

### Stage 1 Build Sequence (Website Backend & Admin CMS)
1. **Step B1.1:** Initialize Laravel 11 + MySQL Migrations (including Stage 2 reserved ERP columns) + Seed initial `storeConfig`, `categoriesData`, and `sareesData` from Phase A.
2. **Step B1.2:** Connect Storefront Blade Views & Dynamic `:root` CSS Token Injection + Open Graph (`og:`) Meta Tags.
3. **Step B1.3:** Build Individual Staff/Admin Auth & **Module 1.1 – 1.4** (Theme Token Editor, Header Mode Switcher, Homepage Banner CMS, Category & Saree Product CRUD with Auto-WebP `3:4` Image Optimizer).
4. **Step B1.4:** Build **Module 1.5, 1.6 & 1.7** (Guest COD Checkout, Phone-Verified Stock Deduction, Call Log & Confirmation Stamp, Customer History & Phone/Email Global Lookup, Customer Complaint/Note Logger, Live Dashboard Sound + Telegram Bot Alert + Automated Customer Emails).
5. **Step B1.5:** Build **Module 1.8** (Customer Review & Photo Moderation + Policy Page Editor + Contact Inquiry Inbox).

### Stage 2 Build Sequence (Aangina Saree ERP System)
1. **Step B2.1:** Build **Omnichannel Manual Order Desk (POS)** for Facebook, WhatsApp & Phone orders + Returning Customer Auto-Fill & Courier Return-Ratio Check.
2. **Step B2.2:** Build **1-Click Bangladesh Courier API Integration** (Steadfast / Pathao / RedX) + Bulk Invoice & Packing Slip Printer.
3. **Step B2.3:** Build **Weaver / Supplier Directory, Purchase Order Batching & Payment Ledger**.
4. **Step B2.4:** Build **Stock Movement Audit Log & Printable Saree SKU / Barcode Tag Generator**.
5. **Step B2.5:** Build **COD Cash Reconciliation, Expense Tracker, Net Profit Dashboard & Staff Role Permissions**.

