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

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

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

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

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

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

$errors = [];

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

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Designation</h2>
        <a href="<?php echo BASE_URL; ?>/admin/departments.php?tab=designations" class="btn btn-secondary">Back to Designations</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="designationForm" 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="designation_code">Designation Code *</label>
                <input type="text" id="designation_code" name="designation_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['designation_code'] ?? ''); ?>"
                       placeholder="e.g., MGR, SR, JR" maxlength="50">
                <small style="color: var(--text-secondary);">Unique code for this designation</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="designation_name">Designation Name *</label>
                <input type="text" id="designation_name" name="designation_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['designation_name'] ?? ''); ?>"
                       placeholder="e.g., Manager, Senior Developer" maxlength="255">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="designation_description">Description</label>
                <textarea id="designation_description" name="designation_description" class="form-control" rows="4"
                          placeholder="Enter designation description..."><?php echo htmlspecialchars($formData['designation_description'] ?? ''); ?></textarea>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="designation_level">Designation Level</label>
                <input type="number" id="designation_level" name="designation_level" class="form-control"
                       value="<?php echo htmlspecialchars($formData['designation_level'] ?? 0); ?>"
                       min="0" max="100">
                <small style="color: var(--text-secondary);">Hierarchy level (0 = lowest, higher = senior)</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="designation_status">Status *</label>
                <select id="designation_status" name="designation_status" class="form-control" required>
                    <option value="active" <?php echo ($formData['designation_status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo ($formData['designation_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=designations" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Designation</button>
        </div>
    </form>
</div>

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

