<?php
//require_once 'api_config.php';
require_once '/etc/jgec_api_config.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

// ============================================
// UPLOAD API
// ============================================
if ($method === 'POST' && $action === 'upload') {
    $api_key = isset($_SERVER['HTTP_X_API_KEY']) ? $_SERVER['HTTP_X_API_KEY'] : '';
    
    if ($api_key !== API_KEY) {
        api_response(false, 'Invalid API Key');
    }
    
    $folder = isset($_POST['folder']) ? $_POST['folder'] : '';
    if (!in_array($folder, ALLOWED_FOLDERS)) {
        api_response(false, 'Invalid folder. Allowed: ' . implode(', ', ALLOWED_FOLDERS));
    }
    
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        api_response(false, 'No file uploaded or upload error');
    }
    
    $file = $_FILES['file'];
    $original_name = basename($file['name']);

    // --- TAMBAHKAN KODE INI (Validasi Ekstensi & Ukuran) ---
    $allowed_ext = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'ppt', 'pptx', 'xlsx', 'xls'];
    $extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
    
    if (!in_array($extension, $allowed_ext)) {
        api_response(false, 'Tipe file tidak diizinkan. Hanya PDF, Gambar, dan Dokumen Office.');
    }


    // --- TAMBAHKAN KODE BARU INI (Validasi MIME Type Asli) ---
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    $allowed_mimes = [
        'application/pdf', 
        'image/jpeg', 
        'image/png', 
        'application/msword', 
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];

    if (!in_array($mime_type, $allowed_mimes)) {
        api_response(false, 'Isi file tidak sesuai dengan ekstensinya. File ditolak.');
    }
    // ---------------------------------------------------------

    // Batasi ukuran file maksimal 10MB (10 * 1024 * 1024)
    if ($file['size'] > 10485760) {
        api_response(false, 'Ukuran file terlalu besar. Maksimal 10MB.');
    }
    // ---------------------------------------------------------


    $target_dir = BASE_DIR . '/' . $folder;
    
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
        chown($target_dir, 'www-data');
        chgrp($target_dir, 'www-data');
    }
    
    $extension = pathinfo($original_name, PATHINFO_EXTENSION);
    $basename = pathinfo($original_name, PATHINFO_FILENAME);
    $unique_name = $basename . '_' . time() . '.' . $extension;
    $target_file = $target_dir . '/' . $unique_name;
    
    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        chmod($target_file, 0644);
        chown($target_file, 'www-data');
        chgrp($target_file, 'www-data');
        
        $download_url = BASE_URL . '/api.php?action=download&folder=' . $folder . '&file=' . $unique_name;
        
        api_response(true, 'File uploaded successfully', [
            'filename' => $unique_name,
            'original_name' => $original_name,
            'folder' => $folder,
            'size' => $file['size'],
            'download_url' => $download_url
        ]);
    } else {
        api_response(false, 'Failed to move uploaded file');
    }
}

// ============================================
// DOWNLOAD API (GET - Menampilkan Form atau Download Langsung)
// ============================================
if ($method === 'GET' && $action === 'download') {
    $folder = isset($_GET['folder']) ? $_GET['folder'] : '';
    $file = isset($_GET['file']) ? $_GET['file'] : '';
    $password = isset($_GET['password']) ? $_GET['password'] : '';

    // Validasi dasar untuk mencegah directory traversal
    if (empty($folder) || empty($file) || strpos($file, '..') !== false || strpos($file, '/') !== false) {
        api_response(false, 'Invalid folder or filename');
    }

    $filepath = BASE_DIR . '/' . $folder . '/' . $file;

    // Jika password disediakan via URL (untuk kompatibilitas API/Scriptcase)
    if (!empty($password)) {
        if ($password !== API_PASSWORD) {
            api_response(false, 'Invalid password');
        }
        if (!in_array($folder, ALLOWED_FOLDERS) || !file_exists($filepath)) {
            api_response(false, 'File not found');
        }
        
        // Serve file
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
        header('Content-Length: ' . filesize($filepath));
        header('Cache-Control: no-cache');
        readfile($filepath);
        exit;
    }

    // Jika TIDAK ada password di URL, tampilkan Dialog Box HTML
    if (!in_array($folder, ALLOWED_FOLDERS) || !file_exists($filepath)) {
        api_response(false, 'File not found or invalid folder');
    }

    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html>
    <html lang="id">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JGEC Media File Manager</title>
        <style>
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f2f5; margin: 0; }
            .dialog { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); text-align: center; width: 320px; }
            .dialog h2 { margin-top: 0; color: #1a1a1a; font-size: 20px; }
            .dialog p { color: #666; font-size: 14px; margin-bottom: 20px; word-break: break-all; }
            .dialog input[type="password"] { width: 100%; padding: 12px; margin-bottom: 20px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; outline: none; transition: border 0.2s; }
            .dialog input[type="password"]:focus { border-color: #007bff; }
            .dialog button { width: 100%; padding: 12px; background-color: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.2s; }
            .dialog button:hover { background-color: #0056b3; }
            .error { color: #dc3545; margin-bottom: 15px; font-size: 14px; font-weight: 500; background: #f8d7da; padding: 10px; border-radius: 6px; }
            .logo { max-width: 120px; margin-bottom: 20px; }
        </style>
    </head>
    <body>
        <div class="dialog">
            <img src="/assets/logo.png" alt="Logo" class="logo" onerror="this.style.display=\'none\'">
            <h2>🔒 JGEC Protected Download</h2>
            <p>File: <strong>' . htmlspecialchars($file) . '</strong></p>
            ' . (isset($_GET['error']) ? '<div class="error">Password salah! Silakan coba lagi.</div>' : '') . '
            <form method="POST" action="">
                <input type="hidden" name="action" value="download">
                <input type="hidden" name="folder" value="' . htmlspecialchars($folder) . '">
                <input type="hidden" name="file" value="' . htmlspecialchars($file) . '">
                <input type="password" name="password" placeholder="Masukkan Password" required autofocus autocomplete="off">
                <button type="submit">Download File</button>
            </form>
        </div>
    </body>
    </html>';
    exit;
}

// ============================================
// DOWNLOAD API (POST - Menerima Password dari Form)
// ============================================
if ($method === 'POST' && $action === 'download') {
    $folder = isset($_POST['folder']) ? $_POST['folder'] : '';
    $file = isset($_POST['file']) ? $_POST['file'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    if ($password !== API_PASSWORD) {
        // Redirect kembali ke form dengan pesan error
        header('Location: ?action=download&folder=' . urlencode($folder) . '&file=' . urlencode($file) . '&error=1');
        exit;
    }

    $filepath = BASE_DIR . '/' . $folder . '/' . $file;
    
    if (!in_array($folder, ALLOWED_FOLDERS) || !file_exists($filepath)) {
        api_response(false, 'File not found');
    }

    // Serve file
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
    header('Content-Length: ' . filesize($filepath));
    header('Cache-Control: no-cache');
    readfile($filepath);
    exit;
}

// ============================================
// LIST FILES API
// ============================================
if ($method === 'GET' && $action === 'list') {
    $api_key = isset($_SERVER['HTTP_X_API_KEY']) ? $_SERVER['HTTP_X_API_KEY'] : '';
    
    if ($api_key !== API_KEY) {
        api_response(false, 'Invalid API Key');
    }
    
    $folder = isset($_GET['folder']) ? $_GET['folder'] : '';
    if (!in_array($folder, ALLOWED_FOLDERS)) {
        api_response(false, 'Invalid folder');
    }
    
    $target_dir = BASE_DIR . '/' . $folder;
    if (!is_dir($target_dir)) {
        api_response(true, 'Folder is empty', ['files' => []]);
    }
    
    $files = [];
    $scanned = scandir($target_dir);
    foreach ($scanned as $f) {
        if ($f === '.' || $f === '..') continue;
        $filepath = $target_dir . '/' . $f;
        $files[] = [
            'name' => $f,
            'size' => filesize($filepath),
            'modified' => date('Y-m-d H:i:s', filemtime($filepath)),
            'download_url' => BASE_URL . '/api.php?action=download&folder=' . $folder . '&file=' . $f
        ];
    }
    
    api_response(true, 'Files listed successfully', ['files' => $files]);
}

// ============================================
// INVALID REQUEST
// ============================================
api_response(false, 'Invalid request');
?>
