<?php
define('SECURE_ACCESS', true);

$pageTitle = "Designation Management";
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();

$currentUser = getCurrentUser();

$error = '';
$success = '';
$editDesig = null;

// Fetch all events for multiselect access control
$events = [];
try {
    $stmt = $pdo->query("SELECT id, title FROM events ORDER BY id DESC");
    $events = $stmt->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load events: " . $e->getMessage();
}

// Handle Delete Designation Action
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (!verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: designations");
        exit();
    }
    $deleteId = (int)$_GET['id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM designations WHERE id = ?");
        $stmt->execute([$deleteId]);
        $_SESSION['flash_success'] = "Designation deleted successfully.";
    } catch (PDOException $e) {
        $_SESSION['flash_error'] = "Failed to delete designation (it may be assigned to active users).";
    }
    header("Location: designations");
    exit();
}

// Handle Add/Edit Designation Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_desig'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: designations");
        exit();
    }
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $is_default = isset($_POST['is_default']) ? 1 : 0;
    $matrix_width = (int)($_POST['matrix_width'] ?? 4);
    $matrix_depth = (int)($_POST['matrix_depth'] ?? 5);
    $level_commissions = trim($_POST['level_commissions'] ?? '');
    $criteria_direct_referrals = (int)($_POST['criteria_direct_referrals'] ?? 0);
    $criteria_team_size = (int)($_POST['criteria_team_size'] ?? 0);
    $criteria_min_payout = (float)($_POST['criteria_min_payout'] ?? 0.00);
    $criteria_max_earning_cap = (float)($_POST['criteria_max_earning_cap'] ?? 0.00);
    $criteria_min_duration_months = (int)($_POST['criteria_min_duration_months'] ?? 0);
    $allow_wallet_payment = isset($_POST['allow_wallet_payment']) ? 1 : 0;
    
    // Process multiselect events
    $sel_events = $_POST['accessible_event_ids'] ?? [];
    $accessible_event_ids = implode(',', array_map('intval', $sel_events));

    // Validate Level Commissions
    $commissions_arr = array_filter(array_map('trim', explode(',', $level_commissions)));
    $commissions_sum = 0;
    foreach ($commissions_arr as $c) {
        if (!is_numeric($c)) {
            $error = "Commissions must be comma-separated numbers (e.g. 10,5,5,10).";
            break;
        }
        $commissions_sum += (float)$c;
    }

    if (empty($title)) {
        $error = "Designation Title is required.";
    } elseif ($commissions_sum > 50) {
        $error = "The sum of level commissions cannot exceed 50% (Current sum: $commissions_sum%).";
    } elseif (count($commissions_arr) > $matrix_depth) {
        $error = "You cannot configure more commission levels than the matrix depth ($matrix_depth).";
    }

    if (empty($error)) {
        try {
            $pdo->beginTransaction();

            // If this is set as default, reset all other default designations
            if ($is_default) {
                $db_stmt = $pdo->prepare("UPDATE designations SET is_default = FALSE WHERE is_default = TRUE");
                $db_stmt->execute();
            }

            if ($id > 0) {
                // Update
                $upd_stmt = $pdo->prepare("
                    UPDATE designations 
                    SET title = ?, description = ?, is_default = ?, matrix_width = ?, matrix_depth = ?, level_commissions = ?, 
                        criteria_direct_referrals = ?, criteria_team_size = ?, criteria_min_payout = ?, 
                        criteria_max_earning_cap = ?, criteria_min_duration_months = ?, accessible_event_ids = ?,
                        allow_wallet_payment = ?
                    WHERE id = ?
                ");
                $upd_stmt->execute([
                    $title, $description, $is_default ? 'true' : 'false', $matrix_width, $matrix_depth, implode(',', $commissions_arr),
                    $criteria_direct_referrals, $criteria_team_size, $criteria_min_payout, 
                    $criteria_max_earning_cap, $criteria_min_duration_months, $accessible_event_ids, $allow_wallet_payment ? 'true' : 'false', $id
                ]);
                $_SESSION['flash_success'] = "Designation '$title' updated successfully.";
            } else {
                // Insert
                $ins_stmt = $pdo->prepare("
                    INSERT INTO designations (title, description, is_default, matrix_width, matrix_depth, level_commissions, 
                                              criteria_direct_referrals, criteria_team_size, criteria_min_payout, 
                                              criteria_max_earning_cap, criteria_min_duration_months, accessible_event_ids, allow_wallet_payment) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $ins_stmt->execute([
                    $title, $description, $is_default ? 'true' : 'false', $matrix_width, $matrix_depth, implode(',', $commissions_arr),
                    $criteria_direct_referrals, $criteria_team_size, $criteria_min_payout, 
                    $criteria_max_earning_cap, $criteria_min_duration_months, $accessible_event_ids, $allow_wallet_payment ? 'true' : 'false'
                ]);
                $_SESSION['flash_success'] = "Designation '$title' created successfully.";
            }

            $pdo->commit();
            header("Location: designations");
            exit();
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = "Database transaction failed: " . $e->getMessage();
        }
    }
}

// Fetch single designation if editing
if (isset($_GET['edit_id'])) {
    $editId = (int)$_GET['edit_id'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM designations WHERE id = ?");
        $stmt->execute([$editId]);
        $editDesig = $stmt->fetch();
    } catch (PDOException $e) {
        $error = "Failed to load designation details.";
    }
}

// Fetch all designations for rendering
$designations = [];
try {
    $stmt = $pdo->query("SELECT * FROM designations ORDER BY id ASC");
    $designations = $stmt->fetchAll();
} catch (PDOException $e) {
    $error = "Failed to load designations: " . $e->getMessage();
}

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

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">Designation & Performance Hierarchy</h1>
        <p class="text-muted mb-0">Configure corporate designations, organization structures, level commissions, and event access control filters.</p>
    </div>
    <div>
        <button type="button" class="btn btn-primary px-4 py-2.5 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#desigModal">
            <i class="bi bi-patch-plus me-1"></i> Add Designation
        </button>
    </div>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Designations List Table -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light text-muted uppercase font-monospace" style="font-size: 0.75rem;">
                    <tr>
                        <th class="ps-4">Rank Designation</th>
                        <th>Hierarchy Width/Depth</th>
                        <th>Level Commission %</th>
                        <th>Direct/Team Criteria</th>
                        <th>Payout/Earning Limits</th>
                        <th>Accessible Events</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($designations)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-5 text-muted">
                                <i class="bi bi-award fs-1 mb-2"></i>
                                <p class="mb-0">No designations configured.</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($designations as $d): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <div class="p-2 bg-primary bg-opacity-10 text-primary rounded me-3">
                                            <i class="bi bi-award-fill fs-5"></i>
                                        </div>
                                        <div>
                                            <strong class="text-dark d-block"><?php echo htmlspecialchars($d['title']); ?></strong>
                                            <?php if ($d['is_default']): ?>
                                                <span class="badge bg-success-subtle text-success small" style="font-size: 0.7rem;">DEFAULT ASSIGNMENT</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge bg-dark bg-opacity-10 text-dark font-monospace"><?php echo $d['matrix_width']; ?>x<?php echo $d['matrix_depth']; ?> Org Layout</span>
                                </td>
                                <td>
                                    <div class="d-flex flex-wrap gap-1">
                                        <?php 
                                            $comm_list = explode(',', $d['level_commissions']);
                                            foreach ($comm_list as $idx => $pct) {
                                                echo '<span class="badge bg-primary bg-opacity-10 text-primary small">L' . ($idx + 1) . ': ' . $pct . '%</span>';
                                            }
                                        ?>
                                    </div>
                                </td>
                                <td>
                                    <div class="small text-secondary">
                                        <div>Direct: <strong><?php echo $d['criteria_direct_referrals']; ?></strong></div>
                                        <div>Team: <strong><?php echo $d['criteria_team_size']; ?></strong></div>
                                    </div>
                                </td>
                                <td>
                                    <div class="small text-secondary">
                                        <div>Min Payout: <strong>₹<?php echo number_format($d['criteria_min_payout'], 2); ?>/mo</strong></div>
                                        <div>Max Cap: <strong>₹<?php echo number_format($d['criteria_max_earning_cap'], 2); ?>/mo</strong></div>
                                    </div>
                                </td>
                                <td>
                                    <?php if (empty($d['accessible_event_ids'])): ?>
                                        <span class="text-success small"><i class="bi bi-unlock-fill me-1"></i>All Events</span>
                                    <?php else: ?>
                                        <span class="text-warning small"><i class="bi bi-lock-fill me-1"></i><?php echo count(explode(',', $d['accessible_event_ids'])); ?> Restrict</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end pe-4">
                                    <div class="d-flex justify-content-end gap-2">
                                        <a href="designations?edit_id=<?php echo $d['id']; ?>" class="btn btn-sm btn-outline-warning" title="Edit Designation">
                                            <i class="bi bi-pencil-fill"></i> Edit
                                        </a>
                                        <?php if (!$d['is_default']): ?>
                                            <a href="designations?action=delete&id=<?php echo $d['id']; ?>&csrf_token=<?php echo getCSRFToken(); ?>" class="btn btn-sm btn-outline-danger" title="Delete Designation" onclick="return confirm('Delete designation rank <?php echo htmlspecialchars($d['title']); ?>?');">
                                                <i class="bi bi-trash-fill"></i> Delete
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Designation Modal Container -->
<div class="modal fade" id="desigModal" tabindex="-1" aria-labelledby="desigModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form method="POST" action="designations" class="modal-content">
            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="desigModalLabel">
                    <?php if ($editDesig): ?>
                        <i class="bi bi-pencil-square text-warning me-2"></i>Edit Designation Config
                    <?php else: ?>
                        <i class="bi bi-patch-check text-primary me-2"></i>Create New Designation
                    <?php endif; ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <?php if ($editDesig): ?>
                    <input type="hidden" name="id" value="<?php echo $editDesig['id']; ?>">
                <?php endif; ?>

                <!-- Step Indicators -->
                <div class="row g-2 text-center mb-4 border-bottom pb-3 font-monospace small">
                    <div class="col-3">
                        <span id="indicatorStep1" class="badge rounded-pill p-2 w-100 bg-primary text-white">1. Basic Info</span>
                    </div>
                    <div class="col-3">
                        <span id="indicatorStep2" class="badge rounded-pill p-2 w-100 bg-light text-dark">2. Matrix Setup</span>
                    </div>
                    <div class="col-3">
                        <span id="indicatorStep3" class="badge rounded-pill p-2 w-100 bg-light text-dark">3. Promotion Rules</span>
                    </div>
                    <div class="col-3">
                        <span id="indicatorStep4" class="badge rounded-pill p-2 w-100 bg-light text-dark">4. Event Access</span>
                    </div>
                </div>

                <!-- Step 1: Basic Info -->
                <div class="desig-step" id="desigStep1">
                    <h6 class="fw-bold text-dark border-bottom pb-2 mb-3"><i class="bi bi-info-circle me-1 text-primary"></i> 1. Basic Designation Rank Details</h6>
                    <div class="row g-3">
                        <div class="col-12 col-md-8">
                            <label for="title" class="form-label">Designation Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="title" name="title" required value="<?php echo htmlspecialchars($editDesig['title'] ?? ''); ?>" placeholder="e.g. Sales Coordinator">
                        </div>
                        <div class="col-12 col-md-4 d-flex flex-column justify-content-end">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" id="is_default" name="is_default" <?php echo isset($editDesig) && $editDesig['is_default'] ? 'checked' : ''; ?>>
                                <label class="form-check-label fw-semibold" for="is_default">
                                    Set as Default Rank
                                </label>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" id="allow_wallet_payment" name="allow_wallet_payment" <?php echo isset($editDesig) && $editDesig['allow_wallet_payment'] ? 'checked' : ''; ?>>
                                <label class="form-check-label fw-semibold" for="allow_wallet_payment">
                                    Allow Wallet Payments
                                </label>
                            </div>
                        </div>
                        <div class="col-12">
                            <label for="description" class="form-label">Description</label>
                             <textarea class="form-control" id="description" name="description" rows="3" placeholder="Brief outline of target organizational rankings..."><?php echo htmlspecialchars($editDesig['description'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Step 2: Performance Forced Matrix Settings -->
                <div class="desig-step" id="desigStep2" style="display: none;">
                    <h6 class="fw-bold text-dark border-bottom pb-2 mb-3"><i class="bi bi-diagram-3 me-1 text-primary"></i> 2. Organizational Placement & Level Incentives</h6>
                    <div class="row g-3">
                        <div class="col-12 col-sm-6 col-md-4">
                            <label for="matrix_width" class="form-label">Hierarchy Structure Width</label>
                            <input type="number" class="form-control" id="matrix_width" name="matrix_width" required min="2" max="10" value="<?php echo htmlspecialchars($editDesig['matrix_width'] ?? 4); ?>">
                            <span class="small text-muted font-monospace">Children count per node.</span>
                        </div>
                        <div class="col-12 col-sm-6 col-md-4">
                            <label for="matrix_depth" class="form-label">Hierarchy Structure Depth</label>
                            <input type="number" class="form-control" id="matrix_depth" name="matrix_depth" required min="2" max="10" value="<?php echo htmlspecialchars($editDesig['matrix_depth'] ?? 5); ?>">
                            <span class="small text-muted font-monospace">Maximum level depth.</span>
                        </div>
                        <div class="col-12 col-md-4">
                            <label for="level_commissions" class="form-label">Level Commissions (%)</label>
                            <input type="text" class="form-control font-monospace" id="level_commissions" name="level_commissions" required placeholder="e.g. 10,5,5,10,20" value="<?php echo htmlspecialchars($editDesig['level_commissions'] ?? '10,5,5,10,20'); ?>">
                            <span class="small text-muted font-monospace">Comma-separated. Sum &le; 50%.</span>
                        </div>
                    </div>
                </div>

                <!-- Step 3: Promotion Criteria -->
                <div class="desig-step" id="desigStep3" style="display: none;">
                    <h6 class="fw-bold text-dark border-bottom pb-2 mb-3"><i class="bi bi-graph-up-arrow me-1 text-primary"></i> 3. Promotion/Qualifying Criteria</h6>
                    <div class="row g-3">
                        <div class="col-12 col-sm-6 col-md-4">
                            <label for="criteria_direct_referrals" class="form-label">Direct Team Required</label>
                            <input type="number" class="form-control" id="criteria_direct_referrals" name="criteria_direct_referrals" value="<?php echo htmlspecialchars($editDesig['criteria_direct_referrals'] ?? 0); ?>">
                        </div>
                        <div class="col-12 col-sm-6 col-md-4">
                            <label for="criteria_team_size" class="form-label">Total Team Size Required</label>
                            <input type="number" class="form-control" id="criteria_team_size" name="criteria_team_size" value="<?php echo htmlspecialchars($editDesig['criteria_team_size'] ?? 0); ?>">
                        </div>
                        <div class="col-12 col-sm-6 col-md-4">
                            <label for="criteria_min_duration_months" class="form-label">Min Months in Designation</label>
                            <input type="number" class="form-control" id="criteria_min_duration_months" name="criteria_min_duration_months" value="<?php echo htmlspecialchars($editDesig['criteria_min_duration_months'] ?? 0); ?>">
                        </div>
                        <div class="col-12 col-sm-6">
                            <label for="criteria_min_payout" class="form-label">Minimum Payout per Month (₹)</label>
                            <input type="number" step="0.01" class="form-control" id="criteria_min_payout" name="criteria_min_payout" value="<?php echo htmlspecialchars($editDesig['criteria_min_payout'] ?? 0.00); ?>">
                        </div>
                        <div class="col-12 col-sm-6">
                            <label for="criteria_max_earning_cap" class="form-label">Maximum Earning Cap per Month (₹)</label>
                            <input type="number" step="0.01" class="form-control" id="criteria_max_earning_cap" name="criteria_max_earning_cap" value="<?php echo htmlspecialchars($editDesig['criteria_max_earning_cap'] ?? 0.00); ?>">
                        </div>
                    </div>
                </div>

                <!-- Step 4: Content Access Control -->
                <div class="desig-step" id="desigStep4" style="display: none;">
                    <h6 class="fw-bold text-dark border-bottom pb-2 mb-3"><i class="bi bi-shield-lock me-1 text-primary"></i> 4. Event Content Access Control</h6>
                    <div class="mb-2">
                        <label class="form-label">Select Accessible Events <span class="text-muted small">(Leave completely empty to unlock all events)</span></label>
                        <select name="accessible_event_ids[]" multiple class="form-select" size="5" style="border-radius: 8px;">
                            <?php 
                                $accessible_arr = !empty($editDesig['accessible_event_ids']) ? explode(',', $editDesig['accessible_event_ids']) : [];
                                foreach ($events as $ev): 
                            ?>
                                <option value="<?php echo $ev['id']; ?>" <?php echo in_array($ev['id'], $accessible_arr) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($ev['title']); ?> (ID: <?php echo $ev['id']; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <span class="small text-muted font-monospace d-block mt-1">Press Ctrl (Windows) / Cmd (Mac) to select multiple specific events.</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer d-flex justify-content-between">
                <div>
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-secondary" id="btnBack" style="display: none;"><i class="bi bi-arrow-left me-1"></i> Back</button>
                    <button type="button" class="btn btn-primary" id="btnNext">Next <i class="bi bi-arrow-right ms-1"></i></button>
                    <button type="submit" name="submit_desig" class="btn btn-success px-4 fw-bold" id="btnSave" style="display: none;">
                        <i class="bi bi-save me-1"></i> Save Configuration
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        let currentStep = 1;
        const totalSteps = 4;

        function showStep(step) {
            for (let i = 1; i <= totalSteps; i++) {
                const stepEl = document.getElementById('desigStep' + i);
                if (stepEl) stepEl.style.display = 'none';

                const indEl = document.getElementById('indicatorStep' + i);
                if (indEl) {
                    indEl.classList.remove('bg-primary', 'text-white');
                    indEl.classList.add('bg-light', 'text-dark');
                }
            }

            const activeStepEl = document.getElementById('desigStep' + step);
            if (activeStepEl) activeStepEl.style.display = 'block';

            const activeIndEl = document.getElementById('indicatorStep' + step);
            if (activeIndEl) {
                activeIndEl.classList.remove('bg-light', 'text-dark');
                activeIndEl.classList.add('bg-primary', 'text-white');
            }

            const btnBack = document.getElementById('btnBack');
            const btnNext = document.getElementById('btnNext');
            const btnSave = document.getElementById('btnSave');

            if (step === 1) {
                if (btnBack) btnBack.style.display = 'none';
                if (btnNext) btnNext.style.display = 'inline-block';
                if (btnSave) btnSave.style.display = 'none';
            } else if (step === totalSteps) {
                if (btnBack) btnBack.style.display = 'inline-block';
                if (btnNext) btnNext.style.display = 'none';
                if (btnSave) btnSave.style.display = 'inline-block';
            } else {
                if (btnBack) btnBack.style.display = 'inline-block';
                if (btnNext) btnNext.style.display = 'inline-block';
                if (btnSave) btnSave.style.display = 'none';
            }
        }

        const btnNext = document.getElementById('btnNext');
        if (btnNext) {
            btnNext.addEventListener('click', function() {
                if (currentStep === 1) {
                    const titleVal = document.getElementById('title').value.trim();
                    if (!titleVal) {
                        alert('Designation Title is required.');
                        return;
                    }
                } else if (currentStep === 2) {
                    const widthVal = parseInt(document.getElementById('matrix_width').value);
                    const depthVal = parseInt(document.getElementById('matrix_depth').value);
                    const commsVal = document.getElementById('level_commissions').value.trim();

                    if (isNaN(widthVal) || widthVal < 2 || widthVal > 10) {
                        alert('Matrix Width must be between 2 and 10.');
                        return;
                    }
                    if (isNaN(depthVal) || depthVal < 2 || depthVal > 10) {
                        alert('Matrix Depth must be between 2 and 10.');
                        return;
                    }
                    if (!commsVal) {
                        alert('Level commissions are required.');
                        return;
                    }

                    const commsArr = commsVal.split(',').map(v => parseFloat(v.trim()));
                    let sum = 0;
                    for (let c of commsArr) {
                        if (isNaN(c)) {
                            alert('Commissions must be valid numbers.');
                            return;
                        }
                        sum += c;
                    }
                    if (sum > 50) {
                        alert('Sum of commissions cannot exceed 50%. Current sum: ' + sum + '%');
                        return;
                    }
                    if (commsArr.length > depthVal) {
                        alert('You cannot configure more commissions than the matrix depth (' + depthVal + ').');
                        return;
                    }
                }

                if (currentStep < totalSteps) {
                    currentStep++;
                    showStep(currentStep);
                }
            });
        }

        const btnBack = document.getElementById('btnBack');
        if (btnBack) {
            btnBack.addEventListener('click', function() {
                if (currentStep > 1) {
                    currentStep--;
                    showStep(currentStep);
                }
            });
        }

        const desigModalEl = document.getElementById('desigModal');
        if (desigModalEl) {
            desigModalEl.addEventListener('show.bs.modal', function () {
                currentStep = 1;
                showStep(1);
            });
            desigModalEl.addEventListener('hidden.bs.modal', function () {
                if (window.location.search.includes('edit_id=')) {
                    window.location.href = 'designations';
                }
            });
        }
    });
</script>

<?php if ($editDesig): ?>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const desigModal = new bootstrap.Modal(document.getElementById('desigModal'));
        desigModal.show();
    });
</script>
<?php endif; ?>

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