import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._();
  static Database? _database;

  DatabaseHelper._();

  Future<Database> get db async {
    _database ??= await initDb();
    return _database!;
  }

  Future<Database> initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'student_university.db');
    return await openDatabase(
      path,
      version: 2,
      onCreate: _onCreate,
      onUpgrade: _onUpgrade,
    );
  }

  Future _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE IF NOT EXISTS STUDENT (
        cardId TEXT PRIMARY KEY,
        studentId TEXT,
        firstName TEXT,
        name TEXT,
        promotion TEXT
      )
    ''');
    await db.execute('''
      CREATE TABLE IF NOT EXISTS ATTENDANCE (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        promotion TEXT,
        subject TEXT,
        date TEXT,
        studentId TEXT,
        FOREIGN KEY (studentId) REFERENCES STUDENT(cardId)
      )
    ''');
  }

  Future _onUpgrade(Database db, int oldVersion, int newVersion) async {
    if (oldVersion < 2) {
      await db.execute('''
        CREATE TABLE IF NOT EXISTS ATTENDANCE (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          promotion TEXT,
          subject TEXT,
          date TEXT,
          studentId TEXT,
          FOREIGN KEY (studentId) REFERENCES STUDENT(cardId)
        )
      ''');
    }
  }

  Future<void> clear() async {
    Database db = await instance.db;
    await db.delete('attendance');
    await db.delete('student');
  }
}
