<?php
/**
 * Enterprise HRM ERP System - Change Employee Status
 * Quick action to change employee status (especially to inactive)
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();
requirePermission('EMPLOYEE_EDIT');

$siteId = getCurrentSiteId();
$employeeId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$newStatus = sanitize($_GET['status'] ?? 'inactive');

if ($employeeId <= 0) {
    redirect(BASE_URL . '/modules/employee/list.php', 'Invalid employee ID.', 'error');
}

// Validate status
$allowedStatuses = ['active', 'inactive', 'terminated', 'resigned'];
if (!in_array($newStatus, $allowedStatuses)) {
    redirect(BASE_URL . '/modules/employee/list.php', 'Invalid status.', 'error');
}

try {
    $db = getDB();
    
    // Get employee data
    $stmt = $db->prepare("SELECT * FROM employees WHERE employee_id = ? AND site_id = ?");
    $stmt->execute([$employeeId, $siteId]);
    $employee = $stmt->fetch();
    
    if (!$employee) {
        redirect(BASE_URL . '/modules/employee/list.php', 'Employee not found.', 'error');
    }
    
    // Update status
    $stmt = $db->prepare("UPDATE employees SET employment_status = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP WHERE employee_id = ? AND site_id = ?");
    $result = $stmt->execute([$newStatus, getCurrentUserId(), $employeeId, $siteId]);
    
    if ($result && $stmt->rowCount() > 0) {
        // Log audit
        try {
            $oldData = $employee;
            $newData = $employee;
            $newData['employment_status'] = $newStatus;
            logAudit('UPDATE', 'employees', $employeeId, $oldData, $newData);
        } catch (Exception $auditError) {
            error_log("Audit log error (non-critical): " . $auditError->getMessage());
        }
        
        $statusLabels = [
            'active' => 'Active',
            'inactive' => 'Inactive',
            'terminated' => 'Terminated',
            'resigned' => 'Resigned'
        ];
        
        redirect(BASE_URL . '/modules/employee/list.php', 'Employee status changed to ' . $statusLabels[$newStatus] . ' successfully.', 'success');
    } else {
        redirect(BASE_URL . '/modules/employee/list.php', 'Failed to update employee status.', 'error');
    }
    
} catch (Exception $e) {
    error_log("Error changing employee status: " . $e->getMessage());
    redirect(BASE_URL . '/modules/employee/list.php', 'An error occurred while changing employee status: ' . htmlspecialchars($e->getMessage()), 'error');
}

