const Database = require('better-sqlite3');
const bcrypt = require('bcryptjs');
const path = require('path');
const fs = require('fs');

const dbPath = process.env.DB_PATH || path.join(__dirname, '../../data/school.db');

// Ensure data directory exists
const dataDir = path.dirname(dbPath);
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir, { recursive: true });
}

const db = new Database(dbPath);

// Enable foreign keys
db.pragma('foreign_keys = ON');

// WAL mode for better concurrency
db.pragma('journal_mode = WAL');

console.log('Initializing Africa Alert database...');
console.log('Database path:', dbPath);

// ========================================
// BASE TABLES WITH SYNC INFRASTRUCTURE
// ========================================
// All tables have: last_synced_at, sync_status, is_deleted

db.exec(`
  -- =============================================
  -- CORE USERS TABLE WITH SYNC FIELDS
  -- =============================================
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    email TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    role TEXT NOT NULL CHECK(role IN ('admin', 'teacher', 'student', 'parent', 'accountant', 'librarian', 'nurse')),
    first_name TEXT NOT NULL,
    last_name TEXT NOT NULL,
    phone TEXT,
    address TEXT,
    date_of_birth DATE,
    gender TEXT CHECK(gender IN ('male', 'female', 'other')),
    id_number TEXT,
    profile_image TEXT,
    emergency_contact TEXT,
    emergency_phone TEXT,
    is_active INTEGER DEFAULT 1,
    last_login DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending' CHECK(sync_status IN ('synced', 'pending', 'conflict')),
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- CLASSES TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS classes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    section TEXT,
    capacity INTEGER DEFAULT 40,
    class_teacher_id INTEGER REFERENCES users(id),
    description TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- SUBJECTS TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS subjects (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    class_id INTEGER REFERENCES classes(id),
    teacher_id INTEGER REFERENCES users(id),
    description TEXT,
    credit_hours INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- STUDENT ENROLLMENTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS enrollments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    class_id INTEGER NOT NULL REFERENCES classes(id),
    section TEXT,
    roll_number TEXT,
    admission_date DATE DEFAULT (date('now')),
    academic_year TEXT,
    status TEXT DEFAULT 'active' CHECK(status IN ('active', 'inactive', 'transferred', 'graduated')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ATTENDANCE TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS attendance (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    class_id INTEGER REFERENCES classes(id),
    subject_id INTEGER REFERENCES subjects(id),
    date DATE NOT NULL,
    status TEXT NOT NULL CHECK(status IN ('present', 'absent', 'late', 'excused')),
    remarks TEXT,
    marked_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- FEE GROUPS
  -- =============================================
  CREATE TABLE IF NOT EXISTS fee_groups (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    description TEXT,
    amount REAL NOT NULL,
    type TEXT CHECK(type IN ('tuition', 'transport', 'hostel', 'exam', 'library', 'activity', 'other')),
    frequency TEXT CHECK(frequency IN ('one-time', 'monthly', 'termly', 'annually')),
    academic_year TEXT,
    due_date DATE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- STUDENT FEES
  -- =============================================
  CREATE TABLE IF NOT EXISTS student_fees (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    fee_group_id INTEGER NOT NULL REFERENCES fee_groups(id),
    amount REAL NOT NULL,
    paid_amount REAL DEFAULT 0,
    discount_amount REAL DEFAULT 0,
    fine_amount REAL DEFAULT 0,
    status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'partial', 'paid', 'cancelled')),
    due_date DATE,
    paid_at DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- PAYMENTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS payments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_fee_id INTEGER NOT NULL REFERENCES student_fees(id),
    amount REAL NOT NULL,
    payment_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    payment_method TEXT CHECK(payment_method IN ('cash', 'bank', 'card', 'paynow', 'ecocash', 'internal_transfer')),
    reference_number TEXT,
    transaction_id TEXT,
    paynow_poll_url TEXT,
    collected_by INTEGER REFERENCES users(id),
    notes TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- MESSAGES
  -- =============================================
  CREATE TABLE IF NOT EXISTS messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    sender_id INTEGER REFERENCES users(id),
    recipient_id INTEGER REFERENCES users(id),
    subject TEXT NOT NULL,
    body TEXT,
    is_read INTEGER DEFAULT 0,
    is_announcement INTEGER DEFAULT 0,
    priority TEXT DEFAULT 'normal' CHECK(priority IN ('low', 'normal', 'high', 'urgent')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- EVENTS/CALENDAR
  -- =============================================
  CREATE TABLE IF NOT EXISTS events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    title TEXT NOT NULL,
    description TEXT,
    event_date DATE NOT NULL,
    end_date DATE,
    event_type TEXT CHECK(event_type IN ('holiday', 'exam', 'meeting', 'activity', 'deadline', 'other')),
    venue TEXT,
    created_by INTEGER REFERENCES users(id),
    is_public INTEGER DEFAULT 1,
    academic_year TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- EXPENSES
  -- =============================================
  CREATE TABLE IF NOT EXISTS expenses (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    category TEXT NOT NULL,
    subcategory TEXT,
    description TEXT NOT NULL,
    amount REAL NOT NULL,
    expense_date DATE,
    vendor TEXT,
    invoice_number TEXT,
    payment_method TEXT,
    created_by INTEGER REFERENCES users(id),
    approved_by INTEGER REFERENCES users(id),
    receipt_image TEXT,
    status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'approved', 'rejected', 'paid')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- GRADES/RESULTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS grades (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    subject_id INTEGER NOT NULL REFERENCES subjects(id),
    exam_type TEXT CHECK(exam_type IN ('test', 'quiz', 'midterm', 'final', 'assignment')),
    marks REAL NOT NULL,
    total_marks REAL DEFAULT 100,
    grade TEXT,
    remarks TEXT,
    graded_by INTEGER REFERENCES users(id),
    graded_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    academic_year TEXT,
    term TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- SYNC LOGS
  -- =============================================
  CREATE TABLE IF NOT EXISTS sync_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    table_name TEXT NOT NULL,
    record_id INTEGER,
    operation TEXT NOT NULL CHECK(operation IN ('push', 'pull', 'conflict', 'error')),
    status TEXT NOT NULL CHECK(status IN ('success', 'failed', 'pending')),
    error_message TEXT,
    retry_count INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    synced_at DATETIME
  );

  -- =============================================
  -- SYNC CONFIG
  -- =============================================
  CREATE TABLE IF NOT EXISTS sync_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    key TEXT UNIQUE NOT NULL,
    value TEXT,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );

  -- =============================================
  -- SYSTEM SETTINGS
  -- =============================================
  CREATE TABLE IF NOT EXISTS system_settings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    key TEXT UNIQUE NOT NULL,
    value TEXT,
    description TEXT,
    category TEXT DEFAULT 'general',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('Core tables created.');

// ========================================
// PAYROLL & HR MODULE
// ========================================
db.exec(`
  -- =============================================
  -- STAFF ROLES
  -- =============================================
  CREATE TABLE IF NOT EXISTS staff_roles (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    description TEXT,
    is_teaching_role INTEGER DEFAULT 0,
    permissions TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- SALARY GRADES
  -- =============================================
  CREATE TABLE IF NOT EXISTS salary_grades (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    grade_level TEXT,
    basic_salary REAL NOT NULL,
    housing_allowance REAL DEFAULT 0,
    transport_allowance REAL DEFAULT 0,
    medical_allowance REAL DEFAULT 0,
    other_allowances REAL DEFAULT 0,
    description TEXT,
    effective_date DATE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- STAFF EMPLOYMENT RECORDS
  -- =============================================
  CREATE TABLE IF NOT EXISTS staff_records (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    user_id INTEGER NOT NULL REFERENCES users(id),
    staff_number TEXT UNIQUE,
    role_id INTEGER REFERENCES staff_roles(id),
    salary_grade_id INTEGER REFERENCES salary_grades(id),
    employment_type TEXT DEFAULT 'full-time' CHECK(employment_type IN ('full-time', 'part-time', 'contract', 'temporary', 'intern')),
    appointment_date DATE,
    confirmation_date DATE,
    termination_date DATE,
    termination_reason TEXT,
    bank_name TEXT,
    bank_branch TEXT,
    account_number TEXT,
    account_name TEXT,
    department TEXT,
    designation TEXT,
    reports_to INTEGER REFERENCES users(id),
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- LEAVE TYPES
  -- =============================================
  CREATE TABLE IF NOT EXISTS leave_types (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    description TEXT,
    max_days_per_year INTEGER,
    is_paid INTEGER DEFAULT 1,
    requires_approval INTEGER DEFAULT 1,
    color TEXT DEFAULT '#3b82f6',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- LEAVE REQUESTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS leave_requests (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    staff_id INTEGER NOT NULL REFERENCES users(id),
    leave_type_id INTEGER NOT NULL REFERENCES leave_types(id),
    start_date DATE NOT NULL,
    end_date DATE NOT NULL,
    days_count REAL NOT NULL,
    reason TEXT,
    status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'approved', 'rejected', 'cancelled')),
    approved_by INTEGER REFERENCES users(id),
    approved_at DATETIME,
    rejection_reason TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- STAFF ATTENDANCE
  -- =============================================
  CREATE TABLE IF NOT EXISTS staff_attendance (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    staff_id INTEGER NOT NULL REFERENCES users(id),
    date DATE NOT NULL,
    check_in DATETIME,
    check_out DATETIME,
    status TEXT DEFAULT 'present' CHECK(status IN ('present', 'absent', 'late', 'half-day', 'on-leave')),
    remarks TEXT,
    marked_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- PAYROLL GENERATION
  -- =============================================
  CREATE TABLE IF NOT EXISTS payroll_runs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    period_month INTEGER NOT NULL,
    period_year INTEGER NOT NULL,
    description TEXT,
    status TEXT DEFAULT 'draft' CHECK(status IN ('draft', 'calculated', 'approved', 'paid', 'cancelled')),
    total_gross REAL DEFAULT 0,
    total_deductions REAL DEFAULT 0,
    total_net REAL DEFAULT 0,
    approved_by INTEGER REFERENCES users(id),
    paid_at DATETIME,
    created_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- PAYSLIPS
  -- =============================================
  CREATE TABLE IF NOT EXISTS payslips (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    staff_id INTEGER NOT NULL REFERENCES users(id),
    payroll_run_id INTEGER NOT NULL REFERENCES payroll_runs(id),
    basic_salary REAL NOT NULL,
    housing_allowance REAL DEFAULT 0,
    transport_allowance REAL DEFAULT 0,
    medical_allowance REAL DEFAULT 0,
    other_allowances REAL DEFAULT 0,
    gross_salary REAL NOT NULL,
    tax_deduction REAL DEFAULT 0,
    pension_deduction REAL DEFAULT 0,
    other_deductions REAL DEFAULT 0,
    total_deductions REAL DEFAULT 0,
    net_salary REAL NOT NULL,
    bank_reference TEXT,
    paid_at DATETIME,
    status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'approved', 'paid', 'cancelled')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('Payroll & HR tables created.');

// ========================================
// INVENTORY MODULE
// ========================================
db.exec(`
  -- =============================================
  -- ITEM CATEGORIES
  -- =============================================
  CREATE TABLE IF NOT EXISTS item_categories (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    description TEXT,
    parent_id INTEGER REFERENCES item_categories(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- SUPPLIERS
  -- =============================================
  CREATE TABLE IF NOT EXISTS suppliers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    contact_person TEXT,
    email TEXT,
    phone TEXT,
    address TEXT,
    city TEXT,
    country TEXT DEFAULT 'Zimbabwe',
    tax_id TEXT,
    bank_details TEXT,
    notes TEXT,
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- STORE LOCATIONS
  -- =============================================
  CREATE TABLE IF NOT EXISTS store_locations (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    description TEXT,
    address TEXT,
    manager_id INTEGER REFERENCES users(id),
    is_warehouse INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ITEMS/INVENTORY
  -- =============================================
  CREATE TABLE IF NOT EXISTS items (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    barcode TEXT,
    description TEXT,
    category_id INTEGER REFERENCES item_categories(id),
    unit TEXT NOT NULL,
    purchase_price REAL DEFAULT 0,
    selling_price REAL DEFAULT 0,
    reorder_level INTEGER DEFAULT 10,
    expiry_tracking INTEGER DEFAULT 0,
    serial_tracking INTEGER DEFAULT 0,
    supplier_id INTEGER REFERENCES suppliers(id),
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ITEM STOCK
  -- =============================================
  CREATE TABLE IF NOT EXISTS item_stock (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    item_id INTEGER NOT NULL REFERENCES items(id),
    store_id INTEGER NOT NULL REFERENCES store_locations(id),
    quantity INTEGER DEFAULT 0,
    min_quantity INTEGER DEFAULT 0,
    max_quantity INTEGER,
    last_stocktake DATE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- STOCK TRANSACTIONS
  -- =============================================
  CREATE TABLE IF NOT EXISTS stock_transactions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    item_id INTEGER NOT NULL REFERENCES items(id),
    store_id INTEGER NOT NULL REFERENCES store_locations(id),
    type TEXT NOT NULL CHECK(type IN ('purchase', 'sale', 'adjustment', 'transfer', 'damage', 'expired', 'return')),
    quantity INTEGER NOT NULL,
    unit_price REAL,
    total_amount REAL,
    reference_number TEXT,
    supplier_id INTEGER REFERENCES suppliers(id),
    transaction_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    notes TEXT,
    created_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ITEM ISSUES
  -- =============================================
  CREATE TABLE IF NOT EXISTS item_issues (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    item_id INTEGER NOT NULL REFERENCES items(id),
    issued_to_type TEXT NOT NULL CHECK(issued_to_type IN ('staff', 'department', 'student', 'class')),
    issued_to_id INTEGER,
    quantity INTEGER NOT NULL,
    purpose TEXT,
    issue_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    return_due_date DATE,
    returned_date DATETIME,
    returned_quantity INTEGER DEFAULT 0,
    condition_on_return TEXT,
    issued_by INTEGER REFERENCES users(id),
    status TEXT DEFAULT 'issued' CHECK(status IN ('issued', 'returned', 'partially_returned', 'damaged')),
    notes TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('Inventory tables created.');

// ========================================
// ONLINE EXAMS MODULE
// ========================================
db.exec(`
  -- =============================================
  -- EXAM GROUPS
  -- =============================================
  CREATE TABLE IF NOT EXISTS exam_groups (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    description TEXT,
    exam_type TEXT CHECK(exam_type IN ('quiz', 'test', 'midterm', 'final', 'practice')),
    duration_minutes INTEGER DEFAULT 60,
    total_marks REAL DEFAULT 100,
    passing_marks REAL DEFAULT 50,
    is_random_order INTEGER DEFAULT 0,
    show_results INTEGER DEFAULT 1,
    allow_review INTEGER DEFAULT 1,
    max_attempts INTEGER DEFAULT 1,
    academic_year TEXT,
    term TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- QUESTION BANKS
  -- =============================================
  CREATE TABLE IF NOT EXISTS question_banks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    exam_group_id INTEGER REFERENCES exam_groups(id),
    subject_id INTEGER REFERENCES subjects(id),
    question_type TEXT NOT NULL CHECK(question_type IN ('multiple-choice', 'true-false', 'short-answer', 'essay', 'fill-blank')),
    question TEXT NOT NULL,
    options TEXT,
    correct_answer TEXT NOT NULL,
    marks REAL DEFAULT 1,
    explanation TEXT,
    difficulty TEXT DEFAULT 'medium' CHECK(difficulty IN ('easy', 'medium', 'hard')),
    tags TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- EXAM SCHEDULES
  -- =============================================
  CREATE TABLE IF NOT EXISTS exam_schedules (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    exam_group_id INTEGER NOT NULL REFERENCES exam_groups(id),
    class_id INTEGER REFERENCES classes(id),
    subject_id INTEGER REFERENCES subjects(id),
    start_time DATETIME NOT NULL,
    end_time DATETIME,
    duration_minutes INTEGER,
    instructions TEXT,
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- STUDENT EXAM ATTEMPTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS exam_attempts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    exam_group_id INTEGER NOT NULL REFERENCES exam_groups(id),
    schedule_id INTEGER REFERENCES exam_schedules(id),
    started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    submitted_at DATETIME,
    time_spent_seconds INTEGER,
    total_marks REAL DEFAULT 0,
    obtained_marks REAL DEFAULT 0,
    percentage REAL DEFAULT 0,
    status TEXT DEFAULT 'in-progress' CHECK(status IN ('in-progress', 'completed', 'submitted', 'graded')),
    ip_address TEXT,
    user_agent TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- EXAM ANSWERS
  -- =============================================
  CREATE TABLE IF NOT EXISTS exam_answers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    attempt_id INTEGER NOT NULL REFERENCES exam_attempts(id),
    question_id INTEGER NOT NULL REFERENCES question_banks(id),
    answer TEXT,
    is_correct INTEGER DEFAULT 0,
    marks_obtained REAL DEFAULT 0,
    answered_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('Online Exams tables created.');

// ========================================
// HOSTEL MODULE
// ========================================
db.exec(`
  -- =============================================
  -- HOSTELS
  -- =============================================
  CREATE TABLE IF NOT EXISTS hostels (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    type TEXT NOT NULL CHECK(type IN ('boys', 'girls', 'co-ed')),
    address TEXT,
    warden_id INTEGER REFERENCES users(id),
    phone TEXT,
    description TEXT,
    total_rooms INTEGER DEFAULT 0,
    capacity INTEGER DEFAULT 0,
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ROOM TYPES
  -- =============================================
  CREATE TABLE IF NOT EXISTS room_types (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    description TEXT,
    bed_count INTEGER DEFAULT 1,
    price_per_semester REAL DEFAULT 0,
    facilities TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ROOMS
  -- =============================================
  CREATE TABLE IF NOT EXISTS rooms (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    hostel_id INTEGER NOT NULL REFERENCES hostels(id),
    room_type_id INTEGER REFERENCES room_types(id),
    room_number TEXT NOT NULL,
    floor INTEGER DEFAULT 0,
    bed_count INTEGER DEFAULT 1,
    status TEXT DEFAULT 'available' CHECK(status IN ('available', 'occupied', 'maintenance', 'reserved')),
    description TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ROOM ASSIGNMENTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS room_assignments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    room_id INTEGER NOT NULL REFERENCES rooms(id),
    bed_number INTEGER DEFAULT 1,
    start_date DATE NOT NULL,
    end_date DATE,
    status TEXT DEFAULT 'active' CHECK(status IN ('active', 'inactive', 'transferred', 'expelled')),
    remarks TEXT,
    assigned_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- HOSTEL FEES
  -- =============================================
  CREATE TABLE IF NOT EXISTS hostel_fees (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    room_id INTEGER REFERENCES rooms(id),
    amount REAL NOT NULL,
    period TEXT,
    due_date DATE,
    paid_amount REAL DEFAULT 0,
    status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'partial', 'paid', 'waived')),
    paid_at DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('Hostel tables created.');

// ========================================
// TRANSPORT MODULE
// ========================================
db.exec(`
  -- =============================================
  -- VEHICLES
  -- =============================================
  CREATE TABLE IF NOT EXISTS vehicles (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    registration_number TEXT NOT NULL,
    model TEXT,
    make TEXT,
    year INTEGER,
    color TEXT,
    capacity INTEGER DEFAULT 0,
    vehicle_type TEXT CHECK(vehicle_type IN ('bus', 'minibus', 'van', 'car', 'other')),
    fuel_type TEXT,
    insurance_expiry DATE,
    roadworthy_expiry DATE,
    status TEXT DEFAULT 'active' CHECK(status IN ('active', 'maintenance', 'retired', 'sold')),
    last_service_date DATE,
    next_service_date DATE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ROUTES
  -- =============================================
  CREATE TABLE IF NOT EXISTS routes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    description TEXT,
    start_point TEXT NOT NULL,
    end_point TEXT NOT NULL,
    distance_km REAL,
    estimated_time_minutes INTEGER,
    status TEXT DEFAULT 'active' CHECK(status IN ('active', 'inactive', 'suspended')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- PICKUP POINTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS pickup_points (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    route_id INTEGER NOT NULL REFERENCES routes(id),
    name TEXT NOT NULL,
    address TEXT,
    latitude REAL,
    longitude REAL,
    pickup_time TIME,
    dropoff_time TIME,
    sequence_order INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- VEHICLE ROUTE ASSIGNMENTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS vehicle_routes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    vehicle_id INTEGER NOT NULL REFERENCES vehicles(id),
    route_id INTEGER NOT NULL REFERENCES routes(id),
    driver_id INTEGER REFERENCES users(id),
    conductor_id INTEGER REFERENCES users(id),
    start_time TIME,
    end_time TIME,
    days_of_week TEXT,
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- TRANSPORT ALLOCATIONS
  -- =============================================
  CREATE TABLE IF NOT EXISTS transport_allocations (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    route_id INTEGER NOT NULL REFERENCES routes(id),
    pickup_point_id INTEGER REFERENCES pickup_points(id),
    vehicle_route_id INTEGER REFERENCES vehicle_routes(id),
    fee_amount REAL DEFAULT 0,
    is_active INTEGER DEFAULT 1,
    effective_from DATE,
    effective_to DATE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('Transport tables created.');

// ========================================
// FRONT OFFICE MODULE
// ========================================
db.exec(`
  -- =============================================
  -- ADMISSION ENQUIRIES
  -- =============================================
  CREATE TABLE IF NOT EXISTS admission_enquiries (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    full_name TEXT NOT NULL,
    email TEXT,
    phone TEXT NOT NULL,
    address TEXT,
    class_interested TEXT,
    source TEXT,
    enquiry_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    follow_up_date DATE,
    status TEXT DEFAULT 'new' CHECK(status IN ('new', 'contacted', 'visited', 'enrolled', 'not-interested', 'closed')),
    assigned_to INTEGER REFERENCES users(id),
    notes TEXT,
    next_action TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- VISITOR LOGS
  -- =============================================
  CREATE TABLE IF NOT EXISTS visitor_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    visitor_name TEXT NOT NULL,
    visitor_type TEXT CHECK(visitor_type IN ('parent', 'vendor', 'government', 'media', 'other')),
    phone TEXT,
    email TEXT,
    id_number TEXT,
    purpose TEXT,
    person_to_visit TEXT,
    check_in DATETIME DEFAULT CURRENT_TIMESTAMP,
    check_out DATETIME,
    badge_number TEXT,
    remarks TEXT,
    created_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- PHONE CALL LOGS
  -- =============================================
  CREATE TABLE IF NOT EXISTS phone_call_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    caller_name TEXT,
    caller_phone TEXT,
    caller_type TEXT CHECK(caller_type IN ('parent', 'student', 'vendor', 'government', 'other')),
    direction TEXT DEFAULT 'incoming' CHECK(direction IN ('incoming', 'outgoing')),
    call_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    duration_seconds INTEGER,
    purpose TEXT,
    response TEXT,
    follow_up_required INTEGER DEFAULT 0,
    follow_up_date DATE,
    handled_by INTEGER REFERENCES users(id),
    notes TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- POSTAL DISPATCH
  -- =============================================
  CREATE TABLE IF NOT EXISTS postal_dispatch (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    type TEXT DEFAULT 'dispatch' CHECK(type IN ('dispatch', 'receive')),
    reference_number TEXT UNIQUE,
    sender TEXT NOT NULL,
    receiver TEXT NOT NULL,
    address TEXT,
    courier TEXT,
    tracking_number TEXT,
    dispatch_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    received_date DATETIME,
    received_by INTEGER REFERENCES users(id),
    description TEXT,
    status TEXT DEFAULT 'pending' CHECK(status IN ('pending', 'sent', 'delivered', 'returned')),
    created_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- COMPLAINTS
  -- =============================================
  CREATE TABLE IF NOT EXISTS complaints (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    complainant_name TEXT NOT NULL,
    complainant_type TEXT CHECK(complainant_type IN ('parent', 'student', 'staff', 'visitor', 'other')),
    contact_phone TEXT,
    contact_email TEXT,
    category TEXT NOT NULL,
    priority TEXT DEFAULT 'medium' CHECK(priority IN ('low', 'medium', 'high', 'urgent')),
    subject TEXT NOT NULL,
    description TEXT NOT NULL,
    date_received DATETIME DEFAULT CURRENT_TIMESTAMP,
    assigned_to INTEGER REFERENCES users(id),
    status TEXT DEFAULT 'open' CHECK(status IN ('open', 'investigating', 'resolved', 'closed', 'rejected')),
    resolution TEXT,
    resolved_by INTEGER REFERENCES users(id),
    resolved_at DATETIME,
    rating INTEGER,
    feedback TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('Front Office tables created.');

// ========================================
// NEW ENTITIES FOR ACADEMIC MODULE
// ========================================
db.exec(`
  -- =============================================
  -- DEPARTMENTS TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS departments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    head_teacher_id INTEGER REFERENCES users(id),
    description TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending' CHECK(sync_status IN ('synced', 'pending', 'conflict')),
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- SUBJECTS (Extended with department_id and credits)
  -- =============================================
  CREATE TABLE IF NOT EXISTS subjects_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    code TEXT,
    department_id INTEGER REFERENCES departments(id),
    teacher_id INTEGER REFERENCES users(id),
    credits REAL DEFAULT 0,
    description TEXT,
    class_id INTEGER REFERENCES classes(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- COURSES TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS courses (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    name TEXT NOT NULL,
    subject_id INTEGER REFERENCES subjects_new(id),
    teacher_id INTEGER REFERENCES users(id),
    description TEXT,
    schedule TEXT,
    start_date DATE,
    end_date DATE,
    max_students INTEGER DEFAULT 30,
    status TEXT DEFAULT 'active' CHECK(status IN ('active', 'inactive', 'completed', 'cancelled')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- COURSE ENROLMENTS TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS course_enrolments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    course_id INTEGER NOT NULL REFERENCES courses(id),
    enrolled_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'active' CHECK(status IN ('active', 'dropped', 'completed')),
    progress REAL DEFAULT 0,
    completed_at DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ASSIGNMENTS TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS assignments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    course_id INTEGER NOT NULL REFERENCES courses(id),
    title TEXT NOT NULL,
    description TEXT,
    instructions TEXT,
    due_date DATETIME,
    max_score REAL DEFAULT 100,
    submission_type TEXT DEFAULT 'file' CHECK(submission_type IN ('file', 'text', 'online', 'offline')),
    allow_late_submission INTEGER DEFAULT 0,
    is_published INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- SUBMISSIONS TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS submissions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    assignment_id INTEGER NOT NULL REFERENCES assignments(id),
    student_id INTEGER NOT NULL REFERENCES users(id),
    content TEXT,
    file_path TEXT,
    submitted_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'submitted' CHECK(status IN ('submitted', 'graded', 'returned', 'late')),
    grade REAL,
    feedback TEXT,
    graded_by INTEGER REFERENCES users(id),
    graded_at DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- COURSE GRADES TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS course_grades (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    course_id INTEGER NOT NULL REFERENCES courses(id),
    score REAL,
    letter_grade TEXT,
    term TEXT,
    academic_year TEXT,
    remarks TEXT,
    graded_by INTEGER REFERENCES users(id),
    graded_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- ATTENDANCE (Updated with subject_id)
  -- =============================================
  CREATE TABLE IF NOT EXISTS attendance_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    student_id INTEGER NOT NULL REFERENCES users(id),
    subject_id INTEGER REFERENCES subjects_new(id),
    date DATE NOT NULL,
    status TEXT NOT NULL CHECK(status IN ('present', 'absent', 'late', 'excused')),
    remarks TEXT,
    marked_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- MESSAGES (Enhanced with from/to user tracking)
  -- =============================================
  CREATE TABLE IF NOT EXISTS messages_new (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    from_user_id INTEGER REFERENCES users(id),
    to_user_id INTEGER REFERENCES users(id),
    subject TEXT NOT NULL,
    body TEXT,
    is_read INTEGER DEFAULT 0,
    is_announcement INTEGER DEFAULT 0,
    priority TEXT DEFAULT 'normal' CHECK(priority IN ('low', 'normal', 'high', 'urgent')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- CALENDAR EVENTS TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS calendar_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    title TEXT NOT NULL,
    description TEXT,
    date DATE NOT NULL,
    time TIME,
    end_time TIME,
    location TEXT,
    type TEXT CHECK(type IN ('holiday', 'exam', 'meeting', 'activity', 'deadline', 'event', 'other')),
    is_all_day INTEGER DEFAULT 0,
    is_public INTEGER DEFAULT 1,
    academic_year TEXT,
    created_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- NOTICE BOARD
  -- =============================================
  CREATE TABLE IF NOT EXISTS notices (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    category TEXT DEFAULT 'Academic',
    priority TEXT DEFAULT 'Normal'
      CHECK(priority IN ('Normal','Important','Urgent')),
    audience TEXT DEFAULT 'All',
    is_pinned INTEGER DEFAULT 0,
    created_by INTEGER REFERENCES users(id),
    expiry_date DATE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- LIBRARY BOOKS
  -- =============================================
  CREATE TABLE IF NOT EXISTS library_books (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    isbn TEXT,
    title TEXT NOT NULL,
    author TEXT,
    category TEXT,
    publisher TEXT,
    year_published INTEGER,
    total_copies INTEGER DEFAULT 1,
    available_copies INTEGER DEFAULT 1,
    shelf_location TEXT,
    status TEXT DEFAULT 'available',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- LIBRARY ISSUES
  -- =============================================
  CREATE TABLE IF NOT EXISTS library_issues (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT UNIQUE,
    book_id INTEGER REFERENCES library_books(id),
    user_id INTEGER REFERENCES users(id),
    issue_date DATE,
    due_date DATE,
    return_date DATE,
    status TEXT DEFAULT 'issued',
    issued_by INTEGER REFERENCES users(id),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_deleted INTEGER DEFAULT 0
  );

  -- =============================================
  -- SETTINGS TABLE
  -- =============================================
  CREATE TABLE IF NOT EXISTS settings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    key TEXT UNIQUE NOT NULL,
    value TEXT,
    description TEXT,
    category TEXT DEFAULT 'general',
    is_encrypted INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_synced_at DATETIME,
    sync_status TEXT DEFAULT 'pending',
    is_deleted INTEGER DEFAULT 0
  );
`);

console.log('New entities tables created.');

// ========================================
// CREATE INDEXES
// ========================================
db.exec(`
  -- Sync-related indexes
  CREATE INDEX IF NOT EXISTS idx_users_sync ON users(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_users_uid ON users(uid);
  CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
  CREATE INDEX IF NOT EXISTS idx_users_role ON users(role);

  CREATE INDEX IF NOT EXISTS idx_classes_sync ON classes(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_subjects_sync ON subjects(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_enrollments_sync ON enrollments(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_attendance_sync ON attendance(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_fees_sync ON student_fees(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_payments_sync ON payments(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_messages_sync ON messages(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_events_sync ON events(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_expenses_sync ON expenses(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_grades_sync ON grades(sync_status, is_deleted);

  -- Performance indexes
  CREATE INDEX IF NOT EXISTS idx_attendance_date ON attendance(date);
  CREATE INDEX IF NOT EXISTS idx_attendance_student ON attendance(student_id);
  CREATE INDEX IF NOT EXISTS idx_student_fees_status ON student_fees(status);
  CREATE INDEX IF NOT EXISTS idx_payments_date ON payments(payment_date);
  CREATE INDEX IF NOT EXISTS idx_expenses_date ON expenses(expense_date);
  CREATE INDEX IF NOT EXISTS idx_leave_requests_status ON leave_requests(status);
  CREATE INDEX IF NOT EXISTS idx_exam_attempts_student ON exam_attempts(student_id);
  CREATE INDEX IF NOT EXISTS idx_complaints_status ON complaints(status);

  -- Sync logs
  CREATE INDEX IF NOT EXISTS idx_sync_logs_table ON sync_logs(table_name, operation);
  CREATE INDEX IF NOT EXISTS idx_sync_logs_created ON sync_logs(created_at);

  -- New entity indexes
  CREATE INDEX IF NOT EXISTS idx_departments_sync ON departments(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_subjects_new_sync ON subjects_new(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_courses_sync ON courses(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_course_enrolments_sync ON course_enrolments(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_assignments_sync ON assignments(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_submissions_sync ON submissions(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_course_grades_sync ON course_grades(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_attendance_new_sync ON attendance_new(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_messages_new_sync ON messages_new(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_calendar_events_sync ON calendar_events(sync_status, is_deleted);
  CREATE INDEX IF NOT EXISTS idx_settings_sync ON settings(sync_status, is_deleted);

  -- Performance indexes for new tables
  CREATE INDEX IF NOT EXISTS idx_courses_subject ON courses(subject_id);
  CREATE INDEX IF NOT EXISTS idx_courses_teacher ON courses(teacher_id);
  CREATE INDEX IF NOT EXISTS idx_assignments_course ON assignments(course_id);
  CREATE INDEX IF NOT EXISTS idx_assignments_due_date ON assignments(due_date);
  CREATE INDEX IF NOT EXISTS idx_submissions_assignment ON submissions(assignment_id);
  CREATE INDEX IF NOT EXISTS idx_submissions_student ON submissions(student_id);
  CREATE INDEX IF NOT EXISTS idx_course_grades_student ON course_grades(student_id);
  CREATE INDEX IF NOT EXISTS idx_course_grades_course ON course_grades(course_id);
  CREATE INDEX IF NOT EXISTS idx_calendar_events_date ON calendar_events(date);
  CREATE INDEX IF NOT EXISTS idx_messages_from ON messages_new(from_user_id);
  CREATE INDEX IF NOT EXISTS idx_messages_to ON messages_new(to_user_id);
  CREATE INDEX IF NOT EXISTS idx_messages_read ON messages_new(is_read);

  -- Library indexes
  CREATE INDEX IF NOT EXISTS idx_library_books_isbn ON library_books(isbn);
  CREATE INDEX IF NOT EXISTS idx_library_books_title ON library_books(title);
  CREATE INDEX IF NOT EXISTS idx_library_books_category ON library_books(category);
  CREATE INDEX IF NOT EXISTS idx_library_books_status ON library_books(status);
  CREATE INDEX IF NOT EXISTS idx_library_issues_book ON library_issues(book_id);
  CREATE INDEX IF NOT EXISTS idx_library_issues_user ON library_issues(user_id);
  CREATE INDEX IF NOT EXISTS idx_library_issues_status ON library_issues(status);
`);

console.log('Indexes created.');

// ========================================
// SEED DEFAULT DATA
// ========================================

// Seed demo accounts
const createUser = (email, password, role, first_name, last_name, phone) => {
  const exists = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
  if (!exists) {
    const hashedPassword = bcrypt.hashSync(password, 10);
    const uid = require('uuid').v4();
    db.prepare(`
      INSERT INTO users (uid, email, password, role, first_name, last_name, phone)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `).run(uid, email, hashedPassword, role, first_name, last_name, phone);
    console.log(`Created ${role}: ${email}`);
  }
};

createUser('admin@school.com', 'admin123', 'admin', 'System', 'Administrator', '+1234567890');
createUser('teacher@school.com', 'teacher123', 'teacher', 'Jane', 'Smith', '+1234567891');
createUser('student@school.com', 'student123', 'student', 'John', 'Student', '+1234567892');
createUser('parent@school.com', 'parent123', 'parent', 'Mike', 'Parent', '+1234567893');

// Seed classes
const classCount = db.prepare('SELECT COUNT(*) as count FROM classes').get().count;
if (classCount === 0) {
  const insertClass = db.prepare('INSERT INTO classes (uid, name, section) VALUES (?, ?, ?)');
  insertClass.run(require('uuid').v4(), 'Grade 1', 'A');
  insertClass.run(require('uuid').v4(), 'Grade 2', 'A');
  insertClass.run(require('uuid').v4(), 'Grade 3', 'A');
  insertClass.run(require('uuid').v4(), 'Grade 4', 'A');
  insertClass.run(require('uuid').v4(), 'Grade 5', 'A');
  console.log('Created sample classes');
}

// Seed subjects
const subjectCount = db.prepare('SELECT COUNT(*) as count FROM subjects').get().count;
if (subjectCount === 0) {
  const insertSubject = db.prepare('INSERT INTO subjects (uid, name, class_id) VALUES (?, ?, ?)');
  insertSubject.run(require('uuid').v4(), 'Mathematics', 1);
  insertSubject.run(require('uuid').v4(), 'English', 1);
  insertSubject.run(require('uuid').v4(), 'Science', 1);
  insertSubject.run(require('uuid').v4(), 'Mathematics', 2);
  insertSubject.run(require('uuid').v4(), 'English', 2);
  insertSubject.run(require('uuid').v4(), 'Science', 2);
  console.log('Created sample subjects');
}

// Seed leave types
const leaveTypeCount = db.prepare('SELECT COUNT(*) as count FROM leave_types').get().count;
if (leaveTypeCount === 0) {
  const insert = db.prepare('INSERT INTO leave_types (uid, name, code, max_days_per_year) VALUES (?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'Annual Leave', 'AL', 21);
  insert.run(require('uuid').v4(), 'Sick Leave', 'SL', 14);
  insert.run(require('uuid').v4(), 'Maternity Leave', 'ML', 90);
  insert.run(require('uuid').v4(), 'Paternity Leave', 'PL', 10);
  insert.run(require('uuid').v4(), 'Emergency Leave', 'EL', 5);
  console.log('Created leave types');
}

// Seed salary grades
const salaryGradeCount = db.prepare('SELECT COUNT(*) as count FROM salary_grades').get().count;
if (salaryGradeCount === 0) {
  const insert = db.prepare('INSERT INTO salary_grades (uid, name, basic_salary, housing_allowance, transport_allowance) VALUES (?, ?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'Grade A (Entry)', 50000, 10000, 5000);
  insert.run(require('uuid').v4(), 'Grade B (Mid)', 80000, 15000, 8000);
  insert.run(require('uuid').v4(), 'Grade C (Senior)', 120000, 20000, 10000);
  console.log('Created salary grades');
}

// Seed item categories
const itemCatCount = db.prepare('SELECT COUNT(*) as count FROM item_categories').get().count;
if (itemCatCount === 0) {
  const insert = db.prepare('INSERT INTO item_categories (uid, name, code) VALUES (?, ?, ?)');
  insert.run(require('uuid').v4(), 'Stationery', 'STAT');
  insert.run(require('uuid').v4(), 'Electronics', 'ELEC');
  insert.run(require('uuid').v4(), 'Furniture', 'FURN');
  insert.run(require('uuid').v4(), 'Cleaning Supplies', 'CLEN');
  console.log('Created item categories');
}

// Seed exam groups
const examGroupCount = db.prepare('SELECT COUNT(*) as count FROM exam_groups').get().count;
if (examGroupCount === 0) {
  const insert = db.prepare('INSERT INTO exam_groups (uid, name, exam_type, duration_minutes) VALUES (?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'Mathematics Quiz 1', 'quiz', 30);
  insert.run(require('uuid').v4(), 'English Test', 'test', 60);
  insert.run(require('uuid').v4(), 'Science Final Exam', 'final', 120);
  console.log('Created exam groups');
}

// Seed hostels
const hostelCount = db.prepare('SELECT COUNT(*) as count FROM hostels').get().count;
if (hostelCount === 0) {
  const insert = db.prepare('INSERT INTO hostels (uid, name, type, capacity) VALUES (?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'Boys Hostel A', 'boys', 100);
  insert.run(require('uuid').v4(), 'Girls Hostel B', 'girls', 100);
  insert.run(require('uuid').v4(), 'New Hostel', 'co-ed', 50);
  console.log('Created hostels');
}

// Seed vehicles
const vehicleCount = db.prepare('SELECT COUNT(*) as count FROM vehicles').get().count;
if (vehicleCount === 0) {
  const insert = db.prepare('INSERT INTO vehicles (uid, registration_number, model, capacity, vehicle_type) VALUES (?, ?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'ABC 123', 'Toyota Coaster', 30, 'bus');
  insert.run(require('uuid').v4(), 'DEF 456', 'Nissan Civilian', 20, 'minibus');
  insert.run(require('uuid').v4(), 'GHI 789', 'Toyota Hiace', 14, 'van');
  console.log('Created vehicles');
}

// Seed system settings
const settingCount = db.prepare('SELECT COUNT(*) as count FROM system_settings').get().count;
if (settingCount === 0) {
  const insert = db.prepare('INSERT INTO system_settings (key, value, category) VALUES (?, ?, ?)');
  insert.run('school_name', 'Africa Alert School', 'general');
  insert.run('academic_year', '2026', 'academic');
  insert.run('term', 'Term 1', 'academic');
  insert.run('currency', 'USD', 'general');
  insert.run('paynow_integration_id', '', 'payment');
  insert.run('paynow_integration_key', '', 'payment');
  insert.run('paynow_callback_url', '', 'payment');
  insert.run('supabase_url', 'https://api.next_gen.techarvest.co.zw', 'sync');
  insert.run('supabase_key', '', 'sync');
  insert.run('sync_interval_seconds', '30', 'sync');
  console.log('Created system settings');
}

// Initialize sync config
db.prepare('INSERT OR REPLACE INTO sync_config (key, value) VALUES (?, ?)').run('last_sync', '');
db.prepare('INSERT OR REPLACE INTO sync_config (key, value) VALUES (?, ?)').run('sync_running', '0');

// ========================================
// SEED NEW ENTITY DATA
// ========================================

// Seed departments
const deptCount = db.prepare('SELECT COUNT(*) as count FROM departments').get().count;
if (deptCount === 0) {
  const insert = db.prepare('INSERT INTO departments (uid, name, description) VALUES (?, ?, ?)');
  insert.run(require('uuid').v4(), 'Mathematics', 'Department for all mathematics courses and tutoring');
  insert.run(require('uuid').v4(), 'Languages', 'Department for English and other language studies');
  insert.run(require('uuid').v4(), 'Sciences', 'Department for Physics, Chemistry, Biology and Environmental Science');
  insert.run(require('uuid').v4(), 'Humanities', 'Department for History, Geography and Social Studies');
  insert.run(require('uuid').v4(), 'Technology', 'Department for Computer Science and IT courses');
  console.log('Created departments');
}

// Seed subjects_new
const subjectNewCount = db.prepare('SELECT COUNT(*) as count FROM subjects_new').get().count;
if (subjectNewCount === 0) {
  const insert = db.prepare('INSERT INTO subjects_new (uid, name, code, department_id, credits) VALUES (?, ?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'Calculus', 'MATH101', 1, 4);
  insert.run(require('uuid').v4(), 'Literature', 'ENG101', 2, 3);
  insert.run(require('uuid').v4(), 'Physics', 'PHY101', 3, 4);
  console.log('Created subjects_new');
}

// Seed courses
const courseCount = db.prepare('SELECT COUNT(*) as count FROM courses').get().count;
if (courseCount === 0) {
  const insert = db.prepare('INSERT INTO courses (uid, name, subject_id, schedule, status) VALUES (?, ?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'Advanced Mathematics', 1, 'Mon/Wed 9:00-11:00', 'active');
  insert.run(require('uuid').v4(), 'English Literature', 2, 'Tue/Thu 10:00-12:00', 'active');
  insert.run(require('uuid').v4(), 'Physics Fundamentals', 3, 'Mon/Wed/Fri 14:00-16:00', 'active');
  console.log('Created courses');
}

// Seed assignments
const assignCount = db.prepare('SELECT COUNT(*) as count FROM assignments').get().count;
if (assignCount === 0) {
  const insert = db.prepare('INSERT INTO assignments (uid, course_id, title, instructions, due_date, is_published) VALUES (?, ?, ?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 1, 'Algebra Homework 1', 'Complete exercises 1-20 from Chapter 3', '2026-06-15', 1);
  insert.run(require('uuid').v4(), 1, 'Calculus Quiz', 'Online quiz covering derivatives', '2026-06-10', 1);
  insert.run(require('uuid').v4(), 2, 'Essay: Shakespeare', 'Write a 2000-word essay on Macbeth', '2026-06-20', 1);
  console.log('Created assignments');
}

// Seed calendar events
const calCount = db.prepare('SELECT COUNT(*) as count FROM calendar_events').get().count;
if (calCount === 0) {
  const insert = db.prepare('INSERT INTO calendar_events (uid, title, date, time, location, type) VALUES (?, ?, ?, ?, ?, ?)');
  insert.run(require('uuid').v4(), 'Mid-Term Exams', '2026-06-15', '08:00', 'Main Hall', 'exam');
  insert.run(require('uuid').v4(), 'Parent-Teacher Meeting', '2026-06-22', '14:00', 'Classroom A1', 'meeting');
  insert.run(require('uuid').v4(), 'Independence Day Holiday', '2026-06-18', null, null, 'holiday');
  insert.run(require('uuid').v4(), 'Sports Day', '2026-06-25', '09:00', 'Sports Ground', 'activity');
  console.log('Created calendar events');
}

// Seed settings
const settingsCount = db.prepare('SELECT COUNT(*) as count FROM settings').get().count;
if (settingsCount === 0) {
  const insert = db.prepare('INSERT INTO settings (key, value, category) VALUES (?, ?, ?)');
  insert.run('school_name', 'Africa Alert Academy', 'general');
  insert.run('school_address', '123 Education Street, Harare', 'general');
  insert.run('contact_email', 'info@africaalert.edu.zw', 'general');
  insert.run('contact_phone', '+263 77 123 4567', 'general');
  insert.run('term_start_date', '2026-01-15', 'academic');
  insert.run('term_end_date', '2026-04-15', 'academic');
  insert.run('working_hours_start', '08:00', 'general');
  insert.run('working_hours_end', '17:00', 'general');
  console.log('Created settings');
}

console.log('Database initialization complete!');
console.log('Total tables: Core + 7 Modules + New Entities + Library + Sync + Settings');