<?php
/**
 * Enterprise HRM ERP System - Delete Employee
 */

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

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

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

// Get employee data for audit log
try {
    $db = getDB();
    
    // For Super Admin, allow deletion from any site
    // For others, check site_id
    if (isSuperAdmin()) {
        $stmt = $db->prepare("SELECT * FROM employees WHERE employee_id = ?");
        $stmt->execute([$employeeId]);
    } else {
        $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');
    }
    
    // Additional permission check for HR Admin - can only delete employees they created
    if (isHRAdmin() && !isSuperAdmin()) {
        if ($employee['created_by'] != getCurrentUserId()) {
            redirect(BASE_URL . '/modules/employee/list.php', 'You can only delete employees you have created.', 'error');
        }
    }
    
    // Check if employee has related records in various tables
    // Prevent deletion if there are related records
    $relatedRecords = [];
    
    // Helper function to safely check table existence and count records
    $checkTable = function($tableName, $columnName = 'employee_id') use ($db, $employeeId, &$relatedRecords) {
        try {
            // Check if table exists
            $checkStmt = $db->query("SHOW TABLES LIKE '{$tableName}'");
            if ($checkStmt->rowCount() > 0) {
                $stmt = $db->prepare("SELECT COUNT(*) FROM {$tableName} WHERE {$columnName} = ?");
    $stmt->execute([$employeeId]);
                $count = $stmt->fetchColumn();
                if ($count > 0) {
                    $relatedRecords[$tableName] = $count;
                }
            }
        } catch (Exception $e) {
            // Table might not exist or column name might be different, skip it
            error_log("Warning: Could not check table {$tableName}: " . $e->getMessage());
        }
    };
    
    // Check all possible related tables
    $checkTable('attendance');
    $checkTable('payroll_records');
    $checkTable('employee_salary_structure');
    $checkTable('employee_master_sheet');
    $checkTable('salary_register', 'employee_id');
    $checkTable('new_joinee_statutory', 'employee_id');
    
    // Check if employee is a manager (has employees reporting to them)
    try {
        $checkStmt = $db->query("SHOW COLUMNS FROM employees LIKE 'manager_id'");
        if ($checkStmt->rowCount() > 0) {
            $stmt = $db->prepare("SELECT COUNT(*) FROM employees WHERE manager_id = ?");
    $stmt->execute([$employeeId]);
            $managerCount = $stmt->fetchColumn();
            if ($managerCount > 0) {
                $relatedRecords['employees (as manager)'] = $managerCount;
            }
        }
    } catch (Exception $e) {
        // manager_id column might not exist
    }
    
    // Start transaction for safe deletion
    $db->beginTransaction();
    
    try {
        // Always delete related records automatically before deleting employee
        if (!empty($relatedRecords)) {
            // Delete related records from various tables
            foreach ($relatedRecords as $table => $count) {
                try {
                    // Check if table exists
                    $checkStmt = $db->query("SHOW TABLES LIKE '{$table}'");
                    if ($checkStmt->rowCount() > 0) {
                        // Delete records
                        $deleteStmt = $db->prepare("DELETE FROM {$table} WHERE employee_id = ?");
                        $deleteStmt->execute([$employeeId]);
                        error_log("Deleted {$deleteStmt->rowCount()} record(s) from {$table} for employee {$employeeId}");
                    }
                } catch (Exception $e) {
                    error_log("Warning: Could not delete from {$table}: " . $e->getMessage());
                    // Continue with other tables
                }
            }
            
            // Handle manager_id references (employees managed by this employee)
            try {
                $checkStmt = $db->query("SHOW COLUMNS FROM employees LIKE 'manager_id'");
                if ($checkStmt->rowCount() > 0) {
                    $updateStmt = $db->prepare("UPDATE employees SET manager_id = NULL WHERE manager_id = ?");
                    $updateStmt->execute([$employeeId]);
                    error_log("Updated manager_id for employees managed by employee {$employeeId}");
                }
            } catch (Exception $e) {
                error_log("Warning: Could not update manager_id references: " . $e->getMessage());
            }
        }
        
        // Delete employee
        // For Super Admin, allow deletion from any site
        // For others, check site_id
        if (isSuperAdmin()) {
            $stmt = $db->prepare("DELETE FROM employees WHERE employee_id = ?");
            $result = $stmt->execute([$employeeId]);
        } else {
            $stmt = $db->prepare("DELETE FROM employees WHERE employee_id = ? AND site_id = ?");
            $result = $stmt->execute([$employeeId, $siteId]);
        }
        
        if (!$result) {
            throw new Exception('Delete query failed');
        }
        
        $affectedRows = $stmt->rowCount();
        
        if ($affectedRows === 0) {
            $db->rollBack();
            redirect(BASE_URL . '/modules/employee/list.php', 'Employee not found or already deleted.', 'error');
        }
        
        // Log audit
        try {
            if (function_exists('logAudit')) {
                logAudit('DELETE', 'employees', $employeeId, $employee, null);
            }
        } catch (Exception $auditError) {
            // Log audit error but don't fail the deletion
            error_log("Audit log error (non-critical): " . $auditError->getMessage());
        }
        
        // Commit transaction
        $db->commit();
        
        redirect(BASE_URL . '/modules/employee/list.php', 'Employee deleted successfully.');
        
    } catch (Exception $e) {
        $db->rollBack();
        error_log("Error deleting employee {$employeeId}: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        redirect(BASE_URL . '/modules/employee/list.php', 'An error occurred while deleting the employee: ' . htmlspecialchars($e->getMessage()), 'error');
    }
    
} catch (PDOException $e) {
    // Rollback transaction if it was started
    try {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
    } catch (Exception $rollbackError) {
        error_log("Error during rollback: " . $rollbackError->getMessage());
    }
    
    $errorCode = $e->getCode();
    $errorMessage = $e->getMessage();
    
    // Check for foreign key constraint violation
    if ($errorCode == '23000' || strpos($errorMessage, 'foreign key constraint') !== false) {
        error_log("Foreign key constraint error while deleting employee {$employeeId}: " . $errorMessage);
        redirect(BASE_URL . '/modules/employee/list.php', 'Cannot delete employee due to related records in other tables. Please change status to inactive instead.', 'error');
    }
    
    error_log("Database error deleting employee {$employeeId}: " . $errorMessage);
    error_log("Error code: " . $errorCode);
    redirect(BASE_URL . '/modules/employee/list.php', 'An error occurred while deleting the employee: ' . htmlspecialchars($errorMessage), 'error');
}

