<?php
function slugify($text) {
    $text = preg_replace('~[^
\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    $text = strtolower($text);
    return $text ?: 'item';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $filePath = '../faculty.json';
    $faculties = [];

    if (file_exists($filePath)) {
        $raw = file_get_contents($filePath);
        $decoded = json_decode($raw, true);

        if (is_array($decoded)) {
            // if object style (assoc) convert to array
            if (array_keys($decoded) !== range(0, count($decoded) - 1)) {
                $faculties = [$decoded];
            } else {
                $faculties = $decoded;
            }
        }
    }

    $index = isset($_POST['index']) ? intval($_POST['index']) : -1;

    $newEntry = [
        'name' => $_POST['name'] ?? '',
        'slug' => isset($_POST['slug']) ? trim($_POST['slug']) : slugify($_POST['name'] ?? ''),
        'initials' => $_POST['initials'] ?? '',
        'designation' => $_POST['designation'] ?? '',
        'institution' => $_POST['institution'] ?? '',
        'phone' => $_POST['phone'] ?? '',
        'email' => $_POST['email'] ?? '',
        'linkedin' => $_POST['linkedin'] ?? '',
        'stats' => [
            'experience' => $_POST['stats']['experience'] ?? '',
            'publications' => $_POST['stats']['publications'] ?? '',
            'research' => $_POST['stats']['research'] ?? '',
            'admin' => $_POST['stats']['admin'] ?? ''
        ],
        'professionalProfile' => $_POST['professionalProfile'] ?? '',
        'areaOfInterest' => $_POST['areaOfInterest'] ?? '',
        'subjectsTaught' => [
            'ug' => isset($_POST['subjectsTaught']['ug']) ? array_filter(array_map('trim', explode(',', $_POST['subjectsTaught']['ug']))) : [],
            'pg' => isset($_POST['subjectsTaught']['pg']) ? array_filter(array_map('trim', explode(',', $_POST['subjectsTaught']['pg']))) : []
        ],
        'keySkills' => isset($_POST['keySkills']) ? array_filter(array_map('trim', explode(',', $_POST['keySkills']))) : [],
        'experienceSummary' => [
            'total' => $_POST['experienceSummary']['total'] ?? '',
            'research' => $_POST['experienceSummary']['research'] ?? '',
            'admin' => $_POST['experienceSummary']['admin'] ?? ''
        ],
        'academicBackground' => json_decode($_POST['academicBackground'] ?? '[]', true) ?: [],
        'workExperience' => json_decode($_POST['workExperience'] ?? '[]', true) ?: [],
        'publications' => json_decode($_POST['publications'] ?? '[]', true) ?: []
    ];

    if ($index >= 0 && $index < count($faculties)) {
        $faculties[$index] = $newEntry;
    } else {
        $faculties[] = $newEntry;
    }

    file_put_contents($filePath, json_encode($faculties, JSON_PRETTY_PRINT));
	header('Location: index.php?status=success');
    exit;
}

echo 'Invalid request.';
?>