<?php
session_start();

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
if ($userRole !== 'M' && $userRole !== 'A') {
    header("Location: ../../index.html?error=forbidden");
    exit;
}

require_once __DIR__ . '/../../DataBase/koneksi.php';

// Handle form submission
$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get and validate form data
    $nip = mysqli_real_escape_string($conn, trim($_POST['nip'] ?? ''));
    $nama = mysqli_real_escape_string($conn, trim($_POST['nama'] ?? ''));
    $jenis_kelamin = mysqli_real_escape_string($conn, trim($_POST['jenis_kelamin'] ?? ''));
    $tempat_lahir = mysqli_real_escape_string($conn, trim($_POST['tempat_lahir'] ?? ''));
    $tanggal_lahir = mysqli_real_escape_string($conn, trim($_POST['tanggal_lahir'] ?? ''));
    $alamat = mysqli_real_escape_string($conn, trim($_POST['alamat'] ?? ''));
    $no_hp = mysqli_real_escape_string($conn, trim($_POST['no_hp'] ?? ''));
    $email = mysqli_real_escape_string($conn, trim($_POST['email'] ?? ''));
    $jabatan = mysqli_real_escape_string($conn, trim($_POST['jabatan'] ?? ''));
    $kantor = mysqli_real_escape_string($conn, trim($_POST['kantor'] ?? ''));
    $tanggal_masuk = mysqli_real_escape_string($conn, trim($_POST['tanggal_masuk'] ?? ''));
    $status = mysqli_real_escape_string($conn, trim($_POST['status'] ?? 'Aktif'));
    $pendidikan = mysqli_real_escape_string($conn, trim($_POST['pendidikan'] ?? ''));
    $jurusan = mysqli_real_escape_string($conn, trim($_POST['jurusan'] ?? ''));

    // Validation
    if (empty($nama)) {
        $errors[] = "Nama harus diisi";
    }

    // Check if NIP already exists
    if (!empty($nip)) {
        $checkNip = mysqli_query($conn, "SELECT id FROM sdm WHERE nip = '$nip'");
        if (mysqli_num_rows($checkNip) > 0) {
            $errors[] = "NIP sudah terdaftar";
        }
    }

    // Check if email already exists
    if (!empty($email)) {
        $checkEmail = mysqli_query($conn, "SELECT id FROM sdm WHERE email = '$email'");
        if (mysqli_num_rows($checkEmail) > 0) {
            $errors[] = "Email sudah terdaftar";
        }
    }

    // If no errors, insert data
    if (empty($errors)) {
        $queryInsert = "INSERT INTO sdm (
            nip, nama, jenis_kelamin, tempat_lahir, tanggal_lahir, 
            alamat, no_hp, email, jabatan, kantor, 
            tanggal_masuk, status, pendidikan, jurusan, created_at
        ) VALUES (
            '$nip', '$nama', '$jenis_kelamin', '$tempat_lahir', " . (empty($tanggal_lahir) ? "NULL" : "'$tanggal_lahir'") . ",
            '$alamat', '$no_hp', '$email', '$jabatan', '$kantor',
            " . (empty($tanggal_masuk) ? "NULL" : "'$tanggal_masuk'") . ", '$status', '$pendidikan', '$jurusan', NOW()
        )";

        if (mysqli_query($conn, $queryInsert)) {
            // Log activity
            $username = $_SESSION['username'] ?? 'Unknown';
            $logQuery = "INSERT INTO activity_log (user, action, description, timestamp) 
                         VALUES ('$username', 'INSERT', 'Menambah SDM baru: $nama', NOW())";
            @mysqli_query($conn, $logQuery);

            $success = true;
            // Redirect to index after success
            header("Location: index.php?success=added");
            exit;
        } else {
            $errors[] = "Gagal menambahkan data: " . mysqli_error($conn);
        }
    }
}

// Get list for dropdowns
$kantorList = [];
$qKantor = mysqli_query($conn, "SELECT DISTINCT kantor FROM sdm WHERE kantor IS NOT NULL AND kantor != '' ORDER BY kantor");
while($r = mysqli_fetch_assoc($qKantor)) { $kantorList[] = $r['kantor']; }

$jabatanList = [];
$qJabatan = mysqli_query($conn, "SELECT DISTINCT jabatan FROM sdm WHERE jabatan IS NOT NULL AND jabatan != '' ORDER BY jabatan");
while($r = mysqli_fetch_assoc($qJabatan)) { $jabatanList[] = $r['jabatan']; }

mysqli_close($conn);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tambah SDM - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-teal: #7AB2B2;
            --secondary-teal: #4D869C;
            --light-mint: #CDE8E5;
            --lightest-mint: #EEF7FF;
            --bg-light: #f8fafc;
            --text-dark: #1e293b;
            --text-medium: #475569;
            --text-light: #64748b;
            --border-color: #e2e8f0;
            --purple: #6366f1;
            --green: #16a34a;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-light);
            color: var(--text-dark);
            padding: 24px;
            line-height: 1.6;
        }

        .container { max-width: 1000px; margin: 0 auto; }

        /* Header */
        .page-header {
            margin-bottom: 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .header-title h1 {
            font-size: 28px;
            font-weight: 800;
            color: var(--text-dark);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .breadcrumb {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: var(--text-light);
        }

        .breadcrumb a {
            color: var(--primary-teal);
            text-decoration: none;
            font-weight: 600;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        /* Alert Messages */
        .alert {
            padding: 14px 18px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
            font-size: 14px;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #6ee7b7;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }

        .alert i {
            font-size: 18px;
            margin-top: 2px;
        }

        .alert-content {
            flex: 1;
        }

        .alert-content ul {
            margin-top: 8px;
            padding-left: 20px;
        }

        .alert-content li {
            margin-bottom: 4px;
        }

        /* Main Card */
        .main-card {
            background: white;
            border-radius: 16px;
            border: 1px solid var(--border-color);
            overflow: hidden;
        }

        .card-header {
            padding: 24px;
            border-bottom: 1px solid var(--border-color);
            background: var(--bg-light);
        }

        .card-title {
            font-size: 18px;
            font-weight: 700;
            color: var(--text-dark);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-body {
            padding: 24px;
        }

        /* Form */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 24px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-label {
            font-size: 13px;
            font-weight: 700;
            color: var(--text-dark);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .required {
            color: #dc2626;
        }

        .form-input,
        .form-select,
        .form-textarea {
            padding: 12px 16px;
            border: 2px solid var(--border-color);
            border-radius: 10px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            outline: none;
            transition: all 0.3s ease;
            background: white;
        }

        .form-input:focus,
        .form-select:focus,
        .form-textarea:focus {
            border-color: var(--purple);
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
        }

        .form-textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-select {
            cursor: pointer;
        }

        .input-with-icon {
            position: relative;
        }

        .input-with-icon i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-light);
        }

        .input-with-icon .form-input {
            padding-left: 42px;
        }

        .radio-group {
            display: flex;
            gap: 20px;
            margin-top: 8px;
        }

        .radio-option {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }

        .radio-option input[type="radio"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .radio-option label {
            font-size: 14px;
            color: var(--text-dark);
            cursor: pointer;
        }

        /* Form Actions */
        .form-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            padding-top: 20px;
            border-top: 1px solid var(--border-color);
        }

        .btn {
            padding: 12px 28px;
            border-radius: 10px;
            font-weight: 700;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            border: none;
            transition: all 0.3s ease;
            text-decoration: none;
        }

        .btn-outline {
            background: white;
            color: var(--text-dark);
            border: 2px solid var(--border-color);
        }

        .btn-outline:hover {
            background: var(--bg-light);
            border-color: var(--primary-teal);
        }

        .btn-primary {
            background: var(--purple);
            color: white;
        }

        .btn-primary:hover {
            background: #4f46e5;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
        }

        .helper-text {
            font-size: 12px;
            color: var(--text-light);
            margin-top: 6px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            body { padding: 12px; }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-actions {
                flex-direction: column-reverse;
            }

            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Page Header -->
        <div class="page-header">
            <div class="header-title">
                <h1>
                    <i class="fas fa-user-plus" style="color: var(--purple);"></i>
                    Tambah Data SDM
                </h1>
                <div class="breadcrumb">
                    <a href="javascript:history.back()"><i class="fas fa-arrow-left"></i> Kembali</a>
                    <span>/</span>
                    <span>Tambah SDM</span>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <i class="fas fa-exclamation-circle"></i>
            <div class="alert-content">
                <strong>Terjadi kesalahan:</strong>
                <ul>
                    <?php foreach ($errors as $error): ?>
                    <li><?= htmlspecialchars($error) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
        <?php endif; ?>

        <!-- Main Form Card -->
        <form method="POST">
            <div class="main-card">
                <!-- Personal Information Section -->
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-user"></i>
                        Informasi Personal
                    </div>
                </div>
                <div class="card-body">
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label">
                                NIP
                            </label>
                            <div class="input-with-icon">
                                <i class="fas fa-id-card"></i>
                                <input type="text" 
                                       name="nip" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['nip'] ?? '') ?>"
                                       placeholder="Masukkan NIP">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">
                                Nama Lengkap <span class="required">*</span>
                            </label>
                            <div class="input-with-icon">
                                <i class="fas fa-user"></i>
                                <input type="text" 
                                       name="nama" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['nama'] ?? '') ?>"
                                       placeholder="Masukkan nama lengkap"
                                       required>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Jenis Kelamin</label>
                            <div class="radio-group">
                                <div class="radio-option">
                                    <input type="radio" 
                                           id="laki" 
                                           name="jenis_kelamin" 
                                           value="Laki-laki"
                                           <?= ($_POST['jenis_kelamin'] ?? '') === 'Laki-laki' ? 'checked' : '' ?>>
                                    <label for="laki">Laki-laki</label>
                                </div>
                                <div class="radio-option">
                                    <input type="radio" 
                                           id="perempuan" 
                                           name="jenis_kelamin" 
                                           value="Perempuan"
                                           <?= ($_POST['jenis_kelamin'] ?? '') === 'Perempuan' ? 'checked' : '' ?>>
                                    <label for="perempuan">Perempuan</label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="Aktif" <?= ($_POST['status'] ?? 'Aktif') === 'Aktif' ? 'selected' : '' ?>>Aktif</option>
                                <option value="Non-Aktif" <?= ($_POST['status'] ?? '') === 'Non-Aktif' ? 'selected' : '' ?>>Non-Aktif</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Tempat Lahir</label>
                            <div class="input-with-icon">
                                <i class="fas fa-map-marker-alt"></i>
                                <input type="text" 
                                       name="tempat_lahir" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['tempat_lahir'] ?? '') ?>"
                                       placeholder="Masukkan tempat lahir">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Tanggal Lahir</label>
                            <div class="input-with-icon">
                                <i class="fas fa-calendar"></i>
                                <input type="date" 
                                       name="tanggal_lahir" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['tanggal_lahir'] ?? '') ?>">
                            </div>
                        </div>

                        <div class="form-group full-width">
                            <label class="form-label">Alamat</label>
                            <textarea name="alamat" 
                                      class="form-textarea" 
                                      placeholder="Masukkan alamat lengkap"><?= htmlspecialchars($_POST['alamat'] ?? '') ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Contact Information Section -->
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-address-book"></i>
                        Informasi Kontak
                    </div>
                </div>
                <div class="card-body">
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label">Nomor HP</label>
                            <div class="input-with-icon">
                                <i class="fas fa-phone"></i>
                                <input type="tel" 
                                       name="no_hp" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['no_hp'] ?? '') ?>"
                                       placeholder="08xxxxxxxxxx">
                            </div>
                            <span class="helper-text">Format: 08xxxxxxxxxx</span>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Email</label>
                            <div class="input-with-icon">
                                <i class="fas fa-envelope"></i>
                                <input type="email" 
                                       name="email" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
                                       placeholder="nama@example.com">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Employment Information Section -->
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-briefcase"></i>
                        Informasi Kepegawaian
                    </div>
                </div>
                <div class="card-body">
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label">Jabatan</label>
                            <input type="text" 
                                   name="jabatan" 
                                   class="form-input" 
                                   value="<?= htmlspecialchars($_POST['jabatan'] ?? '') ?>"
                                   list="jabatanList"
                                   placeholder="Pilih atau ketik jabatan">
                            <datalist id="jabatanList">
                                <?php foreach ($jabatanList as $j): ?>
                                <option value="<?= htmlspecialchars($j) ?>">
                                <?php endforeach; ?>
                            </datalist>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Kantor</label>
                            <input type="text" 
                                   name="kantor" 
                                   class="form-input" 
                                   value="<?= htmlspecialchars($_POST['kantor'] ?? '') ?>"
                                   list="kantorList"
                                   placeholder="Pilih atau ketik kantor">
                            <datalist id="kantorList">
                                <?php foreach ($kantorList as $k): ?>
                                <option value="<?= htmlspecialchars($k) ?>">
                                <?php endforeach; ?>
                            </datalist>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Tanggal Masuk</label>
                            <div class="input-with-icon">
                                <i class="fas fa-calendar-check"></i>
                                <input type="date" 
                                       name="tanggal_masuk" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['tanggal_masuk'] ?? '') ?>">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Education Information Section -->
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-graduation-cap"></i>
                        Informasi Pendidikan
                    </div>
                </div>
                <div class="card-body">
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label">Pendidikan Terakhir</label>
                            <select name="pendidikan" class="form-select">
                                <option value="">-- Pilih Pendidikan --</option>
                                <option value="SD" <?= ($_POST['pendidikan'] ?? '') === 'SD' ? 'selected' : '' ?>>SD</option>
                                <option value="SMP" <?= ($_POST['pendidikan'] ?? '') === 'SMP' ? 'selected' : '' ?>>SMP</option>
                                <option value="SMA/SMK" <?= ($_POST['pendidikan'] ?? '') === 'SMA/SMK' ? 'selected' : '' ?>>SMA/SMK</option>
                                <option value="D3" <?= ($_POST['pendidikan'] ?? '') === 'D3' ? 'selected' : '' ?>>D3</option>
                                <option value="D4" <?= ($_POST['pendidikan'] ?? '') === 'D4' ? 'selected' : '' ?>>D4</option>
                                <option value="S1" <?= ($_POST['pendidikan'] ?? '') === 'S1' ? 'selected' : '' ?>>S1</option>
                                <option value="S2" <?= ($_POST['pendidikan'] ?? '') === 'S2' ? 'selected' : '' ?>>S2</option>
                                <option value="S3" <?= ($_POST['pendidikan'] ?? '') === 'S3' ? 'selected' : '' ?>>S3</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Jurusan</label>
                            <div class="input-with-icon">
                                <i class="fas fa-book"></i>
                                <input type="text" 
                                       name="jurusan" 
                                       class="form-input" 
                                       value="<?= htmlspecialchars($_POST['jurusan'] ?? '') ?>"
                                       placeholder="Masukkan jurusan">
                            </div>
                        </div>
                    </div>

                    <!-- Form Actions -->
                    <div class="form-actions">
                        <a href="javascript:history.back()" class="btn btn-outline">
                            <i class="fas fa-times"></i>
                            Batal
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i>
                            Simpan Data
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>
</html>