const pool = require('../config/database');
const bcrypt = require('bcryptjs');
class Tour {
    // ดึงทัวร์ทั้งหมด
    static async getAllTours() {
      try {
        console.log('Fetching all tours...');
        const [rows] = await pool.query('SELECT * FROM tours');
        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) {
      // ตรวจสอบข้อมูล
      if (!name || !price || !duration) {
        throw new Error('ข้อมูลไม่ครบถ้วน กรุณากรอกข้อมูลให้ครบถ้วน');
      }

      const query = 'INSERT INTO tours (name, description, price, duration) VALUES (?, ?, ?, ?)';
      try {
        await pool.execute(query, [name, description, price, duration]);
      } catch (error) {
        console.error('Error creating tour:', error);
        throw new Error('เกิดข้อผิดพลาดในการสร้างทัวร์');
      }
    }

  
    // อัปเดตทัวร์
    static async updateTour(id, tourData) {
      const { name, description, price, duration } = tourData;
  
      // ตรวจสอบข้อมูล
      if (!name || !price || !duration) {
        throw new Error('ข้อมูลไม่ครบถ้วน กรุณากรอกข้อมูลให้ครบถ้วน');
      }
  
      const query = 'UPDATE tours SET name = ?, description = ?, price = ?, duration = ? WHERE id = ?';
      try {
        await pool.execute(query, [name, description, price, duration, id]);
      } catch (error) {
        console.error('Error updating tour:', error);
        throw new Error('เกิดข้อผิดพลาดในการอัปเดตทัวร์');
      }
    }
  
    // ดึงทัวร์ตาม ID
    static async getTourById(id) {
      try {
        console.log('Searching for tour with ID:', id); // เพิ่มบรรทัดนี้
        const [rows] = await pool.query('SELECT * FROM tours WHERE id = ?', [id]);
        if (rows.length === 0) {
          throw new Error('ไม่พบทัวร์ที่มี ID นี้');
        }
        return rows[0];
      } catch (error) {
        console.error('Error fetching tour by ID:', error);
        throw new Error('เกิดข้อผิดพลาดในการดึงข้อมูลทัวร์');
      }
    }

    // ลบทัวร์
    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;
        }
    }
}

module.exports = { User, Tour };