# LotteryHub — Complete Implementation Roadmap

## Phase 1: Foundation & Authentication
**Goal:** Working Laravel project with auth, roles, and the complete database schema.

### 1.1 Project Scaffolding
- `composer create-project laravel/laravel:^12.0 lotteryhub`
- Configure `.env` for MySQL, shared hosting (DB cache, DB queue, DB session, mail)
- Install packages:
  - `composer require laravel/sanctum`
  - `composer require spatie/laravel-permission`
  - `composer require barryvdh/laravel-debugbar --dev`
  - `npm install react react-dom @inertiajs/react`
  - `npm install tailwindcss @tailwindcss/vite`
  - `npm install @shadcn/ui framer-motion lucide-react`
  - `npm install apexcharts react-apexcharts`
  - `npm install @tanstack/react-table`
  - `npm install react-hook-form @hookform/resolvers zod`
- Vite config for React + Inertia + Tailwind
- Set up `resources/js/` with React entry point, TypeScript config

### 1.2 Complete Database Schema (ALL Migrations)
Write every migration so the schema is final from day one:

**Users & Auth:**
- `create_users_table` — id (uuid), name, email, phone, nic, password, avatar, is_active, email_verified_at, phone_verified_at, last_login_at, remember_token, timestamps, soft_deletes
- `create_password_reset_tokens_table`
- `create_personal_access_tokens_table` (Sanctum)

**Roles & Permissions (Spatie):**
- `create_permission_tables` (permissions, roles, model_has_roles, model_has_permissions, role_has_permissions)

**Geography:**
- `create_districts_table` — id, name (unique), code, is_active, timestamps
- `create_towns_table` — id, district_id (FK), name, is_active, timestamps

**Packages:**
- `create_packages_table` — id, name, code (starter/bronze/silver/gold/enterprise), description, max_customers, max_ticket_books, max_coins, price, is_active, timestamps

**Owner Management:**
- `create_owner_subscriptions_table` — id, owner_id (FK users), package_id (FK), start_date, end_date, status (active/expired/cancelled), timestamps
- `create_owner_settings_table` — id, owner_id (FK), commission_rate, auto_approve, booking_prefix, whatsapp_number, timestamps

**Draws:**
- `create_draws_table` — id, draw_date (date, unique), lottery_name, winning_number (nullable, varchar 10), status (pending/completed/cancelled), source (manual/api/import), drawn_at, timestamps

**Ticket Books & Numbers:**
- `create_ticket_books_table` — id, owner_id (FK), draw_id (FK), name, number_start (0), number_end (99), is_active, timestamps, soft_deletes
- `create_number_slots_table` — id, ticket_book_id (FK), draw_id (FK), owner_id (FK), number (tinyint 0-99), status (available/reserved/booked/winner/paid/cancelled/expired), timestamps, unique(ticket_book_id, draw_id, number)

**Bookings:**
- `create_bookings_table` — id (uuid), booking_reference (unique), customer_id (FK users), owner_id (FK), ticket_book_id (FK), draw_id (FK), slot_id (FK number_slots), number_selected (tinyint), status (reserved/awaiting_payment/confirmed/cancelled/expired/winner/prize_paid), reserved_at, expires_at, confirmed_at, cancelled_at, coin_cost, coin_deducted (boolean), notes, timestamps, soft_deletes

**Payment Proofs:**
- `create_payment_proofs_table` — id, booking_id (FK), reference_number, bank_name, transfer_slip_path, status (pending/verified/rejected), verified_by (FK users), verified_at, notes, timestamps

**Coins & Wallets:**
- `create_wallets_table` — id, owner_id (FK, unique), balance (decimal 12,2, default 0), bonus_balance (decimal 12,2, default 0), total_earned (decimal 12,2), total_spent (decimal 12,2), timestamps
- `create_coin_transactions_table` — id, wallet_id (FK), owner_id (FK), type (purchase/bonus/adjustment/deduction/refund/expiry/prize), amount (decimal), balance_before, balance_after, description, reference_type (booking/package/prize), reference_id, expiry_date (nullable), timestamps
- `create_coin_packages_table` — id, name, coins, bonus_coins, price, is_active, timestamps

**Prize Payments:**
- `create_prize_payments_table` — id, booking_id (FK), owner_id (FK), customer_id (FK), draw_id (FK), prize_amount (decimal), coin_deducted (decimal), paid_at, notes, timestamps

**Notifications:**
- `create_notifications_table` — Laravel default notifications table
- `create_notification_logs_table` — id, notification_type, channel, recipient, subject, body, status, sent_at, error_message, timestamps

**Audit:**
- `create_audit_logs_table` — id, user_id (FK), action, model_type, model_id, old_values (json), new_values (json), ip_address, user_agent, timestamps

**Banks:**
- `create_banks_table` — id, name (unique), code, is_active, timestamps

**Sessions & Cache (for DB driver):**
- `create_sessions_table`
- `create_cache_table`
- `create_jobs_table`

### 1.3 Models (+ Relationships, Casts, Traits)
- `User` — role enum cast, morphMany notifications, belongsToMany roles (Spatie)
- `District` — hasMany towns
- `Town` — belongsTo district
- `Package` — hasMany ownerSubscriptions
- `OwnerSubscription` — belongsTo user(owner), belongsTo package
- `OwnerSetting` — belongsTo user(owner)
- `Draw` — hasMany numberSlots, hasMany bookings
- `TicketBook` — belongsTo owner, belongsTo draw, hasMany numberSlots, hasMany bookings
- `NumberSlot` — belongsTo ticketBook, belongsTo draw, belongsTo owner, hasOne booking
- `Booking` — belongsTo customer, owner, ticketBook, draw, numberSlot; hasOne paymentProof; hasMany prizePayments
- `PaymentProof` — belongsTo booking, belongsTo verifier (User)
- `Wallet` — belongsTo owner, hasMany coinTransactions
- `CoinTransaction` — belongsTo wallet, belongsTo owner
- `CoinPackage` — self-contained
- `PrizePayment` — belongsTo booking, owner, customer, draw
- `NotificationLog` — self-contained
- `AuditLog` — belongsTo user
- `Bank` — self-contained
- `Traits\TenantScoped` — adds owner_id global scope
- `Traits\Auditable` — auto-log create/update/delete
- `Traits\HasUuid` — uuid primary keys
- `Enums\UserRole` — SuperAdmin, Owner, Staff, Customer, SupportAgent
- `Enums\BookingStatus` — Reserved, AwaitingPayment, Confirmed, Cancelled, Expired, Winner, PrizePaid
- `Enums\NumberStatus` — Available, Reserved, Booked, Winner, Paid, Cancelled, Expired
- `Enums\PackageType` — Starter, Bronze, Silver, Gold, Enterprise
- `Enums\DrawStatus` — Pending, Completed, Cancelled
- `Enums\DrawSource` — Manual, Api, Import
- `Enums\CoinTransactionType` — Purchase, Bonus, Adjustment, Deduction, Refund, Expiry, Prize
- `Enums\NotificationChannel` — WhatsApp, SMS, Email, Push, InApp

### 1.4 Authentication (Sanctum + Inertia)
- Login/Register/ForgotPassword/ResetPassword/EmailVerification controllers
- Role-based redirect middleware
- Inertia shared data: auth user, notifications, permissions
- React pages with Zod + React Hook Form validation

### 1.5 RBAC Setup
- RoleAndPermissionSeeder with all roles and permissions
- Permission groups: owners, packages, customers, districts, towns, draws, bookings, coins, reports, settings, staff, notifications, banks
- CheckPermission middleware
- Policies per model

### 1.6 Multi-Tenancy Foundation
- TenantScope global scope
- TenantScoped trait
- Auto-scoped models
- Super Admin bypass method

### 1.7 Layout System (React + Inertia)
- GuestLayout, AdminLayout, OwnerLayout, CustomerLayout, StaffLayout
- Sidebar, TopNav, ThemeToggle, NotificationDropdown components
- Dark/light mode via useTheme hook

### 1.8 Super Admin Base Pages
- Dashboard stub, Owner CRUD, Package CRUD, District/Town CRUD, Customer search, Banks CRUD

### 1.9 Factories & Seeders
- All factories + DatabaseSeeder with demo data

### 1.10 Error Handling
- Custom exceptions (InsufficientCoinException, BookingExpiredException, NumberNotAvailableException)
- Inertia error pages (403, 404, 500)

### 1.11 Initial Tests
- Auth, RBAC, tenant isolation, enums, relationships

---

## Phase 2: Super Admin Core Management
**Goal:** All Super Admin management features fully functional.

| # | Task | Details |
|---|---|---|
| 2.1 | Owner CRUD | List, create, edit, suspend/activate, detail page |
| 2.2 | Owner Subscription System | Assign package, auto-expire, renewal, proration |
| 2.3 | Package CRUD | List, create, edit, limits configuration |
| 2.4 | District CRUD | CRUD with town count |
| 2.5 | Town CRUD | CRUD filtered by district |
| 2.6 | Customer Search | Mega search: NIC, mobile, name, booking#, QR |
| 2.7 | Coin Settings | Rate configuration, bonus percentages |
| 2.8 | Audit Log Viewer | Filterable log table |
| 2.9 | Bank CRUD | CRUD for banks dropdown |
| 2.10 | Draw Management | CRUD, result entry, auto slot generation |
| 2.11 | Admin Dashboard | Full ApexCharts dashboard |
| 2.12 | Super Admin Profile | Profile edit, password, preferences |

---

## Phase 3: Owner Portal
**Goal:** Owners can fully manage their lottery business.

| # | Task |
|---|---|
| 3.1 | Owner Dashboard with stat cards and charts |
| 3.2 | Ticket Book CRUD with auto slot generation |
| 3.3 | Number Grid View (10x10 color-coded) |
| 3.4 | Staff Management (invite, list, deactivate) |
| 3.5 | Customer List with booking history |
| 3.6 | Booking Approval Workflow (approve/reject with proof) |
| 3.7 | Wallet Dashboard (balance, history, purchase) |
| 3.8 | Prize Payment (mark paid, deduct coins) |
| 3.9 | Owner Settings (profile, prefix, auto-approve) |
| 3.10 | Package Status (usage vs limits, expiry, upgrade) |

---

## Phase 4: Customer Frontend
**Goal:** Customers can register, browse, and book numbers.

| # | Task |
|---|---|
| 4.1 | Customer Registration & Login |
| 4.2 | Landing Page with hero, CTA, how-it-works |
| 4.3 | District → Town → Owner selection wizard |
| 4.4 | Owner Profile Page with number grid |
| 4.5 | Interactive Number Grid (10x10, color-coded) |
| 4.6 | Reserve Number Flow with countdown |
| 4.7 | Upload Payment Proof (reference, bank, slip) |
| 4.8 | My Bookings Page with status filter |
| 4.9 | Booking Detail with QR code, timeline |
| 4.10 | Draw Results Page with winner check |
| 4.11 | Customer Profile & Settings |

---

## Phase 5: Booking Engine (Backend Core Logic)
**Goal:** All business logic for booking lifecycle, coins, and validation.

| # | Task |
|---|---|
| 5.1 | BookingService — reserve, confirm, cancel, expire, markWinner, payPrize |
| 5.2 | CoinService — getBalance, deduct, refund, addBonus, purchase, adjust, getHistory |
| 5.3 | DrawService — createDraw, setResult, calculateWinners |
| 5.4 | ReleaseExpiredReservations job (every minute) |
| 5.5 | AutoCalculateWinners job (daily after draw result) |
| 5.6 | ExpireOwnerSubscriptions job (daily) |
| 5.7 | Wallet auto-creation on owner registration |
| 5.8 | PackageService — canAddCustomer, canCreateTicketBook, getUsage |
| 5.9 | Form Requests with validation + authorization |
| 5.10 | Policies per model |

---

## Phase 6: Draws & Winners
**Goal:** Complete draw lifecycle and winner management.

| # | Task |
|---|---|
| 6.1 | Draw CRUD (Super Admin) |
| 6.2 | Draw Result Entry (manual + auto-import) |
| 6.3 | Winner Calculation (last 2 digits) |
| 6.4 | Winners List (admin, owner, public) |
| 6.5 | Prize Payment via Coin Deduction |
| 6.6 | Scheduler: Auto Daily Draw Creation |
| 6.7 | Scheduler: Auto Winner Calculation |
| 6.8 | Draw History Calendar View |

---

## Phase 7: Notifications
**Goal:** Multi-channel notification delivery.

| # | Task |
|---|---|
| 7.1 | NotificationService — unified dispatch |
| 7.2 | BookingReserved notification |
| 7.3 | BookingExpired notification |
| 7.4 | PaymentUploaded notification |
| 7.5 | PaymentConfirmed notification |
| 7.6 | BookingConfirmed notification |
| 7.7 | WinnerAnnounced notification |
| 7.8 | PrizePaid notification |
| 7.9 | PackageExpiring notification |
| 7.10 | LowCoins notification |
| 7.11 | WhatsApp Channel integration |
| 7.12 | SMS Channel integration |
| 7.13 | Email Channel (Markdown mailables) |
| 7.14 | In-App Notifications (database channel) |
| 7.15 | Notification Preferences UI |
| 7.16 | Notification Logs |
| 7.17 | Events & Listeners |

---

## Phase 8: Reports & Exports
**Goal:** Comprehensive reporting with export.

| # | Task |
|---|---|
| 8.1 | Sales Report |
| 8.2 | Customer Report |
| 8.3 | Owner Report |
| 8.4 | Bookings Report |
| 8.5 | Reserved Numbers Report |
| 8.6 | Winners Report |
| 8.7 | Profit Report |
| 8.8 | Coin Usage Report |
| 8.9 | Package Sales Report |
| 8.10 | District/Town Reports |
| 8.11 | Wallet Report |
| 8.12 | Audit Log Export |
| 8.13 | ExportService (PDF, Excel, CSV) |
| 8.14 | Report Controllers |

---

## Phase 9: REST API v1
**Goal:** Complete API for mobile apps.

| # | Task |
|---|---|
| 9.1 | API Authentication (Sanctum tokens) |
| 9.2 | API Resources |
| 9.3 | Customer API Endpoints |
| 9.4 | Owner API Endpoints |
| 9.5 | Staff API Endpoints |
| 9.6 | Super Admin API Endpoints |
| 9.7 | API Error Handling |
| 9.8 | Swagger Documentation |
| 9.9 | API Versioning |
| 9.10 | API Tests |

---

## Phase 10: Admin UI Polish & PWA
**Goal:** Professional, animated, polished UI.

| # | Task |
|---|---|
| 10.1 | Glassmorphism Design System |
| 10.2 | Framer Motion Animations |
| 10.3 | ApexCharts Integration |
| 10.4 | TanStack Table Enhancement |
| 10.5 | Mega Search (Ctrl+K) |
| 10.6 | Notification Center |
| 10.7 | Quick Actions (FAB) |
| 10.8 | Dark/Light Mode |
| 10.9 | PWA Support |
| 10.10 | Responsive Design |
| 10.11 | Keyboard Shortcuts |
| 10.12 | Loading States & Skeletons |

---

## Phase 11: Printing System
**Goal:** Thermal and A4 printing.

| # | Task |
|---|---|
| 11.1 | 58mm Receipt Template |
| 11.2 | 80mm Receipt Template |
| 11.3 | A4 Report Template |
| 11.4 | QR Code on Receipts |
| 11.5 | Barcode on Receipts |
| 11.6 | Print Controller |
| 11.7 | Print Button in UI |

---

## Phase 12: Testing
**Goal:** Comprehensive test coverage.

| # | Task |
|---|---|
| 12.1 | PHPUnit Configuration |
| 12.2 | Auth Tests |
| 12.3 | Booking Lifecycle Tests |
| 12.4 | Coin Transaction Tests |
| 12.5 | Winner Calculation Tests |
| 12.6 | Package Limit Tests |
| 12.7 | Multi-Tenancy Isolation Tests |
| 12.8 | API Tests |
| 12.9 | Scheduler Tests |
| 12.10 | Permission Tests |

---

## Phase 13: Flutter Mobile Apps
**Goal:** Android + iOS apps.

### Customer App
| # | Task |
|---|---|
| 13.1.1 | Project setup (Flutter, folder structure, Riverpod, Dio) |
| 13.1.2 | Auth screens: login, register, forgot password, biometric |
| 13.1.3 | Home screen: district search, featured owners, countdown |
| 13.1.4 | District → Town → Owner selection (stepper) |
| 13.1.5 | Number grid (10x10) with color-coded status |
| 13.1.6 | Reserve flow → booking reference → countdown |
| 13.1.7 | Upload payment proof (image picker, form) |
| 13.1.8 | My bookings list with status tabs |
| 13.1.9 | Booking detail with QR code |
| 13.1.10 | Draw results page |
| 13.1.11 | Profile & settings, notification preferences |
| 13.1.12 | In-app notifications (Firebase FCM) |
| 13.1.13 | Material Design 3 + Cupertino adaptive |
| 13.1.14 | Dark mode |
| 13.1.15 | QR code scanner |
| 13.1.16 | Push notification setup |

### Owner App
| # | Task |
|---|---|
| 13.2.1 | Auth + biometric |
| 13.2.2 | Dashboard: coins, pending, stats, charts |
| 13.2.3 | Bookings list with swipe-to-approve/reject |
| 13.2.4 | Booking detail with payment proof |
| 13.2.5 | Number grid view |
| 13.2.6 | Wallet: balance, history, purchase |
| 13.2.7 | Staff management (list view) |
| 13.2.8 | Prize payment flow |
| 13.2.9 | Reports (simplified) |
| 13.2.10 | Profile & settings |
| 13.2.11 | Push notifications |
| 13.2.12 | Dark mode, Material 3 / Cupertino |

### Staff App
| # | Task |
|---|---|
| 13.3.1 | Auth + biometric |
| 13.3.2 | Dashboard (limited) |
| 13.3.3 | Bookings list → confirm/reject |
| 13.3.4 | Customer search |
| 13.3.5 | QR code scanner → lookup → confirm |
| 13.3.6 | Profile, dark mode |

---

## Phase 14: Documentation & Deployment
**Goal:** Complete deployment-ready project.

| # | Task |
|---|---|
| 14.1 | Installation Guide (docs/installation.md) |
| 14.2 | Database ER Diagram (docs/er-diagram.md) |
| 14.3 | API Documentation (Swagger UI) |
| 14.4 | User Manual (docs/user-manual.md) |
| 14.5 | Deployment Scripts (deploy/ folder) |
| 14.6 | Scheduler Setup (cron configuration) |
| 14.7 | Queue Setup for Shared Hosting |
| 14.8 | Backup Strategy |
| 14.9 | README.md |
| 14.10 | Docker Support (optional) |
