const csso = require('gulp-csso');
const del = require('del');
const gulp = require('gulp');
const javascriptObfuscator = require('gulp-javascript-obfuscator');
const { Transform } = require('stream');
const JavaScriptObfuscator = require('javascript-obfuscator');

// Obfusca blocos <script> inline em arquivos PHP/HTML,
// preservando as tags <?php ?> como placeholders durante o processo
function obfuscateInlineJs() {
  return new Transform({
    objectMode: true,
    transform(file, enc, cb) {
      if (file.isNull() || file.isDirectory()) return cb(null, file);

      let content = file.contents.toString('utf8');

      content = content.replace(
        /<script([^>]*)>([\s\S]*?)<\/script>/gi,
        (full, attrs, jsContent) => {
          if (/\bsrc\s*=/i.test(attrs)) return full;
          if (!jsContent.trim()) return full;

          const placeholders = [];
          const jsForObfuscation = jsContent.replace(/<\?php[\s\S]*?\?>/g, (php) => {
            placeholders.push(php);
            return `SISPLANPHP${placeholders.length - 1}ENDPHP`;
          });

          try {
            let result = JavaScriptObfuscator.obfuscate(jsForObfuscation.trim(), {
              compact: true,
              stringArray: false,
            }).getObfuscatedCode();

            placeholders.forEach((php, i) => {
              result = result.split(`SISPLANPHP${i}ENDPHP`).join(php);
            });

            return `<script${attrs}>${result}</script>`;
          } catch (e) {
            return full;
          }
        }
      );

      file.contents = Buffer.from(content, 'utf8');
      cb(null, file);
    },
  });
}

gulp.task('dist_css', function () {
  return gulp.src(['./dist/**/*.css'])
    .pipe(csso())
    .pipe(gulp.dest('../sisplan_web_prod/dist/'));
});

gulp.task('dist_map', function () {
  return gulp.src(['./dist/**/*.map', './dist/**/*.gif', './dist/**/*.json', './dist/**/*.jpg', './dist/**/*.png', './dist/**/*.jpeg', './dist/**/*.mp3'])
    .pipe(gulp.dest('../sisplan_web_prod/dist/'));
});

gulp.task('dist_js', function () {
  return gulp.src(['./dist/**/*.js'])
    .pipe(javascriptObfuscator({ compact: true }))
    .pipe(gulp.dest('../sisplan_web_prod/dist/'));
});

gulp.task('plugins_css', function () {
  return gulp.src(['./plugins/**/*.css'])
    .pipe(csso())
    .pipe(gulp.dest('../sisplan_web_prod/plugins/'));
});

gulp.task('plugins_map', function () {
  return gulp.src(['./plugins/**/*.map', './plugins/**/*.svg', './plugins/**/*.eot', './plugins/**/*.woff', './plugins/**/*.woff2', './plugins/**/*.ttf'])
    .pipe(gulp.dest('../sisplan_web_prod/plugins/'));
});

gulp.task('plugins_js', function () {
  return gulp.src(['./plugins/**/**/*.js'])
    .pipe(gulp.dest('../sisplan_web_prod/plugins/'));
});

gulp.task('fr3', function () {
  return gulp.src(['./**/*.fr3', './**/*.FR3'])
    .pipe(gulp.dest('../sisplan_web_prod'));
});

gulp.task('utils', function () {
  return gulp.src(['./utils/**/**/*.js'])
    .pipe(javascriptObfuscator({ compact: true }))
    .pipe(gulp.dest('../sisplan_web_prod/utils/'));
});

gulp.task('modals', function () {
  return gulp.src(['./modals/**/**/*.js'])
    .pipe(javascriptObfuscator({ compact: true }))
    .pipe(gulp.dest('../sisplan_web_prod/modals/'));
});

gulp.task('modals2', function () {
  return gulp.src(['./modals/**/**/*.html'])
    .pipe(gulp.dest('../sisplan_web_prod/modals/'));
});

// Ofusca o JS inline dentro dos PHP de modals
gulp.task('modals_php', function () {
  return gulp.src(['./modals/**/*.php'])
    .pipe(obfuscateInlineJs())
    .pipe(gulp.dest('../sisplan_web_prod/modals/'));
});

gulp.task('pages', function () {
  return gulp.src(['./pages/**/**/*.js'])
    .pipe(javascriptObfuscator({ compact: true }))
    .pipe(gulp.dest('../sisplan_web_prod/pages/'));
});

// Copia HTML e CSS das pages sem processamento
gulp.task('pages_assets', function () {
  return gulp.src(['./pages/**/**/*.html', './pages/**/**/*.css'])
    .pipe(gulp.dest('../sisplan_web_prod/pages/'));
});

// Ofusca o JS inline dentro dos PHP das pages
gulp.task('pages_php', function () {
  return gulp.src(['./pages/**/**/*.php'])
    .pipe(obfuscateInlineJs())
    .pipe(gulp.dest('../sisplan_web_prod/pages/'));
});

// Copia arquivos não-PHP da raiz
gulp.task('others', function () {
  return gulp.src(['./*.md', './*.json', './*.html', './*.ico', './*.bat', './*.js', './.htaccess'])
    .pipe(gulp.dest('../sisplan_web_prod/'));
});

// Ofusca o JS inline dentro dos PHP da raiz (index.php, menu.php, etc.)
gulp.task('others_php', function () {
  return gulp.src(['./*.php'])
    .pipe(obfuscateInlineJs())
    .pipe(gulp.dest('../sisplan_web_prod/'));
});
// Copia pasta v2 inteira sem processamento/ofuscação
gulp.task('v2', function () {
  return gulp.src(['./v2/**/*'], { base: './' })
    .pipe(gulp.dest('../sisplan_web_prod/'));
});

gulp.task('clean', () => del(['../sisplan_web_prod'], { force: true }));

gulp.task('default', gulp.series(
  'clean',
  'dist_css', 'dist_map', 'dist_js',
  'plugins_css', 'plugins_js', 'plugins_map',
  'fr3',
  'modals', 'modals2', 'modals_php',
  'utils',
  'pages', 'pages_assets', 'pages_php',
  'others', 'others_php',
  'v2'
));
