// Local IndexedDB Implementation for Database
const DB_NAME = 'WarehouseDB';
const DB_VERSION = 7; 

let db;

function initDB() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);

    request.onupgradeneeded = (event) => {
      const database = event.target.result;
      if (!database.objectStoreNames.contains('users')) {
        const usersOS = database.createObjectStore('users', { keyPath: 'id', autoIncrement: true });
        usersOS.createIndex('username', 'username', { unique: true });
      }
      if (!database.objectStoreNames.contains('warehouses')) {
        database.createObjectStore('warehouses', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('items')) {
        database.createObjectStore('items', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('projects')) {
        database.createObjectStore('projects', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('transactions')) {
        database.createObjectStore('transactions', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('notifications')) {
        database.createObjectStore('notifications', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('contacts')) {
        database.createObjectStore('contacts', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('units')) {
        database.createObjectStore('units', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('accounts')) {
        database.createObjectStore('accounts', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('journal_entries')) {
        database.createObjectStore('journal_entries', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('activity_logs')) {
        database.createObjectStore('activity_logs', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('subcontracts')) {
        database.createObjectStore('subcontracts', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('subcontract_abstracts')) {
        database.createObjectStore('subcontract_abstracts', { keyPath: 'id', autoIncrement: true });
      }
      if (!database.objectStoreNames.contains('client_abstracts')) {
        database.createObjectStore('client_abstracts', { keyPath: 'id', autoIncrement: true });
      }
    };

    request.onblocked = () => {
      alert("الرجاء إغلاق أي نافذة أو تبويب آخر مفتوح للبرنامج حتى يتم تحديث النظام!");
    };

    request.onsuccess = (event) => {
      db = event.target.result;
      
      // Create default admin user if not exists
      getAll('users').then(users => {
        if(users.length === 0) {
          add('users', { username: 'admin', password: '123', role: 'مدير عام', warehouse_id: null });
        }
      });
      
      // Create default warehouse if not exists
      getAll('warehouses').then(warehouses => {
        if(warehouses.length === 0) {
          add('warehouses', { name: 'المخزن الرئيسي', location: 'المقر الرئيسي' });
        }
      });
      resolve();
    };

    request.onerror = (event) => reject(event.target.error);
  });
}

function getAll(storeName) {
  return new Promise((resolve, reject) => {
    try {
      const transaction = db.transaction([storeName], 'readonly');
      const store = transaction.objectStore(storeName);
      const request = store.getAll();
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    } catch(e) {
      resolve([]); // Return empty if store doesn't exist yet
    }
  });
}

function add(storeName, data) {
  return new Promise((resolve, reject) => {
    try {
      const transaction = db.transaction([storeName], 'readwrite');
      const store = transaction.objectStore(storeName);
      const request = store.add(data);
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    } catch(e) { reject(e); }
  });
}

function update(storeName, data) {
  return new Promise((resolve, reject) => {
    try {
      const transaction = db.transaction([storeName], 'readwrite');
      const store = transaction.objectStore(storeName);
      const request = store.put(data);
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    } catch(e) { reject(e); }
  });
}

function remove(storeName, id) {
    return new Promise((resolve, reject) => {
      try {
        const transaction = db.transaction([storeName], 'readwrite');
        const store = transaction.objectStore(storeName);
        const request = store.delete(id);
        request.onsuccess = () => resolve(request.result);
        request.onerror = () => reject(request.error);
      } catch(e) { reject(e); }
    });
}

function login(username, password) {
  return new Promise((resolve, reject) => {
    getAll('users').then(users => {
      const user = users.find(u => u.username === username && u.password === password);
      resolve(user || null);
    });
  });
}

window.DB = {
  initDB,
  getAll,
  add,
  update,
  remove,
  login
};
