-- Smart Doctor Portal - حسابات الأطباء وربطهم بالمختبرات
-- يسمح للأطباء بتسجيل الدخول ورؤية مرضاهم ونتائج تحاليلهم من المختبرات المرتبطة

-- جدول حسابات الأطباء (ربط طبيب بمختبر + بيانات الدخول)
CREATE TABLE IF NOT EXISTS doctor_accounts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    doctor_id INT NOT NULL,
    tenant_id INT NOT NULL,
    username VARCHAR(100) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    last_login_at DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    created_by INT NULL,
    UNIQUE KEY uk_doctor_tenant (doctor_id, tenant_id),
    UNIQUE KEY uk_username (username),
    INDEX idx_tenant (tenant_id),
    INDEX idx_doctor (doctor_id),
    FOREIGN KEY (doctor_id) REFERENCES doctors(id) ON DELETE CASCADE,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    FOREIGN KEY (created_by) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- جدول سجل تحليل النتائج للمرضى (للمساعدة في اكتشاف الأنماط والأمراض)
CREATE TABLE IF NOT EXISTS patient_medical_notes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id INT NOT NULL,
    doctor_account_id INT NULL,
    order_id INT NULL,
    note_type ENUM('general','lab_review','diagnosis','follow_up','allergy','medication') NOT NULL DEFAULT 'general',
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (patient_id) REFERENCES patients(id) ON DELETE CASCADE,
    FOREIGN KEY (doctor_account_id) REFERENCES doctor_accounts(id) ON DELETE SET NULL,
    FOREIGN KEY (order_id) REFERENCES lab_orders(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
