Gitlab@Informatics

Skip to content
Snippets Groups Projects
tourModel.js 7.91 KiB
const pool = require('../config/database');
const bcrypt = require('bcryptjs');
class Tour {
    // ดึงทัวร์ทั้งหมด
    static async getAllTours(userId) {
      try {
        console.log('Fetching all tours');
        
        // ดึงทัวร์ทั้งหมดที่ userId ตรงกับผู้ใช้ที่ล็อกอิน
        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, userId) {
      // ตรวจสอบข้อมูล
      if (!name || !price || !duration) {
        throw new Error('ข้อมูลไม่ครบถ้วน กรุณากรอกข้อมูลให้ครบถ้วน');
      }
    
      const query = 'INSERT INTO tours (name, description, price, duration, userId) VALUES (?, ?, ?, ?, ?)';
      try {
        // บันทึกทัวร์พร้อมกับ userId ที่สร้างทัวร์
        await pool.execute(query, [name, description, price, duration, userId]);
      } 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 id, name, description, price, duration, userId 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) {
      try {
        console.log("Deleting tour with ID:", id); // เช็คค่า ID ที่รับมา
        if (!id) {
          throw new Error("Tour ID is required");
        }
    
        // ตรวจสอบว่าทัวร์มีอยู่จริง
        const checkQuery = 'SELECT * FROM tours WHERE id = ?';
        const [tours] = await pool.execute(checkQuery, [id]);
    
        if (tours.length === 0) {
          throw new Error(`ไม่พบทัวร์ที่ต้องการลบ ID: ${id}`);
        }
    
        // ลบ bookings ที่เกี่ยวข้องก่อน
        const deleteBookingsQuery = 'DELETE FROM bookings WHERE tour_id = ?';
        await pool.execute(deleteBookingsQuery, [id]);
    
        // ลบ tour หลังจาก bookings ถูกลบแล้ว
        const deleteTourQuery = 'DELETE FROM tours WHERE id = ?';
        const [result] = await pool.execute(deleteTourQuery, [id]);
    
        console.log("Delete result:", result);
        return result;
      } 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.id ASC
    `;
    try {
      const [rows] = await pool.query(query, [userId]);
      return rows;  // คืนค่ารายการจองทั้งหมด
    } catch (error) {
      console.error('Error fetching user bookings:', error);
      throw new Error('Unable to retrieve user bookings');
    }
  }

  // ทำการจองทัวร์
  static async createBooking(userId, tourId) {
    const query = 'INSERT INTO bookings (user_id, tour_id) VALUES (?, ?)';
    try {
      const [result] = await pool.execute(query, [userId, tourId]);
      return result;  // คืนค่าผลลัพธ์จากการจอง
    } catch (error) {
      console.error('Error creating booking:', error);
      throw new Error('Error creating booking');
    }
  }

  // ลบการจอง
  static async deleteBooking(bookingId) {
    const query = 'DELETE FROM bookings WHERE id = ?';
    try {
      const [result] = await pool.execute(query, [bookingId]);
      return result;  // คืนค่าผลลัพธ์จากการลบการจอง
    } catch (error) {
      console.error('Error deleting booking:', error);
      throw new Error('Error deleting booking');
    }
  }
}


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