# HR Management System - Implementation Guide

## Quick Start Guide

### Step 1: Apply Database Migration

Run the SQL migration script to create all necessary tables:

```bash
mysql -u root -p your_database_name < database/migrations/hrm_extensions.sql
```

Or import via PhpMyAdmin:
1. Open PhpMyAdmin
2. Select your database
3. Go to "Import" tab
4. Choose `database/migrations/hrm_extensions.sql`
5. Click "Go"

**Tables Created:**
- ✅ `tbl_salary_templates` - Salary template master data
- ✅ `tbl_employee_salary_templates` - Employee-template assignments
- ✅ `tbl_shifts` - Shift definitions with timings
- ✅ `tbl_employee_shifts` - Employee shift assignments
- ✅ `tbl_attendance` - Daily attendance records
- ✅ `tbl_attendance_summary` - Monthly attendance aggregation
- ✅ `tbl_payroll` - Monthly payroll records
- ✅ `tbl_payroll_adjustments` - Bonus, deductions, corrections

---

## Phase 1: Salary Template Management (Week 1)

### Files to Create:
1. **Frontend Pages**
   - `salary-template-add.php` - Add/Edit salary template form
   - `salary-template-list.php` - List all salary templates with DataTable

2. **API Endpoints**
   - `api/salary_template/create.php` - Create new template
   - `api/salary_template/read.php` - List templates with pagination
   - `api/salary_template/update.php` - Update template
   - `api/salary_template/delete.php` - Delete template

### Form Fields (salary-template-add.php):
```
Template Name (required)
Description (optional)

ALLOWANCES SECTION:
- Basic Salary
- HRA
- DA
- Medical Allowance
- Conveyance
- Other Allowances

DEDUCTIONS SECTION:
- PF Deduction
- Insurance Deduction
- Tax Deduction
- Other Deductions

Status (Active/Inactive)
```

### Data Validation:
- Template name must be unique
- All numeric fields must be >= 0
- Basic salary is required
- Template calculations:
  - Gross = Basic + HRA + DA + Allowances
  - Deductions = PF + Insurance + Tax + Other
  - Net = Gross - Deductions

---

## Phase 2: Employee-Template Assignment (Week 1-2)

### Files to Create:
1. **Frontend Pages**
   - `employee-salary-assign.php` - Assign template to employee

2. **API Endpoints**
   - `api/employee_salary/assign.php` - Assign template
   - `api/employee_salary/read.php` - Get employee's current template
   - `api/employee_salary/history.php` - Template change history

### Features:
- Search employee by name/ID
- Display current salary template if assigned
- Effective date selection for template change
- View template change history
- Bulk template assignment option

---

## Phase 3: Shift Management (Week 2)

### Files to Create:
1. **Frontend Pages**
   - `shift-add.php` - Add/Edit shift timings
   - `shift-list.php` - List all shifts
   - `employee-shift-assign.php` - Assign shift to employee

2. **API Endpoints**
   - `api/shift/create.php` - Create shift
   - `api/shift/read.php` - List shifts
   - `api/shift/update.php` - Update shift
   - `api/shift/delete.php` - Delete shift
   - `api/employee_shift/assign.php` - Assign shift to employee

### Form Fields (shift-add.php):
```
Shift Name (e.g., "Morning Shift") (required)
Start Time (required)
End Time (required)
Duration (calculated)
Break Minutes
Shift Allowance (optional)
Status (Active/Inactive)
```

### Sample Shifts (Pre-loaded):
- Morning: 6:00 AM - 2:00 PM (0 allowance)
- Evening: 2:00 PM - 10:00 PM (₹100 allowance)
- Night: 10:00 PM - 6:00 AM (₹200 allowance)
- Flexible: 9:00 AM - 5:00 PM (0 allowance)

---

## Phase 4: Attendance Management (Week 3)

### Files to Create:
1. **Frontend Pages**
   - `attendance-add.php` - Daily attendance marking
   - `attendance-list.php` - Attendance grid view
   - `attendance-bulk-upload.php` - CSV bulk upload
   - `attendance-report.php` - Monthly summary reports

2. **API Endpoints**
   - `api/attendance/create.php` - Mark attendance
   - `api/attendance/read.php` - Get attendance records
   - `api/attendance/update.php` - Update attendance
   - `api/attendance/bulk_upload.php` - CSV bulk import
   - `api/attendance_summary/calculate.php` - Calculate monthly summary

### Form Fields (attendance-add.php):
```
Employee (Dropdown/Select2)
Date (Date picker)
Status (Dropdown: Present, Absent, Leave, Half-day, Weekend, Holiday)
Shift (Optional)
Check-in Time (Optional)
Check-out Time (Optional)
Notes (Optional textarea)
```

### Features:
- Mark single or multiple employees' attendance
- Filter by employee, date range, branch, status
- Monthly attendance summary auto-calculation
- Import attendance from CSV
- Edit/Correct previous attendance records

### CSV Format for Bulk Upload:
```
employee_id,attendance_date,status,shift_id,notes
1,2026-02-16,present,1,
2,2026-02-16,absent,1,Sick Leave
3,2026-02-16,half_day,2,Doctor Appointment
```

---

## Phase 5: Payroll Generation (Week 4)

### Files to Create:
1. **Frontend Pages**
   - `payroll-generate.php` - Generate monthly payroll
   - `payroll-view.php` - View payroll details
   - `payroll-approve.php` - Approve payroll
   - `payslip-print.php` - Payslip PDF generation
   - `payroll-report.php` - Payroll analysis & reports

2. **API Endpoints**
   - `api/payroll/generate.php` - Auto-generate payroll for month
   - `api/payroll/read.php` - Get payroll records
   - `api/payroll/update.php` - Update payroll amounts
   - `api/payroll/approve.php` - Approve payroll
   - `api/payroll/pdf.php` - Generate payslip PDF
   - `api/payroll_adjustments/create.php` - Add bonus/deduction

### Payroll Generation Logic:

```php
function generatePayroll($employee_id, $salary_month) {
    // 1. Get employee's active salary template
    $template = getActiveSalaryTemplate($employee_id, $salary_month);

    // 2. Get employee's shift for the month
    $shift = getEmployeeShift($employee_id, $salary_month);

    // 3. Get monthly attendance summary
    $attendance = getAttendanceSummary($employee_id, $salary_month);

    // 4. Calculate working days in month
    $working_days = getWorkingDaysInMonth($salary_month);

    // 5. Calculate payroll
    $per_day_salary = $template['basic_salary'] / $working_days;
    $attendance_salary = $per_day_salary * $attendance['present_days'];
    $shift_allowance = $shift['shift_allowance'] * $attendance['present_days'];

    $gross_salary = $template['basic_salary'] +
                    $template['hra'] +
                    $template['da'] +
                    $template['medical_allowance'] +
                    $template['conveyance'] +
                    $template['other_allowances'];

    $total_deductions = $template['pf_deduction'] +
                       $template['insurance_deduction'] +
                       $template['tax_deduction'] +
                       $template['other_deductions'];

    $net_salary = $gross_salary - $total_deductions + $shift_allowance;

    // 6. Insert into tbl_payroll
    insertPayroll($employee_id, $salary_month, [
        'salary_template_id' => $template['id'],
        'working_days' => $working_days,
        'attendance_days' => $attendance['present_days'],
        'leave_days' => $attendance['leave_days'],
        'half_days' => $attendance['half_days'],
        'per_day_salary' => $per_day_salary,
        'gross_salary' => $gross_salary,
        'shift_allowance' => $shift_allowance,
        'total_deductions' => $total_deductions,
        'net_salary' => $net_salary,
        'status' => 'draft'
    ]);
}
```

### Payroll View (payroll-view.php):
```
Employee: [Name]
Month: [Month-Year]

EARNINGS:
- Basic Salary: ₹[amount]
- HRA: ₹[amount]
- DA: ₹[amount]
- Allowances: ₹[amount]
- Shift Allowance: ₹[amount]
GROSS: ₹[amount]

DEDUCTIONS:
- PF: ₹[amount]
- Insurance: ₹[amount]
- Tax: ₹[amount]
- Other: ₹[amount]
TOTAL DEDUCTIONS: ₹[amount]

NET SALARY: ₹[amount]

Status: Draft / Approved / Paid
[Approve Button] [Adjust] [Print PDF]
```

### Payroll Adjustment Flow:
- Add bonus (incentive, performance)
- Add deduction (advance, damage)
- Add correction (manual adjustment)
- Each adjustment recalculates net salary

---

## Implementation Checklist

### Database Setup
- [ ] Run migration script
- [ ] Verify all tables created
- [ ] Check sample data in shifts
- [ ] Check sample salary templates

### Phase 1 - Salary Templates
- [ ] Create `salary-template-add.php`
- [ ] Create `salary-template-list.php`
- [ ] Implement CRUD APIs
- [ ] Test template creation
- [ ] Test template calculations
- [ ] Test edit/delete functionality

### Phase 2 - Template Assignment
- [ ] Create `employee-salary-assign.php`
- [ ] Implement assignment API
- [ ] Link to employee profile
- [ ] Test assignment functionality
- [ ] View assignment history

### Phase 3 - Shifts
- [ ] Create shift management UI
- [ ] Create employee shift assignment
- [ ] Implement shift CRUD APIs
- [ ] Test shift assignment
- [ ] Test shift change history

### Phase 4 - Attendance
- [ ] Create attendance marking interface
- [ ] Create attendance list view
- [ ] Implement attendance CRUD APIs
- [ ] Create bulk upload functionality
- [ ] Implement auto-summary calculation
- [ ] Test all filters and reports
- [ ] Test bulk CSV upload

### Phase 5 - Payroll
- [ ] Create payroll generation page
- [ ] Implement auto-calculation logic
- [ ] Create payroll approval workflow
- [ ] Create payslip PDF generation
- [ ] Implement payroll adjustment system
- [ ] Create payroll analysis reports
- [ ] Test end-to-end payroll process

---

## Security Considerations

### Critical Security Issues to Address:

1. **Password Encryption** (Current Issue: Plain text)
   ```php
   // Change from:
   $stmt->bindValue(':password', $_POST['password']);

   // To:
   $stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
   ```

2. **Payroll Access Control**
   ```php
   // Only HR Managers and Admins can:
   - Generate payroll
   - Approve payroll
   - View employee salaries
   - Make adjustments
   ```

3. **Audit Logging**
   - Log all payroll operations
   - Track who created, approved, paid
   - Maintain change history

4. **Data Protection**
   - Salary data should be encrypted in transit
   - Payroll reports should have access restrictions
   - Payslips should only be visible to employee and HR

---

## Testing Scenarios

### Scenario 1: New Employee Onboarding
1. Create employee record
2. Assign salary template (Jr. Level)
3. Assign shift (Morning Shift)
4. Mark attendance for first month
5. Generate payroll

### Scenario 2: Salary Review
1. Update salary template amount
2. Reassign template to employee
3. Generate payroll for next month
4. Verify new salary in payroll

### Scenario 3: Shift Change
1. Change employee's shift
2. Mark attendance with new shift
3. Verify shift allowance in payroll

### Scenario 4: Leave & Absence
1. Mark employee as "Leave" for 2 days
2. Mark as "Absent" for 1 day
3. Calculate monthly summary
4. Generate payroll with reduced salary

### Scenario 5: Payroll Adjustment
1. Generate payroll (Draft status)
2. Add bonus (+₹5000)
3. Add deduction (-₹1000)
4. Verify net salary recalculation
5. Approve payroll

---

## API Response Examples

### Create Salary Template
```json
POST /api/salary_template/create.php
{
  "status": "success",
  "message": "Salary template created successfully",
  "id": 5
}
```

### Assign Template to Employee
```json
POST /api/employee_salary/assign.php
{
  "status": "success",
  "message": "Template assigned to employee successfully"
}
```

### Mark Attendance
```json
POST /api/attendance/create.php
{
  "status": "success",
  "message": "Attendance marked successfully",
  "id": 1234
}
```

### Generate Payroll
```json
POST /api/payroll/generate.php
{
  "status": "success",
  "message": "Payroll generated for 25 employees",
  "count": 25
}
```

### Get Payroll Details
```json
GET /api/payroll/read.php?employee_id=1&salary_month=2026-02-01
{
  "status": "success",
  "data": {
    "id": 1,
    "employee_id": 1,
    "salary_month": "2026-02-01",
    "working_days": 26,
    "attendance_days": 24,
    "leave_days": 1,
    "half_days": 1,
    "gross_salary": 50000,
    "total_deductions": 5500,
    "net_salary": 44500,
    "status": "draft"
  }
}
```

---

## Useful SQL Queries for Testing

### Attendance Summary for a Month
```sql
SELECT
    e.id, e.name,
    COUNT(CASE WHEN status='present' THEN 1 END) as present,
    COUNT(CASE WHEN status='absent' THEN 1 END) as absent,
    COUNT(CASE WHEN status='leave' THEN 1 END) as leave,
    COUNT(CASE WHEN status='half_day' THEN 1 END) as half_day
FROM tbl_attendance a
JOIN tbl_employees e ON a.employee_id = e.id
WHERE MONTH(a.attendance_date) = 2
  AND YEAR(a.attendance_date) = 2026
GROUP BY e.id, e.name;
```

### Payroll Status Report
```sql
SELECT
    status, COUNT(*) as count,
    SUM(net_salary) as total_payroll
FROM tbl_payroll
WHERE salary_month = '2026-02-01'
GROUP BY status;
```

### Employee Salary Details
```sql
SELECT
    e.name, e.salary,
    st.template_name,
    st.basic_salary, st.hra, st.da,
    (st.basic_salary + st.hra + st.da + st.medical_allowance + st.conveyance) as gross
FROM tbl_employees e
LEFT JOIN tbl_employee_salary_templates est ON e.id = est.employee_id AND est.status='active'
LEFT JOIN tbl_salary_templates st ON est.salary_template_id = st.id
WHERE e.status = 'active';
```

---

## Support & Debugging

### Common Issues & Solutions:

**Issue 1: Payroll calculates incorrect amount**
- Check if salary template is assigned to employee
- Verify attendance is marked for the month
- Check shift assignment and allowance

**Issue 2: Attendance summary doesn't update**
- Ensure attendance dates are correct
- Run summary calculation manually
- Check for duplicate attendance records

**Issue 3: Template assignment not reflecting in payroll**
- Verify assignment date <= payroll month
- Check template status is 'active'
- Ensure no conflicting assignments

---

**Document Version:** 1.0
**Created:** 2026-02-16
**Last Updated:** 2026-02-16
**Status:** Ready for Implementation
