<?php
include 'koneksi.php';

if(isset($_POST['submit'])){
    
    // Ambil data dari form
    $nama = mysqli_real_escape_string($koneksi, $_POST['nama']);
    $email = mysqli_real_escape_string($koneksi, $_POST['email']);
    $no_hp = mysqli_real_escape_string($koneksi, $_POST['no_hp']);
    $kategori = mysqli_real_escape_string($koneksi, $_POST['kategori']);
    $judul = mysqli_real_escape_string($koneksi, $_POST['judul']);
    $pesan = mysqli_real_escape_string($koneksi, $_POST['pesan']);
    
    // Proses upload lampiran
    $lampiran = '';
    if(isset($_FILES['lampiran']) && $_FILES['lampiran']['error'] == 0){
        $target_dir = "uploads/pengaduan/";
        
        // Buat folder jika belum ada
        if(!file_exists($target_dir)){
            mkdir($target_dir, 0777, true);
        }
        
        $file_extension = pathinfo($_FILES['lampiran']['name'], PATHINFO_EXTENSION);
        $lampiran = time() . '_' . uniqid() . '.' . $file_extension;
        $target_file = $target_dir . $lampiran;
        
        // Cek ukuran file (max 5MB)
        if($_FILES['lampiran']['size'] <= 5 * 1024 * 1024){
            move_uploaded_file($_FILES['lampiran']['tmp_name'], $target_file);
        }
    }
    
    // Simpan ke database
    $query = "INSERT INTO pengaduan (nama, email, no_hp, kategori, judul, pesan, lampiran) 
              VALUES ('$nama', '$email', '$no_hp', '$kategori', '$judul', '$pesan', '$lampiran')";
    
    if(mysqli_query($koneksi, $query)){
        // Redirect dengan status sukses
        header("Location: pengaduan.php?status=success");
    } else {
        // Redirect dengan status error
        header("Location: pengaduan.php?status=error");
    }
    exit();
} else {
    // Jika tidak ada submit, redirect ke halaman pengaduan
    header("Location: pengaduan.php");
    exit();
}
?>