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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Metode request tidak valid']);
    exit;
}

$id_event = (int)$_POST['id_event'] ?? 0;
$description = $_POST['description'] ?? '';

// Validasi
if (empty($id_event)) {
    echo json_encode(['success' => false, 'message' => 'ID Event tidak valid']);
    exit;
}

// Handle upload
$uploadDir = '../uploads/event_foto/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$uploadedFiles = [];
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 200 * 1024; // 2MB

foreach ($_FILES['photos']['tmp_name'] as $key => $tmpName) {
    $fileName = $_FILES['photos']['name'][$key];
    $fileSize = $_FILES['photos']['size'][$key];
    $fileType = $_FILES['photos']['type'][$key];
    $error = $_FILES['photos']['error'][$key];
    
    // Validasi
    if ($error !== UPLOAD_ERR_OK) {
        continue;
    }
    
    if (!in_array($fileType, $allowedTypes)) {
        continue;
    }
    
    if ($fileSize > $maxSize) {
        continue;
    }
    
    // Generate nama file unik
    $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = 'event_' . $id_event . '_' . uniqid() . '.' . $fileExt;
    $destination = $uploadDir . $newFileName;
    
    if (move_uploaded_file($tmpName, $destination)) {
        $uploadedFiles[] = $newFileName;
        
        // Simpan ke database
        $stmt = $conn->prepare("INSERT INTO dafdir_event_foto (id_event, nama_file, deskripsi) VALUES (?, ?, ?)");
        $stmt->bind_param("iss", $id_event, $newFileName, $description);
        $stmt->execute();
        $stmt->close();
    }
}

if (empty($uploadedFiles)) {
    echo json_encode(['success' => false, 'message' => 'Tidak ada foto yang berhasil diupload / Ukuran file foto terlalu besar']);
} else {
    echo json_encode(['success' => true, 'message' => 'Foto berhasil diupload']);
}
?>