const pool = require('../config/database');
const bcrypt = require('bcryptjs');
class Tour {
    // ดึงทัวร์ทั้งหมด
    static async getAllTours(userId) {
      try {
        console.log('Fetching tours for user:', userId);
    
        // ดึงทัวร์ทั้งหมดที่ userId ตรงกับผู้ใช้ที่ล็อกอิน
        const [rows] = await pool.query('SELECT * FROM tours WHERE Userid = ?', [userId]);
    
        console.log('Tours fetched successfully:', rows);
        return rows;
      } catch (error) {
        console.error('Error fetching tours:', error.message);
        throw new Error('เกิดข้อผิดพลาดในการดึงข้อมูลทัวร์: ' + error.message);
      }
    }
    
    // ค้นหาทัวร์โดยใช้ชื่อ
    static async searchTours(query) {
      try {

        const [rows] = await pool.query('SELECT * FROM tours WHERE name LIKE ?', [`%${query}%`]);
        // หากไม่มีทัวร์ที่ตรงกับคำค้นหา
        if (rows.length === 0) {
          return 'ไม่พบทัวร์ที่ตรงกับคำค้นหาของคุณ';
        }
        return rows;
      } catch (error) {
        console.error('Error searching tours:', error.message);
        throw new Error('เกิดข้อผิดพลาดในการค้นหาทัวร์');
      }
    }

    // สร้างทัวร์
    static async createTour(name, description, price, duration, userId) {
      // ตรวจสอบข้อมูล
      if (!name || !price || !duration) {
        throw new Error('ข้อมูลไม่ครบถ้วน กรุณากรอกข้อมูลให้ครบถ้วน');
      }
    
      // ตรวจสอบว่า userId เป็นตัวเลขหรือไม่
      const validUserId = parseInt(userId, 10);
      if (isNaN(validUserId)) {
        throw new Error('User ID ไม่ถูกต้อง');
      }
    
      const query = 'INSERT INTO tours (name, description, price, duration, userId) VALUES (?, ?, ?, ?, ?)';
      try {
        // บันทึกทัวร์พร้อมกับ userId ที่สร้างทัวร์
        await pool.execute(query, [name, description, price, duration, validUserId]);
      } catch (error) {
        console.error('Error creating tour:', error);
        throw new Error('เกิดข้อผิดพลาดในการสร้างทัวร์');
      }
    }
    
  
    // อัปเดตทัวร์
    static async updateTour(tourId, tourData) {
      const { name, description, price, duration } = tourData;
    
      // ตรวจสอบข้อมูลให้ครบถ้วน
      if (!name || !description || !price || !duration) {
        throw new Error('ข้อมูลไม่ครบถ้วน');
      }
    
      // สร้างคำสั่ง SQL สำหรับการอัปเดตข้อมูล
      const query = 'UPDATE tours SET name = ?, description = ?, price = ?, duration = ? WHERE id = ?';
      
      try {
        // ใช้ tourId ที่รับมาในการอัปเดต
        const [results] = await pool.execute(query, [name, description, price, duration, tourId]);
        console.log('✅ Update results:', results);
        return results;
      } catch (error) {
        console.error('Error updating tour:', error); // ข้อผิดพลาดจากการอัปเดต
        throw error;
      }
    }
    
    
  
    // ดึงทัวร์ตาม ID
    static async getTourById(tourId) {
      const query = 'SELECT * FROM tours WHERE id = ?';
      
      try {
        const [results] = await pool.execute(query, [tourId]);
        if (results.length === 0) {
          throw new Error(`ไม่พบทัวร์ที่มี ID ${tourId}`);
        }
        return results[0];  // คืนค่าผลลัพธ์ที่พบ
      } catch (error) {
        console.error('Error fetching tour by ID:', error);
        throw error; // ให้โยนข้อผิดพลาดกลับไปที่ controller
      }
    }

    // ลบทัวร์
    static async deleteTour(id) {
      const query = 'DELETE FROM tours WHERE id = ?';
      try {
        await pool.execute(query, [id]);
      } catch (error) {
        console.error('Error deleting tour:', error);
        throw new Error('เกิดข้อผิดพลาดในการลบทัวร์');
      }
    }
}

class User {
    static async findOne(email) {
        try {
            const [rows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
            return rows.length > 0 ? rows[0] : null;
        } catch (err) {
            throw err;
        }
    }

    static async create(name, email, password) {
        try {
            const hashedPassword = await bcrypt.hash(password, 10);
            const [result] = await pool.query(
                'INSERT INTO users (name, email, password) VALUES (?, ?, ?)',
                [name, email, hashedPassword]
            );
            return result.insertId;
        } catch (err) {
            throw err;
        }
    }

    static async comparePassword(email, password) {
        try {
            const user = await User.findOne(email);
            if (!user) return false;
            return await bcrypt.compare(password, user.password);
        } catch (err) {
            throw err;
        }
    }
}

class Booking {
  // ดึงรายการจองของผู้ใช้
  static async getUserBookings(userId) {
      const query = `
          SELECT b.id, t.name AS tour_name, t.price, b.booking_date
          FROM bookings b
          JOIN tours t ON b.tour_id = t.id
          WHERE b.user_id = ?
          ORDER BY b.booking_date DESC
      `;
      const [rows] = await pool.query(query, [userId]);
      return rows;
  }

  // ทำการจองทัวร์
  static async createBooking(userId, tourId) {
      const query = 'INSERT INTO bookings (user_id, tour_id) VALUES (?, ?)';
      await pool.execute(query, [userId, tourId]);
  }

  // ยกเลิกการจอง
  static async cancelBooking(userId, bookingId) {
      const query = 'DELETE FROM bookings WHERE id = ? AND user_id = ?';
      const [result] = await pool.execute(query, [bookingId, userId]);
      return result.affectedRows;
  }
}


module.exports = { User, Tour, Booking };