# Department-Workflow Assignment Setup Guide

This document explains the new department-workflow assignment feature and how to set it up.

## Overview

The system now allows you to assign leave workflows to specific departments. When an employee from a department applies for leave, the system automatically uses the workflow assigned to that department.

## SQL Scripts to Run

Run these SQL scripts in order:

1. **department_table.sql** (if not already run)
   - Creates the `departments` table
   - Populates with 10 default departments

2. **department_workflow_assignment_table.sql**
   - Creates the `department_workflow_assignments` table
   - Links departments to workflows

3. **employee_department_link.sql**
   - Adds `department_id` column to `employee` table
   - Links employees to departments

4. **leave_application_workflow_update.sql**
   - Adds `workflow_id` column to `leave_application` table
   - Tracks which workflow was used for each application

## How It Works

1. **Assign Workflow to Department:**
   - Go to HRManager → Leave Workflows
   - Click "Assign" button next to a workflow
   - Select departments to assign the workflow to

2. **Employee Leave Application:**
   - When an employee applies for leave, the system:
     - Checks the employee's department
     - Finds the workflow assigned to that department
     - Uses the workflow steps to determine approval chain
     - The first workflow step position becomes the supervisor
     - Subsequent steps follow in order

3. **Fallback:**
   - If no workflow is assigned to a department, the system uses the old approval logic (supervisor → HR)

## Assigning Employees to Departments

After running the SQL scripts, you need to assign employees to departments:

```sql
UPDATE employee SET department_id = 1 WHERE emp_no = 'EMP001';
```

Or update through the HR interface if available.

## Files Created/Modified

### New Files:
- `HRManager/department_table.sql` - Department table creation
- `HRManager/department_workflow_assignment_table.sql` - Assignment table
- `HRManager/employee_department_link.sql` - Employee-department link
- `HRManager/leave_application_workflow_update.sql` - Leave application update
- `HRManager/assign-workflow-department.php` - Assignment page
- `HRManager/departments.php` - Department management page

### Modified Files:
- `HRManager/leave-workflows.php` - Added "Assign" button
- `staff/leave.php` - Modified to use department workflows
- `inc/functions.php` - Added workflow functions
- `includes/functions.php` - Added workflow functions for staff area

## Usage

1. Create departments (if not already done)
2. Create leave workflows with steps
3. Assign workflows to departments
4. Assign employees to departments
5. Employees apply for leave - system automatically uses their department's workflow

