<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

require_once "koneksi.php";

$uploadDir = "../uploads/";
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$judul = $_POST['judul'] ?? '';
$keterangan = $_POST['keterangan'] ?? '';

if (empty($judul) || empty($keterangan)) {
    echo json_encode(["status" => false, "msg" => "Judul dan keterangan wajib diisi"]);
    exit;
}

$gambarPath = null;
$videoPath = null;

// Upload gambar
if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] === UPLOAD_ERR_OK) {
    $ext = pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION);
    $namaFile = time() . "_img." . $ext;
    $target = $uploadDir . $namaFile;
    if (move_uploaded_file($_FILES['gambar']['tmp_name'], $target)) {
        $gambarPath = "https://netrapay.xyz/Informasi/uploads/" . $namaFile;
    }
}

// Upload video
if (isset($_FILES['video']) && $_FILES['video']['error'] === UPLOAD_ERR_OK) {
    $ext = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
    $namaFile = time() . "_vid." . $ext;
    $target = $uploadDir . $namaFile;
    if (move_uploaded_file($_FILES['video']['tmp_name'], $target)) {
        $videoPath = "https://netrapay.xyz/Informasi/uploads/" . $namaFile;
    }
}

$stmt = $conn->prepare("INSERT INTO informasi (judul, keterangan, foto, video, created_at) VALUES (?, ?, ?, ?, NOW())");
$stmt->bind_param("ssss", $judul, $keterangan, $gambarPath, $videoPath);

if ($stmt->execute()) {
    echo json_encode(["status" => true, "msg" => "Upload berhasil"]);
} else {
    echo json_encode(["status" => false, "msg" => "Gagal menyimpan ke database: " . $conn->error]);
}

$stmt->close();
$conn->close();
?>