<?php
include '../includes/auth.php';
include '../includes/functions.php';

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $eventId = (int)$_POST['id_event'];
    $description = $conn->real_escape_string($_POST['description'] ?? '');
    
    // Check if file was uploaded
    if (isset($_FILES['undangan']) && $_FILES['undangan']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['undangan'];
        
        // Validate file size (max 2kb)
        if ($file['size'] > 204800) {
            $response['message'] = 'Ukuran file terlalu besar (maksimal 200kb)';
            echo json_encode($response);
            exit;
        }
        
        // Validate file type
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        if (!in_array($file['type'], $allowedTypes)) {
            $response['message'] = 'Format file tidak didukung (hanya JPG, PNG, GIF, PDF)';
            echo json_encode($response);
            exit;
        }
        
        // Create upload directory if not exists
        $uploadDir = '../uploads/event_undangan/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        // Generate unique filename
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'undangan_' . $eventId . '_' . time() . '.' . $ext;
        $destination = $uploadDir . $filename;
        
        if (move_uploaded_file($file['tmp_name'], $destination)) {
            // Save to database
            $stmt = $conn->prepare("INSERT INTO dafdir_event_undangan (id_event, nama_file, deskripsi) VALUES (?, ?, ?)");
            $stmt->bind_param("iss", $eventId, $filename, $description);
            
            if ($stmt->execute()) {
                $response['success'] = true;
                $response['message'] = 'Undangan berhasil diupload';
            } else {
                unlink($destination); // Delete the file if db insert fails
                $response['message'] = 'Gagal menyimpan data undangan';
            }
            
            $stmt->close();
        } else {
            $response['message'] = 'Gagal mengupload file';
        }
    } else {
        $response['message'] = 'Tidak ada file yang diupload atau terjadi error';
    }
}

header('Content-Type: application/json');
echo json_encode($response);
?>