# 🏗️ Kitchen Staff Login System Architecture

## System Overview

```
┌─────────────────────────────────────────────────────────────┐
│                  KITCHEN STAFF LOGIN SYSTEM                 │
│                  (Using Existing Chef Table)                │
└─────────────────────────────────────────────────────────────┘

                          ┌──────────┐
                          │  Browser │
                          └──────────┘
                               │
                    ┌──────────┴──────────┐
                    │                     │
            ┌───────▼────────┐   ┌───────▼────────┐
            │ kitchen/        │   │ admin/         │
            │ login.php       │   │ kitchen_       │
            │ (Login Page)    │   │ staff.php      │
            └───────┬────────┘   │ (Management)   │
                    │            └───────┬────────┘
                    │                    │
        ┌───────────▼──────────────────────▼──────────┐
        │      Backend API Layer                       │
        ├──────────────────────────────────────────────┤
        │                                              │
        │  kitchen_signin.php                          │
        │  ├─ Validate credentials                     │
        │  ├─ Hash password verification               │
        │  └─ Create session                           │
        │                                              │
        │  kitchen_session_check.php                   │
        │  ├─ Verify session exists                    │
        │  ├─ Check timeout (30 min)                   │
        │  └─ Return staff info                        │
        │                                              │
        │  kitchen_logout.php                          │
        │  └─ Destroy session                          │
        │                                              │
        │  admin_kitchen_staff_api.php                 │
        │  ├─ Create staff (hash password)             │
        │  ├─ Update staff details                     │
        │  ├─ Delete staff                             │
        │  └─ Get staff info                           │
        │                                              │
        └──────────────────┬───────────────────────────┘
                           │
        ┌──────────────────▼───────────────────────────┐
        │          MySQL Database                      │
        ├──────────────────────────────────────────────┤
        │                                              │
        │  chefs table (Extended)                      │
        │  ├─ id                                       │
        │  ├─ name                                     │
        │  ├─ email (UNIQUE) ← NEW                     │
        │  ├─ password (HASHED) ← NEW                  │
        │  ├─ employee_id (UNIQUE) ← NEW               │
        │  ├─ position                                 │
        │  ├─ role (Chef/Manager/Staff) ← NEW          │
        │  ├─ status (active/inactive) ← NEW           │
        │  ├─ description                              │
        │  ├─ image_path                               │
        │  ├─ display_order                            │
        │  ├─ created_at                               │
        │  └─ updated_at                               │
        │                                              │
        │  chef_skills table (Existing)                │
        │  chef_social_media table (Existing)          │
        │                                              │
        └──────────────────────────────────────────────┘
```

---

## Authentication Flow

### 1. Login Process
```
USER VISITS: /kitchen/login.php
             ↓
         [Login Form]
             ↓
    User enters: Email OR Employee ID
             ↓
    User enters: Password
             ↓
         [Submit]
             ↓
  POST → kitchen_signin.php
             ↓
  Query: SELECT * FROM chefs 
         WHERE (email=? OR employee_id=?) 
         AND status='active'
             ↓
    Found? YES → Verify password_verify()
           │
           YES → Create Session
                 ├─ $_SESSION['kitchen_staff_id']
                 ├─ $_SESSION['kitchen_staff_name']
                 ├─ $_SESSION['kitchen_staff_role']
                 ├─ $_SESSION['kitchen_staff_login_time']
                 └─ $_SESSION['kitchen_staff_remember_me']
                 ↓
              REDIRECT → /kitchen/dashboard.php
                 ↓
           NO  → Invalid password
                 ↓
              ERROR MESSAGE
             
    Found? NO → Invalid credentials
            ↓
         ERROR MESSAGE
```

### 2. Dashboard Protection
```
USER VISITS: /kitchen/dashboard.php
             ↓
    SESSION CHECK
             ↓
  $_SESSION['kitchen_staff_id'] exists?
             ↓
         YES → Check URL authentication
              ├─ Load kitchen/dashboard.php
              ├─ Display pending orders
              ├─ Show kitchen features
              └─ Display logout button
             
         NO  → REDIRECT → /kitchen/login.php
```

### 3. Session Validation
```
EVERY PAGE LOAD:
    ↓
kitchen_session_check.php
    ↓
session_start()
    ↓
Check: $_SESSION['kitchen_staff_id'] exists?
    ↓
    YES → Check timeout
         ├─ Current time - login time > 30 min?
         │  ├─ YES (no remember_me) → DESTROY SESSION
         │  │                         RETURN 401
         │  │
         │  └─ NO → CONTINUE
         │          UPDATE last activity
         └─
    
    NO  → RETURN 401 (Unauthorized)
```

### 4. Logout Process
```
USER CLICKS: Logout Button
             ↓
        [Confirm Dialog]
             ↓
         [Yes]
             ↓
POST → kitchen_logout.php
             ↓
unset($_SESSION['kitchen_staff_*'])
             ↓
session_destroy()
             ↓
REDIRECT → /kitchen/login.php
```

---

## Admin Management Flow

### Add New Staff
```
ADMIN VISITS: /admin/kitchen_staff.php
             ↓
    Required: Admin logged in
             ↓
         [Click: Add Kitchen Staff]
             ↓
         [Modal Opens]
             ↓
    ADMIN FILLS:
    ├─ Name
    ├─ Email (UNIQUE CHECK)
    ├─ Employee ID (UNIQUE CHECK)
    ├─ Position
    ├─ Role
    ├─ Password (WILL BE HASHED)
    └─ Status
             ↓
         [Save]
             ↓
POST → admin_kitchen_staff_api.php
             ↓
    action='create'
             ↓
    Validate all fields exist
             ↓
    Check: Email or Employee ID already exists?
         ├─ YES → ERROR (duplicate)
         └─ NO  → Continue
             ↓
    Hash password: password_hash($pass, BCCRYPт)
             ↓
    INSERT INTO chefs(...)
    VALUES(?, ?, ?, ...) 
             ↓
    RESPONSE: Success + New Staff ID
             ↓
    [Refresh Page]
```

### Edit Staff
```
Same flow as above but:
- UPDATE instead of INSERT
- Password is optional for edit
- If password provided, hash and update
- Otherwise keep existing password
```

### Delete Staff
```
[Click Delete] → [Confirm] → DELETE FROM chefs WHERE id=?
```

---

## Session Management

### Session Timeout Logic
```
Authentication required for:
✅ /kitchen/dashboard.php (main dashboard)
✅ /kitchen/login.php validates session

Session lifetime:
├─ Default: 30 minutes idle
└─ With Remember Me: 30 days (or until browser close)

Timeout check happens on:
✅ Page load
✅ Every API call
✅ Dashboard access

Session data stored:
├─ kitchen_staff_id
├─ kitchen_staff_name
├─ kitchen_staff_email
├─ kitchen_staff_role
├─ kitchen_staff_position
├─ kitchen_staff_image
├─ kitchen_staff_login_time
└─ kitchen_staff_remember_me (optional)
```

---

## Security Implementation

### 1. Password Security
```
User Input: "MyPassword123"
    ↓
password_hash($password, PASSWORD_BCRYPT)
    ↓
Stored: $2y$10$...encrypted...hash
    ↓
On Login:
    ↓
password_verify("MyPassword123", $hash)
    ↓
Returns: true/false
```

### 2. SQL Injection Prevention
```
VULNERABLE:
❌ "SELECT * FROM chefs WHERE email='" . $_POST['email'] . "'"

SECURED:
✅ Prepared Statement:
   $stmt = $conn->prepare("SELECT * FROM chefs WHERE email=?")
   $stmt->bind_param('s', $email)
   $stmt->execute()
```

### 3. XSS Prevention
```
User Input: "<script>alert('hack')</script>"
    ↓
htmlspecialchars($input)
    ↓
Stored/Displayed: "&lt;script&gt;alert('hack')&lt;/script&gt;"
    ↓
Browser: Shows as text, not executed
```

### 4. Session Hijacking Prevention
```
✅ Session regeneration on login
✅ Secure session cookie settings
✅ HttpOnly flag (prevents JS access)
✅ Secure flag (HTTPS only in production)
✅ Timeout after inactivity
✅ Session destroyed on logout
```

---

## Integration Points

### Existing Systems Used:
```
✅ Chef Table
   ├─ Extended with: email, password, employee_id, role, status
   ├─ All existing data preserved
   ├─ Gallery profiles still work
   └─ Admin chef management still works

✅ Chef Skills Table
   └─ Linked to chef.id (no changes)

✅ Chef Social Media Table
   └─ Linked to chef.id (no changes)
```

### New Systems Created:
```
✅ Kitchen staff login (kitchen/login.php)
✅ Backend authentication (kitchen_signin.php)
✅ Session management (kitchen_session_check.php)
✅ Dashboard protection (dashboard.php)
✅ Admin management panel (admin/kitchen_staff.php)
✅ Admin API (admin_kitchen_staff_api.php)
```

---

## File Relationships

```
kitchen/
├── login.php ──────────┐
│                       ├──→ kitchen_signin.php
│                       │
└── dashboard.php ──────┼──→ kitchen_session_check.php
                        │
                        ├──→ kitchen_logout.php
                        │
                        └──→ kitchen_get_recipe.php (existing)
                           
admin/
└── kitchen_staff.php ──→ admin_kitchen_staff_api.php

backend/
├── add_auth_to_chefs.php ─────────┐
│                                  ├──→ ALTER TABLE chefs
│                                  
├── kitchen_signin.php ────────────┼──→ SELECT FROM chefs
│                                  │   → password_verify()
│                                  │   → session_start()
│
├── kitchen_session_check.php ─────┼──→ Session validation
│                                  │   → Timeout check
│
├── kitchen_logout.php ────────────┼──→ session_destroy()
│
├── admin_kitchen_staff_api.php ───┼──→ CRUD operations
│                                  │   → password_hash()
│
└── setup_kitchen_staff.php ───────┴──→ Test data creation
```

---

## Performance Considerations

### Database Queries:
```
Login:     2-3 queries (SELECT + session setup)
Session:   1 query (SELECT count or exists)
Add Staff: 2 queries (CHECK duplicate + INSERT)
Update:    1-2 queries (UPDATE + verify)
Delete:    1 query (DELETE)
```

### Indexes for Performance:
```
recommended:
- Index on email (UNIQUE)
- Index on employee_id (UNIQUE)
- Index on status
```

### Session Storage:
```
Default: File-based (/tmp on Linux, temp on Windows)
Can upgrade to: Database, Redis, Memcached for scale
```

---

## Scalability & Future Enhancements

### Possible Enhancements:
```
Phase 2:
├─ Two-factor authentication (2FA)
├─ Login audit logs
├─ Password strength requirements
├─ Email verification on account creation
└─ Session activity dashboard

Phase 3:
├─ More detailed role-based permissions
├─ Kitchen shift management
├─ Performance metrics per chef
├─ Specialization tracking
└─ Schedule management
```

---

## Backup & Recovery

### Important Tables to Backup:
```
✅ chefs (stores all kitchen staff + credentials)
✅ chef_skills
✅ chef_social_media
```

### Password Recovery:
```
Lost Password:
   ↓
Admin must:
   1. Go to admin/kitchen_staff.php
   2. Find the staff member
   3. Click Edit
   4. Enter new password
   5. Save
   ↓
Staff can now login with new password
```

---

## Monitoring & Logging

### Recommended Additions:
```
✅ Login success/failure logs
✅ Session timeout logs
✅ Password change logs
✅ Staff status changes
✅ Admin actions log
```

### Example Log Entry:
```
[2026-02-24 14:30:45] SUCCESS - User: ramesh@granny.local IP: 192.168.1.100
[2026-02-24 14:32:10] ACTIVITY - Dashboard viewed
[2026-02-24 15:00:45] TIMEOUT - Session ended (idle 30 min)
[2026-02-24 15:01:00] LOGOUT - User logged out successfully
```

---

**Architecture Document Version**: 1.0  
**Date**: February 24, 2026  
**System**: Granny Restaurant Kitchen Staff LoginSystem  
**Status**: Production Ready ✅
