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

function deleteOldFile($filename) {
    $upload_dir = '../../assets/images/uploads/';
    if (!empty($filename) && file_exists($upload_dir . $filename) && $filename != 'default.png') {
        unlink($upload_dir . $filename);
    }
}

// ==================== PROSES EDIT SEMINAR ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_seminar'])) {
    $id = (int)$_POST['id'];
    
    // 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']);
    
    // Ambil data gambar lama
    $gambar_query = mysql_query("SELECT gambar FROM seminar WHERE id = '$id'");
    $gambar_data = mysql_fetch_assoc($gambar_query);
    $gambar = $gambar_data['gambar'];
    
    // Proses upload gambar baru
    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)) {
            // Hapus file lama jika ada
            if (!empty($gambar)) {
                deleteOldFile($gambar);
            }
            
            $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 (kecuali untuk data ini sendiri)
    $check_query = mysql_query("SELECT id FROM seminar WHERE kode_seminar = '$kode_seminar' AND id != '$id'");
    if (mysql_num_rows($check_query) > 0) {
        $errors[] = "Kode seminar sudah digunakan";
    }
    
    if (empty($errors)) {
        // Update database
        $update_query = "UPDATE 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',
            updated = NOW()
            WHERE id = '$id'";
        
        if (mysql_query($update_query)) {
            $_SESSION['success_message'] = "Seminar berhasil diperbarui!";
            echo "<script>window.location.href = 'seminars-edit&?id=$id';</script>";
            exit();
        } else {
            $_SESSION['error_message'] = "Gagal menyimpan seminar: " . mysql_error();
        }
    } else {
        $_SESSION['error_message'] = implode("<br>", $errors);
    }
}

// ==================== AMBIL DATA SEMINAR ====================
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$copy_mode = isset($_GET['copy']) ? true : false;
$seminar = null;

if ($id > 0) {
    $query = mysql_query("SELECT * FROM seminar WHERE id = '$id'");
    if (mysql_num_rows($query) > 0) {
        $seminar = mysql_fetch_assoc($query);
        if ($copy_mode) {
            // Untuk copy mode, generate kode baru
            $seminar['kode_seminar'] = 'SEM-' . date('ym-dHis').rand(10,99);
            $seminar['judul'] = $seminar['judul'] . ' (Copy)';
            $seminar['aktif'] = 'Y'; // Aktif saat copy
            $seminar['gambar'] = ''; // Kosongkan gambar saat copy
        }
    } else {
        $_SESSION['error_message'] = "Seminar tidak ditemukan!";
        header("Location: seminars-manage/");
        exit();
    }
} else {
    $_SESSION['error_message'] = "ID seminar tidak valid!";
    header("Location: seminars-manage/");
    exit();
}
?>
<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);
    }
    
    .seminar-header {
        background: linear-gradient(135deg, #4361ee 0%, #3a56d4 100%);
        border-radius: var(--border-radius);
        padding: 2rem;
        color: white;
        margin-bottom: 2rem;
    }
    
    .seminar-header h3 {
        font-weight: 700;
        margin-bottom: 0.5rem;
    }
    
    .seminar-meta {
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
        margin-top: 1rem;
    }
    
    .meta-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .image-preview {
        max-height: 150px;
        margin-top: 10px;
        display: none;
        border-radius: var(--border-radius);
        border: 1px solid var(--gray-300);
    }
    
    .current-image {
        max-height: 150px;
        border-radius: var(--border-radius);
        border: 1px solid var(--gray-300);
        margin-top: 10px;
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1"><?php echo $copy_mode ? 'Duplikat Seminar' : 'Edit Seminar'; ?></h4>
        <p class="text-muted mb-0">Edit data seminar yang sudah ada</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>

<!-- ==================== HEADER SEMINAR ==================== -->
<div class="seminar-header">
    <div class="d-flex justify-content-between align-items-start">
        <div>
            <h3><?php echo htmlspecialchars($seminar['judul']); ?></h3>
            <p class="mb-0"><?php echo htmlspecialchars($seminar['kode_seminar']); ?></p>
        </div>
        <div class="text-end">
            <?php if ($seminar['aktif'] == 'Y'): ?>
                <span class="badge bg-success bg-opacity-25 border border-success px-3 py-2">Aktif</span>
            <?php else: ?>
                <span class="badge bg-secondary bg-opacity-25 border border-secondary px-3 py-2">Non-Aktif</span>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="seminar-meta">
        <div class="meta-item">
            <i data-lucide="calendar" width="16"></i>
            <?php echo date('d M Y, H:i', strtotime($seminar['waktu_mulai'])); ?>
        </div>
        <div class="meta-item">
            <i data-lucide="user" width="16"></i>
            <?php echo htmlspecialchars($seminar['pemateri']); ?>
        </div>
        <div class="meta-item">
            <i data-lucide="video" width="16"></i>
            <?php echo ucfirst($seminar['metode']); ?>
        </div>
        <div class="meta-item">
            <i data-lucide="" width="16"></i>
            Rp <?php echo number_format($seminar['biaya_umum'], 0, ',', '.'); ?>
        </div>
    </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; ?>

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

<form method="POST" action="" enctype="multipart/form-data">
    <input type="hidden" name="id" value="<?php echo $seminar['id']; ?>">
    
    <!-- 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 htmlspecialchars($seminar['kode_seminar']); ?>" required>
            </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 $seminar['aktif'] == 'Y' ? 'selected' : ''; ?>>Aktif</option>
                    <option value="T" <?php echo $seminar['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 htmlspecialchars($seminar['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 htmlspecialchars($seminar['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>
                <?php
                $waktu_mulai = strtotime($seminar['waktu_mulai']);
                $waktu_akhir = strtotime($seminar['waktu_akhir']);
                ?>
                <input type="datetime-local" class="form-control" name="waktu_mulai" 
                       value="<?php echo date('Y-m-d\TH:i', $waktu_mulai); ?>" 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 date('Y-m-d\TH:i', $waktu_akhir); ?>" 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 $seminar['metode'] == 'online' ? 'selected' : ''; ?>>Online</option>
                    <option value="offline" <?php echo $seminar['metode'] == 'offline' ? 'selected' : ''; ?>>Offline</option>
                    <option value="hybrid" <?php echo $seminar['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 (int)$seminar['jml_jam']; ?>" 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 (int)$seminar['jml_hari']; ?>" 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 (int)$seminar['biaya_umum']; ?>" 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 (int)$seminar['biaya_anggota']; ?>" 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 htmlspecialchars($seminar['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/*" onchange="previewImage(this, 'imagePreview')">
                <?php if (!empty($seminar['gambar'])): ?>
                <div class="mt-2">
                    <small class="text-muted d-block">Gambar saat ini:</small>
                    <img src="<?= $http ?>assets/images/uploads/<?php echo htmlspecialchars($seminar['gambar']); ?>" 
                         alt="Gambar Seminar" class="current-image"></br>
                </div>
                <?php endif; ?>
                <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="input-group">
                    <span class="input-group-text"><i data-lucide="file-text" width="16"></i></span>
                    <input type="text" class="form-control" name="link_materi" value="<?php echo htmlspecialchars($seminar['link_materi']); ?>">
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Link Video</label>
                <div class="input-group">
                    <span class="input-group-text"><i data-lucide="video" width="16"></i></span>
                    <input type="text" class="form-control" name="link_video" value="<?php echo htmlspecialchars($seminar['link_video']); ?>">
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Link Zoom/Meeting</label>
                <div class="input-group">
                    <span class="input-group-text"><i data-lucide="video" width="16"></i></span>
                    <input type="text" class="form-control" name="link_zoom" value="<?php echo htmlspecialchars($seminar['link_zoom']); ?>">
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Link Group WhatsApp</label>
                <div class="input-group">
                    <span class="input-group-text"><i data-lucide="message-circle" width="16"></i></span>
                    <input type="text" class="form-control" name="link_groupwa" value="<?php echo htmlspecialchars($seminar['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 htmlspecialchars($seminar['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 htmlspecialchars($seminar['wa_cp']); ?>">
            </div>
        </div>
    </div>

    <!-- TOMBOL AKSI -->
    <div class="d-flex justify-content-between mt-4">
        <div>
            <a href="seminars-manage/" class="btn btn-outline-secondary">
                <i data-lucide="x" width="16"></i>
                Batal
            </a>
            <?php if (!$copy_mode): ?>
            <a href="seminars-manage?delete=<?php echo $seminar['id']; ?>" class="btn btn-outline-danger" 
               onclick="return confirm('Hapus seminar ini?')">
                <i data-lucide="trash-2" width="16"></i>
                Hapus
            </a>
            <?php endif; ?>
        </div>
        <div>
            <?php if (!$copy_mode) { ?>
            <a href="seminars-edit?id=<?php echo $seminar['id']; ?>&copy=1" class="btn btn-outline-info me-2">
                <i data-lucide="copy" width="16"></i>
                Duplikat
            </a>
            <?php } ?>
            <button type="submit" name="save_seminar" class="btn btn-primary btn-lg">
                <i data-lucide="save" width="18"></i>
                <?php echo $copy_mode ? 'Simpan Duplikat' : 'Simpan Perubahan';?>
            </button>
        </div>
    </div>
</form>

<script>
// Inisialisasi icons
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // Preview waktu
    const waktuMulai = document.querySelector('input[name="waktu_mulai"]');
    const waktuAkhir = document.querySelector('input[name="waktu_akhir"]');
    
    function formatDateTimePreview() {
        const mulai = new Date(waktuMulai.value);
        const akhir = new Date(waktuAkhir.value);
        
        if (waktuMulai.value && waktuAkhir.value) {
            const options = { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            };
            
            console.log('Seminar akan berlangsung dari:', mulai.toLocaleDateString('id-ID', options), 'hingga', akhir.toLocaleDateString('id-ID', options));
        }
    }
    
    waktuMulai.addEventListener('change', formatDateTimePreview);
    waktuAkhir.addEventListener('change', formatDateTimePreview);
});

// 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>