import { showNotification, _ } from './utils.js';

export const phpScriptGenerator = (() => {
    let dom = {};

    function cacheDom() {
        const settingsModal = document.getElementById('settingsModal');
        if (!settingsModal) return false;
        
        dom.secretKeyCheck = settingsModal.querySelector('#phpSecretKeyCheck');
        dom.secretKey = settingsModal.querySelector('#phpSecretKey');
        dom.savePath = settingsModal.querySelector('#phpSavePath');
        dom.filename = settingsModal.querySelector('#phpFilename');
        dom.fileActionAppendRadio = settingsModal.querySelector('#phpFileActionAppend');
        dom.generatedCode = settingsModal.querySelector('#generatedPhpCode');
        dom.generateBtn = settingsModal.querySelector('#generatePhpScriptBtn');
        dom.copyBtn = settingsModal.querySelector('#copyPhpScriptBtn');
        
        return dom.generateBtn && dom.copyBtn;
    }

    function init() {
        if (!cacheDom()) {
            return;
        }
        dom.generateBtn.addEventListener('click', generatePhpScript);
        dom.copyBtn.addEventListener('click', copyScript);
    }
    
    function generatePhpScript() {
        const useSecretKey = dom.secretKeyCheck.checked;
        const secretKey = dom.secretKey.value.trim();
        const savePath = dom.savePath.value.trim();
        const filename = dom.filename.value.trim() || 'CinePlex_Playlist.m3u';
        const appendToFile = dom.fileActionAppendRadio.checked;

        let script = `<?php\nheader('Content-Type: application/json');\nheader('Access-Control-Allow-Origin: *');\nheader('Access-Control-Allow-Methods: POST, OPTIONS');\nheader('Access-Control-Allow-Headers: Content-Type, Origin, X-Secret-Key');\n\nif ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {\n    http_response_code(200);\n    exit(0);\n}\n\ndefine('SAVE_DIRECTORY', '${savePath.replace(/'/g, "\\'")}');\ndefine('FILENAME', '${filename.replace(/'/g, "\\'")}');\ndefine('FILE_ACTION_APPEND', ${appendToFile ? 'true' : 'false'});\n${useSecretKey ? `define('SECRET_KEY', '${secretKey.replace(/'/g, "\\'")}');` : ''}\n\nfunction sendResponse($success, $message, $filename = '', $http_code = 200) {\n    if (!$success && $http_code === 200) {\n        $http_code = 400;\n    }\n    http_response_code($http_code);\n    echo json_encode(['success' => $success, 'message' => $message, 'filename' => $filename]);\n    exit;\n}\n`;
        if (useSecretKey) {
            script += `\n$auth_key = isset($_SERVER['HTTP_X_SECRET_KEY']) ? $_SERVER['HTTP_X_SECRET_KEY'] : '';\nif (!defined('SECRET_KEY') || SECRET_KEY === '' || $auth_key !== SECRET_KEY) {\n    sendResponse(false, 'Acceso no autorizado. Clave secreta inválida o no proporcionada.', '', 403);\n}\n`;
        }
        script += `\n$json_data = file_get_contents('php://input');\n$data = json_decode($json_data, true);\n\nif (json_last_error() !== JSON_ERROR_NONE) {\n    sendResponse(false, 'Error: Datos JSON inválidos.');\n}\n\nif (!isset($data['streams']) || !is_array($data['streams']) || empty($data['streams'])) {\n    sendResponse(false, 'Error: El JSON debe contener un array "streams" no vacío.');\n}\n\n$save_dir = SAVE_DIRECTORY !== '' ? rtrim(SAVE_DIRECTORY, '/\\') : __DIR__;\n\nif (!is_dir($save_dir) || !is_writable($save_dir)) {\n    sendResponse(false, 'Error del servidor: El directorio de destino no existe o no tiene permisos de escritura.', '', 500);\n}\n\n$safe_filename = preg_replace('/[^\\w\\s._-]/', '', basename(FILENAME));\n$safe_filename = preg_replace('/\\s+/', '_', $safe_filename);\n$target_path = $save_dir . DIRECTORY_SEPARATOR . $safe_filename;\n\n$content_to_write = "";\n\nif (FILE_ACTION_APPEND) {\n    $file_exists = file_exists($target_path);\n    if (!$file_exists) {\n        $content_to_write .= "#EXTM3U\\n";\n    }\n    foreach ($data['streams'] as $stream) {\n        if (isset($stream['extinf'], $stream['url'])) {\n            $content_to_write .= trim($stream['extinf']) . "\\n";\n            $content_to_write .= trim($stream['url']) . "\\n";\n        }\n    }\n    if (file_put_contents($target_path, $content_to_write, FILE_APPEND | LOCK_EX) !== false) {\n        sendResponse(true, 'Streams añadidos correctamente al archivo.', $safe_filename, 200);\n    } else {\n        sendResponse(false, 'Error del servidor: No se pudo añadir contenido al archivo.', '', 500);\n    }\n} else { // Overwrite mode\n    $content_to_write = "#EXTM3U\\n";\n    foreach ($data['streams'] as $stream) {\n        if (isset($stream['extinf'], $stream['url'])) {\n            $content_to_write .= trim($stream['extinf']) . "\\n";\n            $content_to_write .= trim($stream['url']) . "\\n";\n        }\n    }\n    if (file_put_contents($target_path, $content_to_write, LOCK_EX) !== false) {\n        sendResponse(true, 'Archivo de streams sobrescrito correctamente.', $safe_filename, 201);\n    } else {\n        sendResponse(false, 'Error del servidor: No se pudo escribir el archivo.', '', 500);\n    }\n}\n?>`;
        dom.generatedCode.value = script;
        showNotification(_("scriptGenerated"), "success");
    }

    function copyScript() {
        if (!dom.generatedCode.value || dom.generatedCode.value.trim() === '') {
            showNotification(_("errorGeneratingScript"), "warning");
            return;
        }
        navigator.clipboard.writeText(dom.generatedCode.value).then(() => {
            showNotification(_("scriptCopied"), "success");
        }).catch(err => {
            showNotification(_("errorCopyingScript"), "error");
        });
    }

    return { init };
})();