const http = require('http');
const url = require('url');

// Dubai Tour Data
const dubaiTour = {
  id: 1,
  code: 'DXB-5D',
  title: 'Dubai 5 Günlük Muhteşem Tur',
  subtitle: 'Burj Khalifa, Palm Jumeirah ve Daha Fazlası',
  slug: 'dubai-5-gunluk-muhtesem-tur',
  seo_description: 'Dubai\'ye 5 günlük unutulmaz bir tur. Burj Khalifa, Palm Jumeirah, Dubai Mall ve Desert Safari gibi eşsiz deneyimlerle dolu!',
  seo_image: 'https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=1200',
  type: 'flight',
  nights: 4,
  is_active: true,
  brand_id: 1,
  description: JSON.stringify({
    tr: '<h2>Dubai\'ye Hoş Geldiniz!</h2><p>Dubai, modern mimarisi, lüks alışveriş merkezleri ve eşsiz deneyimleriyle dünyanın en gözde turizm destinasyonlarından biridir.</p><h3>Tur Özellikleri:</h3><ul><li>Burj Khalifa ziyareti</li><li>Palm Jumeirah turu</li><li>Dubai Mall alışveriş</li><li>Desert Safari macerası</li><li>Lüks otel konaklama</li></ul>',
    en: '<h2>Welcome to Dubai!</h2><p>Dubai is one of the world\'s most popular tourist destinations with its modern architecture and unique experiences.</p>',
    de: '<h2>Willkommen in Dubai!</h2><p>Dubai ist eines der beliebtesten Reiseziele der Welt.</p>'
  }),
  itinerary: JSON.stringify([
    {
      day: 1,
      title: 'Dubai\'ye Varış ve Şehir Turu',
      stops: [
        { name: 'Dubai Havalimanı', time: '14:00', description: 'Havalimanında karşılama ve otel transferi' },
        { name: 'Burj Al Arab', time: '16:00', description: 'Dünyanın en lüks oteli görünümü' },
        { name: 'Jumeirah Beach', time: '17:00', description: 'Plajda serbest zaman' }
      ],
      images: ['https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=800']
    },
    {
      day: 2,
      title: 'Burj Khalifa ve Dubai Mall',
      stops: [
        { name: 'Burj Khalifa', time: '09:00', description: 'Dünyanın en yüksek binasına çıkış (124. kat)' },
        { name: 'Dubai Mall', time: '11:00', description: 'Alışveriş ve öğle yemeği' },
        { name: 'Dubai Fountain Show', time: '18:00', description: 'Müzikli su gösterisi' }
      ],
      images: ['https://images.unsplash.com/photo-1539650116574-75c0c6d73a6e?w=800']
    },
    {
      day: 3,
      title: 'Palm Jumeirah ve Atlantis',
      stops: [
        { name: 'Palm Jumeirah', time: '10:00', description: 'Palmiye şeklindeki ada turu' },
        { name: 'Atlantis The Palm', time: '12:00', description: 'Lüks otel ve su parkı ziyareti' },
        { name: 'Dubai Marina', time: '16:00', description: 'Marina yürüyüşü ve akşam yemeği' }
      ],
      images: []
    },
    {
      day: 4,
      title: 'Desert Safari Macerası',
      stops: [
        { name: 'Çöl Safari', time: '15:00', description: '4x4 araçlarla çöl turu' },
        { name: 'Deve Binişi', time: '17:00', description: 'Geleneksel deve binişi deneyimi' },
        { name: 'Çöl Kampı', time: '18:00', description: 'Barbekü akşam yemeği ve gösteriler' }
      ],
      images: []
    },
    {
      day: 5,
      title: 'Serbest Zaman ve Dönüş',
      stops: [
        { name: 'Gold Souk', time: '10:00', description: 'Altın çarşısı ziyareti (opsiyonel)' },
        { name: 'Dubai Havalimanı', time: '14:00', description: 'Havalimanına transfer ve dönüş' }
      ],
      images: []
    }
  ]),
  images: JSON.stringify([
    'https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=1200',
    'https://images.unsplash.com/photo-1539650116574-75c0c6d73a6e?w=1200',
    'https://images.unsplash.com/photo-1518684079-3c830dcef090?w=1200',
    'https://images.unsplash.com/photo-1582672060674-bc2bd808a8b5?w=1200'
  ]),
  highlights: JSON.stringify({
    tr: ['Burj Khalifa ziyareti', 'Palm Jumeirah turu', 'Desert Safari', 'Lüks otel konaklama', 'Dubai Mall alışveriş'],
    en: ['Burj Khalifa visit', 'Palm Jumeirah tour', 'Desert Safari', 'Luxury hotel', 'Dubai Mall shopping']
  }),
  included: JSON.stringify({
    tr: ['Uçak bileti (gidiş-dönüş)', '4 gece otel konaklama', 'Kahvaltı dahil', 'Tüm transferler', 'Profesyonel rehberlik', 'Tüm müze giriş ücretleri', 'Desert Safari turu'],
    en: ['Flight tickets (round trip)', '4 nights hotel', 'Breakfast included', 'All transfers', 'Professional guide', 'All museum fees', 'Desert Safari tour'],
    de: ['Flugtickets (Hin- und Rückflug)', '4 Nächte Hotel', 'Frühstück inklusive', 'Alle Transfers', 'Professionelle Führung']
  }),
  excluded: JSON.stringify({
    tr: ['Öğle ve akşam yemekleri', 'Kişisel harcamalar', 'Vize ücretleri', 'Seyahat sigortası'],
    en: ['Lunch and dinner', 'Personal expenses', 'Visa fees', 'Travel insurance'],
    de: ['Mittag- und Abendessen', 'Persönliche Ausgaben', 'Visagebühren', 'Reiseversicherung']
  }),
  dates: [
    {
      id: 1,
      tour_id: 1,
      start_date: '2026-03-01',
      end_date: '2026-03-05',
      adult_price: 1250.00,
      adult_discounted_price: 1099.00,
      child_price: 900.00,
      child_discounted_price: 799.00,
      baby_price: 0.00,
      baby_discounted_price: 0.00,
      capacity: 50,
      booked: 0,
      status: 'available',
      single_supplement_price: 100.00
    },
    {
      id: 2,
      tour_id: 1,
      start_date: '2026-03-15',
      end_date: '2026-03-19',
      adult_price: 1299.00,
      adult_discounted_price: 1149.00,
      child_price: 950.00,
      child_discounted_price: 849.00,
      baby_price: 0.00,
      baby_discounted_price: 0.00,
      capacity: 50,
      booked: 5,
      status: 'available',
      single_supplement_price: 100.00
    },
    {
      id: 3,
      tour_id: 1,
      start_date: '2026-04-01',
      end_date: '2026-04-05',
      adult_price: 1399.00,
      adult_discounted_price: 1199.00,
      child_price: 999.00,
      child_discounted_price: 899.00,
      baby_price: 0.00,
      baby_discounted_price: 0.00,
      capacity: 45,
      booked: 0,
      status: 'available',
      single_supplement_price: 150.00
    }
  ],
  categories: [{ id: 1, name: 'Dubai Turları', slug: 'dubai-turlari' }],
  brand: { id: 1, name: 'Avusturya Gezi', slug: 'avusturya-gezi' }
};

// Bali Tour Data
const baliTour = {
  id: 2,
  code: 'BAL-001',
  title: 'Bali & Singapur Turu',
  subtitle: 'Tropik Cennet',
  type: 'flight',
  nights: 7,
  is_active: true,
  brand_id: 1,
  slug: 'bali-singapur-turu',
  seo_description: 'Bali ve Singapur\'un muhteşem güzelliklerini keşfedin. Tropikal cennet Bali ve modern Singapur\'u bir arada yaşayın.',
  seo_image: 'https://images.unsplash.com/photo-1537996194471-e657df975ab4?w=1200',
  description: JSON.stringify({ tr: 'Bali ve Singapur\'un muhteşem güzelliklerini keşfedin.', en: 'Discover the beauty of Bali and Singapore.' }),
  itinerary: JSON.stringify([]),
  images: JSON.stringify(['https://images.unsplash.com/photo-1537996194471-e657df975ab4?w=1200']),
  highlights: JSON.stringify({ tr: ['Tapınak ziyaretleri', 'Pirinç terasları'], en: ['Temple visits', 'Rice terraces'] }),
  included: JSON.stringify({ tr: ['Uçak bileti', 'Otel'], en: ['Flight', 'Hotel'] }),
  excluded: JSON.stringify({ tr: ['Kişisel harcamalar'], en: ['Personal expenses'] }),
  dates: [
    {
      id: 4,
      tour_id: 2,
      start_date: '2026-02-15',
      end_date: '2026-02-22',
      adult_price: 1250.00,
      adult_discounted_price: 1100.00,
      child_price: 900.00,
      child_discounted_price: 800.00,
      baby_price: 0.00,
      capacity: 50,
      booked: 0,
      status: 'available'
    }
  ],
  categories: [{ id: 2, name: 'Uzak Doğu Turları', slug: 'uzak-dogu-turlari' }],
  brand: { id: 1, name: 'Avusturya Gezi', slug: 'avusturya-gezi' }
};

// Mock users data
const users = [
  {
    id: 1,
    name: 'Admin User',
    email: 'admin@avusturyagezi.com',
    password: 'password', // In real app this would be hashed
    user_type: 'super_admin',
    is_active: true
  },
  {
    id: 2,
    name: 'Test Customer',
    email: 'customer@example.com',
    password: 'password',
    user_type: 'customer',
    is_active: true
  }
];

let tours = [dubaiTour, baliTour];
let nextTourId = 3;
let nextDateId = 5;
let nextUserId = 3;

const server = http.createServer((req, res) => {
  const parsedUrl = url.parse(req.url, true);
  const path = parsedUrl.pathname;
  const method = req.method;

  // CORS headers
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Content-Type', 'application/json');

  if (method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }

  // Authentication routes
  if (path === '/api/auth/login' && method === 'POST') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        const user = users.find(u => u.email === data.email && u.password === data.password);
        
        if (user) {
          if (!user.is_active) {
            res.writeHead(403);
            res.end(JSON.stringify({ message: 'Account is deactivated' }));
            return;
          }
          
          // Generate a mock token
          const token = 'mock_token_' + Date.now();
          
          res.writeHead(200);
          res.end(JSON.stringify({
            message: 'Login successful',
            user: {
              id: user.id,
              name: user.name,
              email: user.email,
              user_type: user.user_type,
            },
            token: token
          }));
        } else {
          res.writeHead(401);
          res.end(JSON.stringify({ message: 'Invalid credentials' }));
        }
      } catch (e) {
        res.writeHead(400);
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
    return;
  }
  
  if (path === '/api/auth/register' && method === 'POST') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        
        // Validate required fields
        if (!data.name || !data.email || !data.password) {
          res.writeHead(422);
          res.end(JSON.stringify({
            message: 'Validation error',
            errors: {
              name: !data.name ? ['The name field is required.'] : undefined,
              email: !data.email ? ['The email field is required.'] : undefined,
              password: !data.password ? ['The password field is required.'] : undefined
            }
          }));
          return;
        }
        
        // Check if user already exists
        const existingUser = users.find(u => u.email === data.email);
        if (existingUser) {
          res.writeHead(422);
          res.end(JSON.stringify({
            message: 'Validation error',
            errors: {
              email: ['The email has already been taken.']
            }
          }));
          return;
        }
        
        const newUser = {
          id: nextUserId++,
          name: data.name,
          email: data.email,
          password: data.password, // In real app this would be hashed
          user_type: 'customer',
          phone: data.phone,
          is_active: true
        };
        
        users.push(newUser);
        
        // Generate a mock token
        const token = 'mock_token_' + Date.now();
        
        res.writeHead(201);
        res.end(JSON.stringify({
          message: 'User registered successfully',
          user: {
            id: newUser.id,
            name: newUser.name,
            email: newUser.email,
          },
          token: token
        }));
      } catch (e) {
        res.writeHead(400);
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
    return;
  }
  
  if (path === '/api/auth/logout' && method === 'POST') {
    // In a real app, this would invalidate the token
    res.writeHead(200);
    res.end(JSON.stringify({ message: 'Logged out successfully' }));
    return;
  }
  
  if (path === '/api/auth/user' && method === 'GET') {
    // In a real app, this would validate the token
    // For mock, return a dummy user
    res.writeHead(200);
    res.end(JSON.stringify({
      user: {
        id: 1,
        name: 'Admin User',
        email: 'admin@avusturyagezi.com',
        phone: null,
        user_type: 'super_admin',
        loyalty_points: 0
      }
    }));
    return;
  }

  console.log(`${method} ${path}`);

  // Health check
  if (path === '/api/health') {
    res.writeHead(200);
    res.end(JSON.stringify({ status: 'ok', message: 'Mock API Server Running' }));
    return;
  }

  // Get all tours (admin)
  if (path === '/api/admin/tours' && method === 'GET') {
    res.writeHead(200);
    res.end(JSON.stringify({
      data: tours,
      current_page: 1,
      last_page: 1,
      total: tours.length
    }));
    return;
  }

  // Get all tours (public)
  if (path === '/api/tours' && method === 'GET') {
    res.writeHead(200);
    res.end(JSON.stringify({
      data: tours.filter(t => t.is_active),
      current_page: 1,
      last_page: 1,
      total: tours.filter(t => t.is_active).length
    }));
    return;
  }

  // Get single tour (admin or public)
  const adminTourMatch = path.match(/^\/api\/admin\/tours\/(\d+)$/);
  const publicTourMatch = path.match(/^\/api\/tours\/(\d+)$/);
  const tourMatch = adminTourMatch || publicTourMatch;

  if (tourMatch && method === 'GET') {
    const tourId = parseInt(tourMatch[1]);
    const tour = tours.find(t => t.id === tourId);
    if (tour) {
      res.writeHead(200);
      res.end(JSON.stringify({ data: tour }));
    } else {
      res.writeHead(404);
      res.end(JSON.stringify({ error: 'Tour not found' }));
    }
    return;
  }

  // Create tour
  if (path === '/api/admin/tours' && method === 'POST') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        const newTour = {
          id: nextTourId++,
          ...data,
          dates: (data.dates || []).map((d, i) => ({ id: nextDateId + i, tour_id: nextTourId - 1, ...d })),
          categories: [],
          brand: { id: 1, name: 'Avusturya Gezi' }
        };
        nextDateId += (data.dates || []).length;
        tours.push(newTour);
        console.log('Created tour:', newTour.code);
        res.writeHead(201);
        res.end(JSON.stringify({ data: newTour }));
      } catch (e) {
        res.writeHead(400);
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
    return;
  }

  // Update tour
  if (adminTourMatch && method === 'PUT') {
    const tourId = parseInt(adminTourMatch[1]);
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        const index = tours.findIndex(t => t.id === tourId);
        if (index >= 0) {
          // Update dates
          if (data.dates) {
            data.dates = data.dates.map((d, i) => ({
              id: d.id || nextDateId++,
              tour_id: tourId,
              ...d
            }));
          }
          tours[index] = { ...tours[index], ...data };
          console.log('Updated tour:', tours[index].code);
          res.writeHead(200);
          res.end(JSON.stringify({ data: tours[index] }));
        } else {
          res.writeHead(404);
          res.end(JSON.stringify({ error: 'Tour not found' }));
        }
      } catch (e) {
        res.writeHead(400);
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
    return;
  }

  // Delete tour
  if (adminTourMatch && method === 'DELETE') {
    const tourId = parseInt(adminTourMatch[1]);
    const index = tours.findIndex(t => t.id === tourId);
    if (index >= 0) {
      tours.splice(index, 1);
      res.writeHead(200);
      res.end(JSON.stringify({ message: 'Deleted' }));
    } else {
      res.writeHead(404);
      res.end(JSON.stringify({ error: 'Tour not found' }));
    }
    return;
  }

  // Dashboard
  if (path === '/api/admin/dashboard' && method === 'GET') {
    res.writeHead(200);
    res.end(JSON.stringify({
      data: {
        totalReservations: 1247,
        pendingApprovals: 23,
        paymentPending: 45,
        todayTours: 8,
        totalRevenue: 125000,
        monthlyGrowth: 12.5
      }
    }));
    return;
  }

  // 404 for other routes
  res.writeHead(404);
  res.end(JSON.stringify({ error: 'Not found', path }));
});

const PORT = 8000;
server.listen(PORT, () => {
  console.log(`\n🚀 Mock API Server running at http://localhost:${PORT}`);
  console.log(`\n📦 Available tours:`);
  tours.forEach(t => console.log(`   - ${t.code}: ${t.title} (${t.dates.length} dates)`));
  console.log(`\n🔗 Endpoints:`);
  console.log(`   GET  /api/health`);
  console.log(`   GET  /api/tours`);
  console.log(`   GET  /api/tours/:id`);
  console.log(`   GET  /api/admin/tours`);
  console.log(`   GET  /api/admin/tours/:id`);
  console.log(`   POST /api/admin/tours`);
  console.log(`   PUT  /api/admin/tours/:id`);
  console.log(`\n✅ Ready for frontend connections!\n`);
});
