const axios = require("axios");

console.log('🗺️  MAPPING DES CHAMPS GRAVITY FORMS\n');

const GF_BASE_URL = 'https://ccis-agadir.ma/wp-json/gf/v2';
const GF_API_KEY = 'ck_5534275e8c85e61848c06076a7a25db263df9d93';
const GF_API_SECRET = 'cs_fb8a28ffb99631d3fe1fb8957f17bfb51390bd24';

// Mapping des formulaires et leurs champs
const formsMapping = {
  7: { // Business Plan
    name: 'Business Plan',
    fields: {
      '1': 'firstName',
      '3': 'lastName', 
      '4': 'nationality',
      '5': 'phone',
      '6': 'email',
      '7': 'company',
      '8': 'city',
      '9': 'education',
      '10': 'needs'
    }
  },
  8: { // Market Research
    name: 'Market Research',
    fields: {
      '1': 'firstName',
      '3': 'lastName',
      '4': 'nationality', 
      '5': 'phone',
      '6': 'email',
      '7': 'company',
      '8': 'city',
      '9': 'researchType',
      '10': 'budget'
    }
  },
  9: { // Networking
    name: 'Networking', 
    fields: {
      '1': 'firstName',
      '3': 'lastName',
      '4': 'nationality',
      '5': 'phone', 
      '6': 'email',
      '7': 'company',
      '8': 'sector',
      '9': 'networkingGoal',
      '10': 'expectations'
    }
  },
  10: { // Sourcing
    name: 'Sourcing',
    fields: {
      '1': 'firstName',
      '3': 'lastName', 
      '4': 'nationality',
      '5': 'phone',
      '6': 'email',
      '7': 'company',
      '8': 'sourcingType',
      '9': 'quantity',
      '10': 'deadline'
    }
  },
  11: { // Prospecting
    name: 'Prospecting',
    fields: {
      '1': 'firstName',
      '3': 'lastName',
      '4': 'nationality',
      '5': 'phone',
      '6': 'email', 
      '7': 'company',
      '8': 'targetMarket',
      '9': 'prospectingMethod',
      '10': 'budget'
    }
  }
};

async function mapAndExtractData() {
  console.log('🎯 Extraction des données légitimes...\n');

  for (const [formId, mapping] of Object.entries(formsMapping)) {
    try {
      console.log(`📋 ${mapping.name} (Form ${formId})...`);
      
      const response = await axios.get(`${GF_BASE_URL}/forms/${formId}/entries`, {
        auth: {
          username: GF_API_KEY,
          password: GF_API_SECRET
        },
        timeout: 15000
      });

      const entries = response.data.entries || [];
      
      // Filtrer et mapper les entrées légitimes
      const legitimateData = entries
        .filter(entry => {
          const field1 = entry['1'] || '';
          return !field1.includes('BTC') && 
                 !field1.includes('Bitcoin') && 
                 !field1.includes('bitcoin') &&
                 field1.length < 50;
        })
        .map(entry => {
          const mapped = {
            id: entry.id,
            date_created: entry.date_created,
            ip: entry.ip,
            status: entry.status
          };

          // Mapper les champs
          Object.entries(mapping.fields).forEach(([gfField, ourField]) => {
            mapped[ourField] = entry[gfField] || null;
          });

          return mapped;
        });

      console.log(`✅ ${legitimateData.length}/${entries.length} entrées légitimes`);

      // Afficher les données formatées
      if (legitimateData.length > 0) {
        legitimateData.forEach((data, index) => {
          console.log(`\n${index + 1}. ${data.firstName} ${data.lastName}`);
          console.log(`   📧 ${data.email}`);
          console.log(`   📞 ${data.phone}`);
          console.log(`   🏢 ${data.company || 'Non spécifié'}`);
          console.log(`   📍 ${data.city || data.targetMarket || data.sector || 'Non spécifié'}`);
          console.log(`   📅 ${data.date_created}`);
          
          // Champs spécifiques
          if (data.needs) console.log(`   💼 Besoins: ${data.needs}`);
          if (data.researchType) console.log(`   🔍 Type recherche: ${data.researchType}`);
          if (data.networkingGoal) console.log(`   🤝 Objectif networking: ${data.networkingGoal}`);
          if (data.sourcingType) console.log(`   🏭 Type sourcing: ${data.sourcingType}`);
          if (data.prospectingMethod) console.log(`   🎯 Méthode prospection: ${data.prospectingMethod}`);
        });
      }

    } catch (error) {
      console.log(`❌ ${mapping.name}: ${error.message}`);
    }
    console.log('─'.repeat(60));
  }
}

mapAndExtractData().catch(console.error);
