<?php
// File: includes/upload_helper.php

/**
 * Upload Gambar dengan Opsi Resize & Convert
 */
function uploadImage($fileInfo, $targetDir, $prefix = 'img', $maxWidth = 800, $convertToWebP = true) {
    // 1. Validasi Basic
    if (empty($fileInfo['name']) || $fileInfo['error'] !== UPLOAD_ERR_OK) {
        return false;
    }

    // Pastikan folder ada
    if (!file_exists($targetDir)) {
        if (!mkdir($targetDir, 0755, true)) {
            throw new Exception("Gagal membuat folder upload: $targetDir");
        }
    }

    $ext = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
    $validExt = ['jpg', 'jpeg', 'png', 'webp', 'ico'];

    if (!in_array($ext, $validExt)) {
        throw new Exception("Format gambar tidak didukung (Gunakan JPG, PNG, WebP, ICO).");
    }

    // Validasi MIME type dari konten binary file (bukan dari nama file)
    $validMime = ['image/jpeg', 'image/png', 'image/webp', 'image/x-icon', 'image/vnd.microsoft.icon'];
    if (function_exists('finfo_open')) {
        $finfo    = finfo_open(FILEINFO_MIME_TYPE);
        $mimeReal = finfo_file($finfo, $fileInfo['tmp_name']);
        finfo_close($finfo);
        if (!in_array($mimeReal, $validMime)) {
            throw new Exception("File bukan gambar yang valid (MIME: $mimeReal). Upload gagal.");
        }
    }

    // 2. Load Gambar ke Memory
    $image = null;
    if ($ext == 'jpeg' || $ext == 'jpg') {
        $image = @imagecreatefromjpeg($fileInfo['tmp_name']);
    } elseif ($ext == 'png') {
        $image = @imagecreatefrompng($fileInfo['tmp_name']);
    } elseif ($ext == 'webp') {
        $image = @imagecreatefromwebp($fileInfo['tmp_name']);
    }

    // Fallback buat ICO atau gagal load
    if (!$image || $ext == 'ico') {
        $newFilename = $prefix . "_" . time() . "_" . uniqid() . "." . $ext;
        $destination = $targetDir . $newFilename;
        if (move_uploaded_file($fileInfo['tmp_name'], $destination)) {
            return str_replace('../', '', $destination);
        }
        return false;
    }

    // --- FIX ERROR: Palette image not supported by webp ---
    // Cek jika gambar bukan true color (misal PNG 8-bit), konversi dulu
    if (!imageistruecolor($image)) {
        imagepalettetotruecolor($image);
        imagealphablending($image, true);
        imagesavealpha($image, true);
    }
    // ------------------------------------------------------

    // 3. Resize Logic
    $width = imagesx($image);
    $height = imagesy($image);

    if ($width > $maxWidth) {
        $newWidth = $maxWidth;
        $newHeight = floor($height * ($maxWidth / $width));
        $tmpImage = imagecreatetruecolor($newWidth, $newHeight);

        // Handle Transparansi
        imagealphablending($tmpImage, false);
        imagesavealpha($tmpImage, true);
        $transparent = imagecolorallocatealpha($tmpImage, 255, 255, 255, 127);
        imagefilledrectangle($tmpImage, 0, 0, $newWidth, $newHeight, $transparent);

        imagecopyresampled($tmpImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        imagedestroy($image);
        $image = $tmpImage;
    }

    // 4. Simpan File
    if ($convertToWebP) {
        $newFilename = $prefix . "_" . time() . "_" . uniqid() . ".webp";
        $destination = $targetDir . $newFilename;
        // Simpan sebagai WebP
        $result = imagewebp($image, $destination, 85);
    } else {
        $newFilename = $prefix . "_" . time() . "_" . uniqid() . "." . $ext;
        $destination = $targetDir . $newFilename;
        
        if ($ext == 'png') {
            $result = imagepng($image, $destination, 9);
        } elseif ($ext == 'jpeg' || $ext == 'jpg') {
            $result = imagejpeg($image, $destination, 90);
        } else {
            $result = imagewebp($image, $destination, 90);
        }
    }
    
    imagedestroy($image);

    if ($result) {
        return str_replace('../', '', $destination);
    } else {
        throw new Exception("Gagal menyimpan gambar.");
    }
}

/**
 * Upload Video (MP4 Only - No Convert)
 */
function uploadVideo($fileInfo, $targetDir) {
    if (empty($fileInfo['name']) || $fileInfo['error'] !== UPLOAD_ERR_OK) return false;

    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0755, true);
    }

    $ext = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['mp4', 'webm', 'ogg'])) {
        throw new Exception("Format video harus MP4, WEBM, atau OGG.");
    }

    // Validasi MIME type video
    $validVideoMime = ['video/mp4', 'video/webm', 'video/ogg', 'application/ogg'];
    if (function_exists('finfo_open')) {
        $finfo    = finfo_open(FILEINFO_MIME_TYPE);
        $mimeReal = finfo_file($finfo, $fileInfo['tmp_name']);
        finfo_close($finfo);
        if (!in_array($mimeReal, $validVideoMime)) {
            throw new Exception("File bukan video yang valid (MIME: $mimeReal). Upload gagal.");
        }
    }

    $newFilename = "vid_" . time() . "_" . uniqid() . "." . $ext;
    $destination = $targetDir . $newFilename;

    if (move_uploaded_file($fileInfo['tmp_name'], $destination)) {
        return str_replace('../', '', $destination);
    }
    return false;
}

/**
 * Upload PDF (Khusus E-Brosur)
 */
function uploadPDF($fileInfo, $targetDir) {
    if ($fileInfo['error'] !== UPLOAD_ERR_OK) return false;
    
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0755, true);
    }

    $ext = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
    if ($ext !== 'pdf') throw new Exception("File harus berformat PDF.");

    // Validasi MIME type PDF
    if (function_exists('finfo_open')) {
        $finfo    = finfo_open(FILEINFO_MIME_TYPE);
        $mimeReal = finfo_file($finfo, $fileInfo['tmp_name']);
        finfo_close($finfo);
        if ($mimeReal !== 'application/pdf') {
            throw new Exception("File bukan PDF yang valid (MIME: $mimeReal). Upload gagal.");
        }
    }

    $newFilename = "brosur_" . time() . "_" . uniqid() . ".pdf";
    $destination = $targetDir . $newFilename;

    if (move_uploaded_file($fileInfo['tmp_name'], $destination)) {
        return str_replace('../', '', $destination);
    }
    throw new Exception("Gagal upload PDF.");
}

/**
 * Hapus File Lama dari Server
 */
function deleteFile($path) {
    if (empty($path)) return;
    $realPath = (strpos($path, '../') === 0) ? $path : '../' . $path;
    if (file_exists($realPath) && is_file($realPath)) {
        if (strpos($path, 'assets/') === false) {
            @unlink($realPath);
        }
    }
}
?>