# OTP Email Verification System - Architecture

## System Architecture Diagram

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                        CLEANING SERVICE WEBSITE                              │
└─────────────────────────────────────────────────────────────────────────────┘

                                 ┌──────────────┐
                                 │   Frontend   │
                                 │   (HTML/CSS) │
                                 └──────────────┘
                                        │
                    ┌───────────────────┼───────────────────┐
                    │                   │                   │
           ┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
           │  register.php   │ │   login.php      │ │forgot_password.php
           │  (2 Steps OTP)  │ │  (Standard Auth) │ │  (OTP Sending)
           └─────────────────┘ └──────────────────┘ └──────────────────┘
                    │                   │                   │
                    └───────────────────┼───────────────────┘
                                        │
                        ┌───────────────▼────────────────┐
                        │   OTP Handler Class            │
                        │   (otp_handler.php)            │
                        │                                │
                        │ Methods:                       │
                        │ ├─ generateOTP()               │
                        │ ├─ sendOTPEmail()              │
                        │ ├─ storeOTP()                  │
                        │ ├─ verifyOTP()                 │
                        │ └─ resendOTP()                 │
                        └───────────────┬────────────────┘
                                        │
                    ┌───────────────────┼───────────────────┐
                    │                   │                   │
           ┌────────▼────────┐ ┌────────▼────────┐ ┌────────▼────────┐
           │   PHPMailer     │ │   MySQL/MariaDB │ │  Sessions       │
           │   (Email SMTP)  │ │   (Database)    │ │  (PHP Sessions) │
           └────────┬────────┘ └────────┬────────┘ └────────┬────────┘
                    │                   │                   │
           ┌────────▼────────┐          │                   │
           │  Gmail SMTP     │          │                   │
           │                 │          │                   │
           │ Host: smtp.     │          │                   │
           │ gmail.com       │          │                   │
           │ Port: 587       │          │                   │
           └────────┬────────┘          │                   │
                    │                   │                   │
           ┌────────▼────────┐ ┌────────▼────────┐          │
           │   Email Sent    │ │  Tables:        │          │
           │                 │ │  - users        │          │
           │ ├─ HTML        │ │  - otp_verifi   │          │
           │ ├─ OTP Code    │ │    cations      │          │
           │ ├─ Branding    │ │                 │          │
           │ └─ Timer       │ │  (Auto-created) │          │
           └─────────────────┘ └─────────────────┘          │
                                                            │
                                                  ┌─────────▼──────────┐
                                                  │ User Sessions:     │
                                                  │ ├─ user_id         │
                                                  │ ├─ user_type       │
                                                  │ ├─ reg_email (OTP) │
                                                  │ └─ reset_email(OTP)│
                                                  └────────────────────┘
```

---

## Data Flow - Registration with OTP

```
User Visits register.php
        │
        ▼
   Fill Form
   (Name, Email, Phone, Password)
        │
        ▼
   Submit (POST)
        │
        ▼
   Validation ───────► Error? ──► Show Error Message
        │                              │
        │◄─────────────────────────────┘
        │ (User fixes and resubmits)
        │
        ▼ (Validation passed)
   Check Email Exists in DB
        │
        ▼
   Email Not Exists? ───► Store session data
        │                  (fullname, email, phone, password)
        │
        ▼
   Generate OTP (6 digits)
        │
        ▼
   Send Email via Gmail SMTP
        │
        ▼
   Store OTP in DB
   (expires_at = NOW() + 10 minutes)
        │
        ▼
   Set Session: registration_step = 2
        │
        ▼
   Redirect to Step 2
   (OTP Entry Page)
        │
        ▼
   User Receives Email
   with OTP Code
        │
        ▼
   User Enters OTP Code
        │
        ▼
   Verify OTP ───────► Invalid/Expired? ──► Show Error
        │                                        │
        │◄───────────────────────────────────────┘
        │ (User can resend OTP)
        │
        ▼ (OTP Valid)
   Create User Account
   (Hash password, insert into users table)
        │
        ▼
   Mark OTP as Verified
        │
        ▼
   Clear Session Data
        │
        ▼
   Show Success Message
        │
        ▼
   Redirect to Login
        │
        ▼
   ✅ Registration Complete
```

---

## Data Flow - Password Reset with OTP

```
User Clicks "Forgot Password?"
        │
        ▼
   forgot_password.php
        │
        ▼
   Enter Email Address
        │
        ▼
   Submit Email
        │
        ▼
   Validate Email
        │
        ▼
   Check Email Exists in DB
        │
        ▼
   Email Not Found? ───► Show Error
        │
        │◄──────────────────────────┘
        │ (User enters different email)
        │
        ▼ (Email Found)
   Generate OTP (6 digits)
        │
        ▼
   Send Reset Email via SMTP
        │
        ▼
   Store OTP in DB
   (type = 'password_reset')
   (expires_at = NOW() + 10 minutes)
        │
        ▼
   Set Session: reset_email, reset_step = 1
        │
        ▼
   Redirect to reset_password.php
        │
        ▼
   User Receives Email
   with OTP Code
        │
        ▼
   reset_password.php (Step 1)
   User Enters OTP Code
        │
        ▼
   Verify OTP ───────► Invalid/Expired? ──► Show Error
        │                                        │
        │◄───────────────────────────────────────┘
        │ (User can resend OTP)
        │
        ▼ (OTP Valid)
   Set Session: reset_step = 2
        │
        ▼
   reset_password.php (Step 2)
   Show New Password Form
        │
        ▼
   User Enters New Password
        │
        ▼
   Validate Password
   (min 6 chars, confirmation match)
        │
        ▼
   Hash New Password
        │
        ▼
   Update users table
   WHERE email = ?
        │
        ▼
   Clear Session Data
        │
        ▼
   Show Success Message
        │
        ▼
   Redirect to Login
        │
        ▼
   ✅ Password Reset Complete
```

---

## Database Schema Relationship

```
┌─────────────────────────────┐
│       users                 │
├─────────────────────────────┤
│ id (Primary Key)            │
│ name                        │
│ email (Unique)              │◄──────┐
│ phone                       │       │
│ password (hashed)           │       │
│ user_type                   │       │ FOREIGN KEY
│ status                      │       │
│ created_at                  │       │
└─────────────────────────────┘       │
                                      │
                    ┌─────────────────┴────────────────┐
                    │                                  │
        ┌───────────▼──────────────────────────────────┐
        │   otp_verifications                          │
        ├────────────────────────────────────────────┤
        │ id (Primary Key)                             │
        │ email (Foreign Key to users.email)           │
        │ otp (6-digit code)                           │
        │ type (registration / password_reset)         │
        │ created_at (timestamp)                       │
        │ expires_at (timestamp)                       │
        │ verified (boolean - used flag)               │
        └────────────────────────────────────────────┘
```

---

## Security Flow

```
┌─────────────────────────────────────────────────────────────┐
│                  Input Security Layers                      │
└─────────────────────────────────────────────────────────────┘

1. HTML Input Validation
   └─ Email format check
   └─ Required fields
   └─ Password strength (min 6)

2. PHP Validation
   └─ filter_var(email)
   └─ trim() whitespace
   └─ strlen() length check
   └─ Duplicate email check

3. SQL Security
   └─ Prepared Statements
   └─ Parameterized Queries
   └─ Bind Parameters
   └─ Prevents SQL Injection ✅

4. Password Security
   └─ Bcrypt hashing
   └─ PASSWORD_DEFAULT
   └─ Never stored plain ✅

5. OTP Security
   └─ Random generation
   └─ One-time use enforcement
   └─ 10-minute expiry
   └─ Database verification ✅

6. Session Security
   └─ PHP sessions
   └─ Session validation
   └─ Proper cleanup ✅
```

---

## Email Flow Diagram

```
Application
    │
    ▼
OTPHandler::sendOTPEmail()
    │
    ▼
PHPMailer Configuration
│
├─ setFrom(email, name)
├─ addAddress(recipient)
├─ isHTML(true)
├─ setSubject()
└─ setBody(HTML template)
    │
    ▼
SMTP Connection
│
├─ Host: smtp.gmail.com
├─ Port: 587
├─ Auth: enabled
├─ TLS: enabled
└─ Username/Password
    │
    ▼
Gmail SMTP Server
    │
    ▼
Internet
    │
    ▼
User's Email Provider
    │
    ▼
User's Inbox ✅
    │
    ▼
User Opens Email
    │
    ▼
User Sees OTP Code
    │
    ▼
User Enters Code
```

---

## Timer/Countdown Flow

```
Page Load
    │
    ▼
JavaScript Countdown Starts
    │
    ├─ Initial: timeLeft = 600 seconds (10 minutes)
    │
    ├─ Update Every 1000ms (1 second)
    │ │
    │ ├─ Calculate: minutes = timeLeft / 60
    │ ├─ Calculate: seconds = timeLeft % 60
    │ ├─ Format: "MM:SS"
    │ ├─ Display in HTML
    │ └─ Decrement timeLeft--
    │
    └─ When timeLeft = 0
        │
        ├─ Stop timer
        ├─ Show expired message
        └─ Allow "Resend OTP"
```

---

## Error Handling Flow

```
Try Operation (OTP send, verify, etc.)
    │
    ├─► Success ──► Continue to next step
    │
    └─► Error ──┬─► Log to error_log()
               │
               ├─► Set error variable
               │
               ├─► Display user-friendly message
               │
               ├─► Allow user to retry
               │
               └─► User can resend OTP
```

---

## Session Lifecycle

```
registration.php (Step 1)
    │
    ├─ $_SESSION['reg_fullname'] = value
    ├─ $_SESSION['reg_email'] = value
    ├─ $_SESSION['reg_phone'] = value
    ├─ $_SESSION['reg_password'] = value
    └─ $_SESSION['registration_step'] = 2
        │
        ▼
registration.php (Step 2)
    │
    ├─ Read: $_SESSION['reg_email']
    ├─ OTP verification happens
    └─ If success:
        │
        ├─ unset($_SESSION['registration_step'])
        ├─ unset($_SESSION['reg_fullname'])
        ├─ unset($_SESSION['reg_email'])
        ├─ unset($_SESSION['reg_phone'])
        ├─ unset($_SESSION['reg_password'])
        │
        └─ Redirect to login
            │
            ▼
        Session cleaned ✅
```

---

This architecture ensures:
- ✅ **Security**: Multiple validation layers
- ✅ **Scalability**: Modular design
- ✅ **Maintainability**: Clear separation of concerns
- ✅ **Reliability**: Error handling at every step
- ✅ **User Experience**: Clear feedback and options
