<?php
/**
 * Enterprise HRM ERP System - Edit Department
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

$pageTitle = 'Edit Department';
$currentModule = 'settings';

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

if ($departmentId <= 0) {
    redirect(BASE_URL . '/admin/departments.php?tab=departments', 'Invalid department ID.', 'error');
}

// Get department details
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM departments WHERE department_id = ? AND site_id = ?");
    $stmt->execute([$departmentId, $siteId]);
    $department = $stmt->fetch();
    
    if (!$department) {
        redirect(BASE_URL . '/admin/departments.php?tab=departments', 'Department not found.', 'error');
    }
    
    $formData = $department;
    
} catch (Exception $e) {
    error_log("Error loading department: " . $e->getMessage());
    redirect(BASE_URL . '/admin/departments.php?tab=departments', 'Error loading department data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'department_code' => sanitize($_POST['department_code'] ?? ''),
        'department_name' => sanitize($_POST['department_name'] ?? ''),
        'department_description' => sanitize($_POST['department_description'] ?? ''),
        'department_head_id' => isset($_POST['department_head_id']) && $_POST['department_head_id'] > 0 ? (int)$_POST['department_head_id'] : null,
        'department_status' => sanitize($_POST['department_status'] ?? 'active'),
    ];
    
    // Validation
    if (empty($formData['department_code'])) {
        $errors[] = 'Department code is required.';
    } elseif (strlen($formData['department_code']) < 2) {
        $errors[] = 'Department code must be at least 2 characters.';
    }
    
    if (empty($formData['department_name'])) {
        $errors[] = 'Department name is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Check if department code already exists for this site (excluding current department)
            $stmt = $db->prepare("SELECT department_id FROM departments WHERE site_id = ? AND department_code = ? AND department_id != ?");
            $stmt->execute([$siteId, $formData['department_code'], $departmentId]);
            if ($stmt->fetch()) {
                $errors[] = 'Department code already exists for this site.';
                $db->rollBack();
            } else {
                // Update department (description field may not exist in schema)
                $stmt = $db->prepare("
                    UPDATE departments SET
                        department_code = ?,
                        department_name = ?,
                        department_head_id = ?,
                        department_status = ?,
                        updated_at = NOW()
                    WHERE department_id = ? AND site_id = ?
                ");
                $stmt->execute([
                    $formData['department_code'],
                    $formData['department_name'],
                    $formData['department_head_id'],
                    $formData['department_status'],
                    $departmentId,
                    $siteId
                ]);
                
                $db->commit();
                
                // Log audit
                logAudit('UPDATE', 'departments', $departmentId);
                
                redirect(BASE_URL . '/admin/departments.php?tab=departments', 'Department updated successfully.');
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error updating department: " . $e->getMessage());
            $errors[] = 'An error occurred while updating department. Please try again.';
        }
    }
}

// Get employees for department head selection
$employees = [];
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT employee_id, employee_code, first_name, last_name, middle_name
        FROM employees
        WHERE site_id = ? AND employment_status = 'active'
        ORDER BY first_name, last_name
    ");
    $stmt->execute([$siteId]);
    $employees = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error loading employees: " . $e->getMessage());
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Department</h2>
        <a href="<?php echo BASE_URL; ?>/admin/departments.php?tab=departments" class="btn btn-secondary">Back to Departments</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" id="departmentForm" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="department_code">Department Code *</label>
                <input type="text" id="department_code" name="department_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['department_code'] ?? ''); ?>"
                       placeholder="e.g., HR, IT, FIN" maxlength="50">
                <small style="color: var(--text-secondary);">Unique code for this department</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="department_name">Department Name *</label>
                <input type="text" id="department_name" name="department_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['department_name'] ?? ''); ?>"
                       placeholder="e.g., Human Resources" maxlength="255">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="department_description">Description</label>
                <textarea id="department_description" name="department_description" class="form-control" rows="4"
                          placeholder="Enter department description..."><?php echo htmlspecialchars($formData['department_description'] ?? ''); ?></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="department_head_id">Department Head</label>
                <select id="department_head_id" name="department_head_id" class="form-control">
                    <option value="">Select Department Head (Optional)</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['employee_id']; ?>" 
                            <?php echo ($formData['department_head_id'] ?? 0) == $emp['employee_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['employee_code'] . ' - ' . trim($emp['first_name'] . ' ' . ($emp['middle_name'] ?? '') . ' ' . $emp['last_name'])); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <small style="color: var(--text-secondary);">Select an employee as department head</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="department_status">Status *</label>
                <select id="department_status" name="department_status" class="form-control" required>
                    <option value="active" <?php echo ($formData['department_status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo ($formData['department_status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                </select>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/admin/departments.php?tab=departments" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Department</button>
        </div>
    </form>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

