<?php
// ==================== FUNGSI BANTU ====================
function generateFileName($originalName) {
    $extension = pathinfo($originalName, PATHINFO_EXTENSION);
    $date = date('YmdHis');
    $random = rand(10000, 99999);
    return $date . $random . '.' . $extension;
}

// ==================== PROSES SIMPAN SEMINAR BARU ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_seminar'])) {
    // Konfigurasi upload
    $upload_dir = '../../assets/images/uploads/';
    
    // Buat direktori jika belum ada
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Ambil semua data dari form
    $kode_seminar = mysql_real_escape_string($_POST['kode_seminar']);
    $judul = mysql_real_escape_string($_POST['judul']);
    $deskripsi = mysql_real_escape_string($_POST['deskripsi']);
    $waktu_mulai = mysql_real_escape_string($_POST['waktu_mulai']);
    $waktu_akhir = mysql_real_escape_string($_POST['waktu_akhir']);
    $metode = mysql_real_escape_string($_POST['metode']);
    $biaya_umum = (int)$_POST['biaya_umum'];
    $biaya_anggota = (int)$_POST['biaya_anggota'];
    $pemateri = mysql_real_escape_string($_POST['pemateri']);
    $jml_jam = (int)$_POST['jml_jam'];
    $jml_hari = (int)$_POST['jml_hari'];
    $link_materi = mysql_real_escape_string($_POST['link_materi']);
    $link_video = mysql_real_escape_string($_POST['link_video']);
    $link_zoom = mysql_real_escape_string($_POST['link_zoom']);
    $link_groupwa = mysql_real_escape_string($_POST['link_groupwa']);
    $nama_cp = mysql_real_escape_string($_POST['nama_cp']);
    $wa_cp = mysql_real_escape_string($_POST['wa_cp']);
    $aktif = mysql_real_escape_string($_POST['aktif']);
    
    // Inisialisasi variabel gambar
    $gambar = '';
    
    // Proses upload gambar
    if (!empty($_FILES['gambar_file']['name'])) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
        $file_type = $_FILES['gambar_file']['type'];
        
        if (in_array($file_type, $allowed_types)) {
            $gambar_filename = generateFileName($_FILES['gambar_file']['name']);
            $gambar_tmp = $_FILES['gambar_file']['tmp_name'];
            $gambar_path = $upload_dir . $gambar_filename;
            
            if (move_uploaded_file($gambar_tmp, $gambar_path)) {
                $gambar = $gambar_filename;
            } else {
                $_SESSION['error_message'] = "Gagal upload gambar seminar!";
            }
        } else {
            $_SESSION['error_message'] = "Format file tidak didukung! Gunakan JPG, PNG, atau GIF.";
        }
    }
    
    // Validasi
    $errors = [];
    
    if (empty($kode_seminar)) $errors[] = "Kode seminar wajib diisi";
    if (empty($judul)) $errors[] = "Judul seminar wajib diisi";
    if (empty($waktu_mulai)) $errors[] = "Waktu mulai wajib diisi";
    if (empty($waktu_akhir)) $errors[] = "Waktu akhir wajib diisi";
    if (empty($metode)) $errors[] = "Metode seminar wajib dipilih";
    
    // Cek kode seminar unik
    $check_query = mysql_query("SELECT id FROM seminar WHERE kode_seminar = '$kode_seminar'");
    if (mysql_num_rows($check_query) > 0) {
        $errors[] = "Kode seminar sudah digunakan";
    }
    
    if (empty($errors)) {
        // Insert ke database
        $insert_query = "INSERT INTO seminar SET
            kode_seminar = '$kode_seminar',
            judul = '$judul',
            deskripsi = '$deskripsi',
            waktu_mulai = '$waktu_mulai',
            waktu_akhir = '$waktu_akhir',
            metode = '$metode',
            biaya_umum = '$biaya_umum',
            biaya_anggota = '$biaya_anggota',
            pemateri = '$pemateri',
            jml_jam = '$jml_jam',
            jml_hari = '$jml_hari',
            link_materi = '$link_materi',
            link_video = '$link_video',
            link_zoom = '$link_zoom',
            link_groupwa = '$link_groupwa',
            nama_cp = '$nama_cp',
            wa_cp = '$wa_cp',
            aktif = '$aktif',
            gambar = '$gambar',
            created = NOW(),
            updated = NOW()";
        
        if (mysql_query($insert_query)) {
            $new_id = mysql_insert_id();
            $_SESSION['success_message'] = "Seminar berhasil ditambahkan!";
            echo "<script>window.location.href = 'seminars-edit&id=$new_id';</script>";
            exit();
        } else {
            $_SESSION['error_message'] = "Gagal menyimpan seminar: " . mysql_error();
        }
    } else {
        $_SESSION['error_message'] = implode("<br>", $errors);
    }
}
?>
<style>
    .form-section {
        background: var(--gray-50);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .form-section h6 {
        border-bottom: 2px solid var(--primary-color);
        padding-bottom: 0.5rem;
        margin-bottom: 1.5rem;
        color: var(--gray-700);
    }
    
    .time-inputs {
        display: flex;
        gap: 10px;
        align-items: center;
    }
    
    .time-inputs .form-control {
        flex: 1;
    }
    
    .link-input-group {
        position: relative;
    }
    
    .link-input-group .form-control {
        padding-left: 40px;
    }
    
    .link-input-group i {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--gray-500);
    }
    
    .image-preview {
        max-height: 150px;
        margin-top: 10px;
        display: none;
        border-radius: var(--border-radius);
        border: 1px solid var(--gray-300);
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1">Tambah Seminar Baru</h4>
        <p class="text-muted mb-0">Tambah data seminar atau workshop baru</p>
    </div>
    <div>
        <a href="seminars-manage/" class="btn btn-outline-secondary">
            <i data-lucide="arrow-left" width="16"></i>
            Kembali ke Daftar
        </a>
    </div>
</div>

<!-- ==================== NOTIFIKASI ==================== -->
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
    <i data-lucide="alert-circle" class="me-2"></i>
    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<form method="POST" action="" enctype="multipart/form-data">
    <!-- INFORMASI DASAR -->
    <div class="form-section">
        <h6>Informasi Dasar</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label fw-medium">Kode Seminar *</label>
                <input type="text" class="form-control" name="kode_seminar" value="<?php echo isset($_POST['kode_seminar']) ? htmlspecialchars($_POST['kode_seminar']) : 'SEM-' . date('ym-dHis').rand(10,99); ?>" required>
                <small class="text-muted">Kode unik untuk seminar (contoh: SEM-2601-12001199)</small>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Status *</label>
                <select class="form-select" name="aktif" required>
                    <option value="Y" <?php echo (isset($_POST['aktif']) && $_POST['aktif'] == 'Y') || !isset($_POST['aktif']) ? 'selected' : ''; ?>>Aktif</option>
                    <option value="T" <?php echo isset($_POST['aktif']) && $_POST['aktif'] == 'T' ? 'selected' : ''; ?>>Non-Aktif</option>
                </select>
            </div>
            <div class="col-12">
                <label class="form-label fw-medium">Judul Seminar *</label>
                <input type="text" class="form-control" name="judul" value="<?php echo isset($_POST['judul']) ? htmlspecialchars($_POST['judul']) : ''; ?>" required>
            </div>
            <div class="col-12">
                <label class="form-label fw-medium">Deskripsi</label>
                <textarea class="form-control" name="deskripsi" rows="4"><?php echo isset($_POST['deskripsi']) ? htmlspecialchars($_POST['deskripsi']) : ''; ?></textarea>
            </div>
        </div>
    </div>

    <!-- WAKTU DAN METODE -->
    <div class="form-section">
        <h6>Waktu dan Metode</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label fw-medium">Waktu Mulai *</label>
                <input type="datetime-local" class="form-control" name="waktu_mulai" value="<?php echo isset($_POST['waktu_mulai']) ? htmlspecialchars($_POST['waktu_mulai']) : date('Y-m-d\TH:i'); ?>" required>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Waktu Akhir *</label>
                <input type="datetime-local" class="form-control" name="waktu_akhir" value="<?php echo isset($_POST['waktu_akhir']) ? htmlspecialchars($_POST['waktu_akhir']) : date('Y-m-d\TH:i', strtotime('+2 hours')); ?>" required>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Metode *</label>
                <select class="form-select" name="metode" required>
                    <option value="online" <?php echo (isset($_POST['metode']) && $_POST['metode'] == 'online') || !isset($_POST['metode']) ? 'selected' : ''; ?>>Online</option>
                    <option value="offline" <?php echo isset($_POST['metode']) && $_POST['metode'] == 'offline' ? 'selected' : ''; ?>>Offline</option>
                    <option value="hybrid" <?php echo isset($_POST['metode']) && $_POST['metode'] == 'hybrid' ? 'selected' : ''; ?>>Hybrid</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label fw-medium">Jumlah Jam</label>
                <input type="number" class="form-control" name="jml_jam" value="<?php echo isset($_POST['jml_jam']) ? (int)$_POST['jml_jam'] : 2; ?>" min="1">
            </div>
            <div class="col-md-3">
                <label class="form-label fw-medium">Jumlah Hari</label>
                <input type="number" class="form-control" name="jml_hari" value="<?php echo isset($_POST['jml_hari']) ? (int)$_POST['jml_hari'] : 1; ?>" min="1">
            </div>
        </div>
    </div>

    <!-- BIAYA -->
    <div class="form-section">
        <h6>Biaya Seminar</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label fw-medium">Biaya Umum (Rp)</label>
                <input type="number" class="form-control" name="biaya_umum" value="<?php echo isset($_POST['biaya_umum']) ? (int)$_POST['biaya_umum'] : 0; ?>" min="0">
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Biaya Anggota (Rp)</label>
                <input type="number" class="form-control" name="biaya_anggota" value="<?php echo isset($_POST['biaya_anggota']) ? (int)$_POST['biaya_anggota'] : 0; ?>" min="0">
            </div>
        </div>
    </div>

    <!-- PEMATERI -->
    <div class="form-section">
        <h6>Informasi Pemateri</h6>
        <div class="row g-3">
            <div class="col-12">
                <label class="form-label fw-medium">Nama Pemateri</label>
                <input type="text" class="form-control" name="pemateri" value="<?php echo isset($_POST['pemateri']) ? htmlspecialchars($_POST['pemateri']) : ''; ?>">
            </div>
        </div>
    </div>

    <!-- LINK DAN MEDIA -->
    <div class="form-section">
        <h6>Link dan Media</h6>
        <div class="row g-3">
            <div class="col-12">
                <label class="form-label fw-medium">Gambar Seminar *</label>
                <input type="file" class="form-control" name="gambar_file" accept="image/*" required onchange="previewImage(this, 'imagePreview')">
                <img id="imagePreview" class="image-preview" src="" alt="Preview">
                <small class="text-muted">Format: JPG, PNG, GIF. Maksimal 2MB</small>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Link Materi</label>
                <div class="link-input-group">
                    <input type="text" class="form-control" style="padding-left:15px" name="link_materi" value="<?php echo isset($_POST['link_materi']) ? htmlspecialchars($_POST['link_materi']) : ''; ?>">
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Link Video</label>
                <div class="link-input-group">
                    <input type="text" class="form-control" style="padding-left:15px" name="link_video" value="<?php echo isset($_POST['link_video']) ? htmlspecialchars($_POST['link_video']) : ''; ?>">
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Link Zoom/Meeting</label>
                <div class="link-input-group">
                    <input type="text" class="form-control" style="padding-left:15px" name="link_zoom" value="<?php echo isset($_POST['link_zoom']) ? htmlspecialchars($_POST['link_zoom']) : ''; ?>">
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Link Group WhatsApp</label>
                <div class="link-input-group">
                    <input type="text" class="form-control" style="padding-left:15px" name="link_groupwa" value="<?php echo isset($_POST['link_groupwa']) ? htmlspecialchars($_POST['link_groupwa']) : ''; ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- KONTAK PERSON -->
    <div class="form-section">
        <h6>Kontak Person</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label fw-medium">Nama CP</label>
                <input type="text" class="form-control" name="nama_cp" value="<?php echo isset($_POST['nama_cp']) ? htmlspecialchars($_POST['nama_cp']) : ''; ?>">
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">WhatsApp CP</label>
                <input type="text" class="form-control" name="wa_cp" value="<?php echo isset($_POST['wa_cp']) ? htmlspecialchars($_POST['wa_cp']) : ''; ?>">
            </div>
        </div>
    </div>

    <!-- TOMBOL AKSI -->
    <div class="d-flex justify-content-between mt-4">
        <a href="seminars-manage/" class="btn btn-outline-secondary">
            <i data-lucide="x" width="16"></i>
            Batal
        </a>
        <button type="submit" name="save_seminar" class="btn btn-primary btn-lg">
            <i data-lucide="save" width="18"></i>
            Simpan Seminar
        </button>
    </div>
</form>

<script>
// Inisialisasi icons
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // Auto generate kode seminar jika kosong
    const kodeInput = document.querySelector('input[name="kode_seminar"]');
    if (!kodeInput.value) {
        const now = new Date();
        const timestamp = now.getFullYear().toString() + 
                         (now.getMonth() + 1).toString().padStart(2, '0') + 
                         now.getDate().toString().padStart(2, '0') + '-' +
                         now.getHours().toString().padStart(2, '0') + 
                         now.getMinutes().toString().padStart(2, '0') + 
                         now.getSeconds().toString().padStart(2, '0');
        kodeInput.value = 'SEM-' + timestamp;
    }
});

// Preview gambar sebelum upload
function previewImage(input, previewId) {
    const preview = document.getElementById(previewId);
    const file = input.files[0];
    
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
}
</script>