# Purchase Manager Module - Documentation

## Overview
The Purchase Manager Module is a comprehensive procurement management system designed for restaurants and food service businesses. It enables efficient supplier management, purchase order creation, requisition handling, and cost comparison across multiple suppliers.

## Features

### 1. **Authentication & Security**
- Secure login system for purchase managers
- Session-based authentication with timeout (30 minutes)
- Password hashing using bcrypt
- Remember me functionality

### 2. **Supplier Database**
- Add and manage supplier information
- Store contact details, addresses, and phone numbers
- Supplier rating system
- Search and filter suppliers

### 3. **Purchase Requisitions**
- Create purchase requisitions for items needed
- Track requisition status (Pending, Approved, Rejected)
- Timestamp tracking for all requisitions
- Notes and approval workflow

### 4. **Purchase Order Creation**
- Create purchase orders from suppliers
- Track order status (Draft, Confirmed, Shipped, Delivered)
- Automatic cost calculation
- Link orders to suppliers

### 5. **Cost Comparison**
- Compare prices across multiple suppliers
- Identify the best and worst prices
- Historical price tracking
- Cost analysis for procurement decisions

## Installation & Setup

### Step 1: Initialize Database
1. Visit: `https://yoursite.com/backend/setup_purchase_manager_db.php`
2. This will create all necessary database tables:
   - `purchase_managers` - User accounts
   - `suppliers` - Supplier information
   - `purchase_requisitions` - Requisition tracking
   - `purchase_orders` - Order management
   - `cost_comparisons` - Price comparisons

### Step 2: Create Purchase Manager Accounts
1. Log in to Admin Panel (`/admin/login.php`)
2. Navigate to "Manage Purchase Managers" section
3. Click "Add New Purchase Manager"
4. Fill in details:
   - Full Name
   - Email Address
   - Password
   - Phone Number
   - Status (Active/Inactive)
5. Click "Create Purchase Manager"

### Step 3: Purchase Manager Login
1. Visit Purchase Manager Login: `/purchase_manager/login.php`
2. Enter email and password
3. Optionally check "Remember me" to save email
4. Access the dashboard

## Module Structure

### Files Overview

#### Frontend Files (in `/purchase_manager/`)
- **login.php** - Login form with modern UI
- **auth_check.php** - Session validation for protected pages
- **dashboard.php** - Main dashboard with statistics
- **suppliers.php** - Supplier management interface
- **requisitions.php** - Purchase requisitions interface
- **purchase_orders.php** - Purchase orders interface
- **cost_comparison.php** - Cost comparison interface

#### Backend Files (in `/backend/`)
- **purchase_manager_signin.php** - Login API
- **purchase_manager_session_check.php** - Session validation API
- **purchase_manager_logout.php** - Logout API
- **purchase_manager_api.php** - Dashboard statistics
- **suppliers_api.php** - Supplier CRUD operations
- **requisitions_api.php** - Requisition operations
- **purchase_orders_api.php** - Purchase order operations
- **cost_comparison_api.php** - Cost comparison operations
- **setup_purchase_manager_db.php** - Database initialization

#### Admin Interface
- **admin/purchase_managers.php** - Manage purchase manager accounts

## API Documentation

### Authentication Endpoints

#### Login
**POST** `/backend/purchase_manager_signin.php`
```json
{
  "email": "user@example.com",
  "password": "password123"
}
```
Response:
```json
{
  "success": true,
  "message": "Login successful",
  "name": "John Doe",
  "email": "user@example.com"
}
```

#### Session Check
**GET** `/backend/purchase_manager_session_check.php`
Response:
```json
{
  "valid": true,
  "purchase_manager_id": 1,
  "purchase_manager_name": "John Doe",
  "purchase_manager_email": "user@example.com"
}
```

#### Logout
**GET/POST** `/backend/purchase_manager_logout.php`
Response:
```json
{
  "success": true,
  "message": "Logged out successfully"
}
```

### Supplier Management

#### Get All Suppliers
**GET** `/backend/suppliers_api.php?action=get_all`
Response:
```json
{
  "success": true,
  "suppliers": [
    {
      "id": 1,
      "name": "ABC Supplier",
      "contact_person": "John",
      "email": "john@abc.com",
      "phone": "123-456-7890",
      "address": "123 Main St",
      "rating": 4.5
    }
  ]
}
```

#### Create Supplier
**POST** `/backend/suppliers_api.php`
```json
{
  "action": "create",
  "name": "ABC Supplier",
  "contact_person": "John Doe",
  "email": "john@suppliers.com",
  "phone": "123-456-7890",
  "address": "123 Main St, City",
  "rating": 4.5
}
```

#### Update Supplier
**POST** `/backend/suppliers_api.php`
```json
{
  "action": "update",
  "id": 1,
  "name": "ABC Supplier",
  "contact_person": "Jane Doe",
  "email": "jane@suppliers.com",
  "phone": "098-765-4321",
  "address": "456 Oak Ave, City",
  "rating": 4.8
}
```

#### Delete Supplier
**POST** `/backend/suppliers_api.php`
```json
{
  "action": "delete",
  "id": 1
}
```

### Purchase Requisitions

#### Get All Requisitions
**GET** `/backend/requisitions_api.php?action=get_all`
Response:
```json
{
  "success": true,
  "requisitions": [
    {
      "id": 1,
      "item_description": "Tomatoes - Fresh",
      "quantity": 50,
      "unit": "kg",
      "status": "pending",
      "created_at": "2026-03-10 10:30:00"
    }
  ]
}
```

#### Create Requisition
**POST** `/backend/requisitions_api.php`
```json
{
  "action": "create",
  "item_description": "Tomatoes - Fresh",
  "quantity": 50,
  "unit": "kg"
}
```

### Purchase Orders

#### Get All Orders
**GET** `/backend/purchase_orders_api.php?action=get_all`

#### Create Purchase Order
**POST** `/backend/purchase_orders_api.php`
```json
{
  "action": "create",
  "supplier_id": 1,
  "item_name": "Chicken Breast",
  "quantity": 100,
  "unit_price": 5.50
}
```

### Cost Comparison

#### Get All Comparisons
**GET** `/backend/cost_comparison_api.php?action=get_all`

#### Get Comparisons for Specific Item
**GET** `/backend/cost_comparison_api.php?action=get_item_comparisons&item=Tomatoes`
Response:
```json
{
  "success": true,
  "item": "Tomatoes",
  "comparisons": [
    {
      "supplier_name": "ABC Supplier",
      "price": 4.50,
      "quantity": 50
    },
    {
      "supplier_name": "XYZ Supplier",
      "price": 5.50,
      "quantity": 50
    }
  ],
  "best_price": 4.50,
  "worst_price": 5.50
}
```

#### Create Cost Comparison
**POST** `/backend/cost_comparison_api.php`
```json
{
  "action": "create",
  "item_name": "Tomatoes",
  "supplier_id": 1,
  "price": 4.50
}
```

## Database Schema

### purchase_managers Table
```sql
id (Primary Key)
name (VARCHAR 100)
email (VARCHAR 100, UNIQUE)
password (VARCHAR 255, hashed)
phone (VARCHAR 20)
status (ENUM: active, inactive)
created_at (TIMESTAMP)
last_login (TIMESTAMP)
```

### suppliers Table
```sql
id (Primary Key)
purchase_manager_id (Foreign Key)
name (VARCHAR 100)
contact_person (VARCHAR 100)
email (VARCHAR 100)
phone (VARCHAR 20)
address (TEXT)
rating (DECIMAL 3,2)
created_at (TIMESTAMP)
```

### purchase_requisitions Table
```sql
id (Primary Key)
purchase_manager_id (Foreign Key)
item_description (VARCHAR 255)
quantity (INT)
unit (VARCHAR 50)
status (ENUM: pending, approved, rejected)
created_at (TIMESTAMP)
approval_date (TIMESTAMP)
notes (TEXT)
```

### purchase_orders Table
```sql
id (Primary Key)
purchase_manager_id (Foreign Key)
supplier_id (Foreign Key)
item_name (VARCHAR 255)
quantity (INT)
unit_price (DECIMAL 10,2)
total_cost (DECIMAL 12,2)
status (ENUM: draft, confirmed, shipped, delivered)
created_at (TIMESTAMP)
delivery_date (TIMESTAMP)
notes (TEXT)
```

### cost_comparisons Table
```sql
id (Primary Key)
purchase_manager_id (Foreign Key)
item_name (VARCHAR 255)
supplier_id (Foreign Key)
price (DECIMAL 10,2)
quantity (INT)
unit (VARCHAR 50)
created_at (TIMESTAMP)
```

## Admin Management

### Access Purchase Manager Admin Panel
1. Log in to Admin Dashboard (`/admin/login.php`)
2. Navigate to sidebar menu
3. Look for "Purchase Managers" option
4. View all purchase manager accounts
5. Add new purchase managers as needed

### Add New Purchase Manager (Admin)
1. Click "Add New Purchase Manager" button
2. Fill in required fields:
   - Full Name
   - Email Address
   - Password
   - Phone Number (optional)
   - Status (Active/Inactive)
3. Submit form
4. New account is immediately available for login

## Features & Workflow Examples

### Example 1: Creating a Supplier
1. Login as Purchase Manager
2. Go to "Suppliers" section
3. Click "Add New Supplier"
4. Fill in supplier details
5. Save to database
6. Use for purchase orders

### Example 2: Creating a Purchase Order
1. Go to "Purchase Orders" section
2. Click "Create New Order"
3. Select supplier from dropdown
4. Enter item name and quantity
5. App calculates total cost automatically
6. Submit and track order status

### Example 3: Cost Comparison Analysis
1. Go to "Cost Comparison" section
2. Click "Create New Comparison"
3. Enter item name
4. Add price quotes from different suppliers
5. System identifies best and worst prices
6. Use data for procurement decisions

## Security Features

✓ **Password Security**
- Bcrypt hashing for all passwords
- Strong password requirements
- Secure session tokens

✓ **Session Management**
- 30-minute automatic session timeout
- Session validation on every page
- Automatic logout on timeout

✓ **Database Protection**
- Prepared statements to prevent SQL injection
- Foreign key constraints
- Data validation on all inputs

✓ **Access Control**
- Role-based access (Purchase Manager only)
- Admin-only management interface
- User authentication required

## Troubleshooting

### Issue: "Database connection failed"
- Check database credentials in `/backend/config.php`
- Ensure MySQL/MariaDB is running
- Verify database name is correct

### Issue: "Session expired"
- Session timeout is set to 30 minutes
- Refresh page to re-validate session
- Log in again if needed

### Issue: "Email already exists"
- The email is already registered as a purchase manager
- Use a different email address
- Contact admin to recover existing account

### Issue: Tables not created
- Run database setup: `/backend/setup_purchase_manager_db.php`
- Check file permissions
- Verify database user has CREATE TABLE privilege

## Support & Maintenance

### Regular Maintenance Tasks
- Backup database regularly
- Review purchase manager account activity
- Archive old purchase orders monthly
- Update supplier ratings

### Best Practices
- Keep passwords secure and unique
- Review cost comparisons regularly
- Archive completed purchase orders
- Monitor account activity via last login timestamp

## Future Enhancement Ideas
- Mobile app for purchase managers
- Email notifications for order status updates
- Integration with accounting system
- Advanced reporting and analytics
- Automated purchase order generation by quantity thresholds
- Supplier performance scoring
- Budget tracking and alerts
- Invoice matching with purchase orders

---

**Version**: 1.0
**Last Updated**: March 10, 2026
**Developed for**: Granny Restaurant Management System
