-- Phase 1-3: ميزات شاملة
-- إعدادات المختبر
INSERT INTO settings (setting_key, setting_value, updated_at) VALUES ('lab_name', 'مختبر تحاليل', NOW()) ON DUPLICATE KEY UPDATE updated_at = NOW();
INSERT INTO settings (setting_key, setting_value, updated_at) VALUES ('lab_phone', '', NOW()) ON DUPLICATE KEY UPDATE updated_at = NOW();
INSERT INTO settings (setting_key, setting_value, updated_at) VALUES ('lab_address', '', NOW()) ON DUPLICATE KEY UPDATE updated_at = NOW();

-- مرفقات المرضى (PDF/صور)
CREATE TABLE IF NOT EXISTS patient_attachments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id INT NOT NULL,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_type VARCHAR(50) NULL,
    uploaded_by INT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (patient_id) REFERENCES patients(id) ON DELETE CASCADE,
    FOREIGN KEY (uploaded_by) REFERENCES users(id)
);

-- ديون المرضى
CREATE TABLE IF NOT EXISTS patient_balances (
    id INT AUTO_INCREMENT PRIMARY KEY,
    patient_id INT NOT NULL,
    order_id INT NULL,
    amount DECIMAL(10,2) NOT NULL,
    balance_type ENUM('debit','credit') NOT NULL,
    note VARCHAR(255) NULL,
    created_by INT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (patient_id) REFERENCES patients(id),
    FOREIGN KEY (order_id) REFERENCES lab_orders(id),
    FOREIGN KEY (created_by) REFERENCES users(id)
);

-- تاريخ انتهاء المخزون (تشغيل كل سطر مرة واحدة؛ تجاهل خطأ العمود الموجود)
-- ALTER TABLE inventory_items ADD COLUMN expiry_date DATE NULL;
-- ALTER TABLE inventory_items ADD COLUMN batch_number VARCHAR(100) NULL;

-- توقيع الفني
-- ALTER TABLE results ADD COLUMN tech_name VARCHAR(150) NULL;

-- بوابة المريض (في run_005_alter)
-- ALTER TABLE patients ADD COLUMN default_doctor_id INT NULL;

-- دور الاستقبال
INSERT INTO roles (name) SELECT 'Reception' WHERE NOT EXISTS (SELECT 1 FROM roles WHERE name = 'Reception');
INSERT INTO roles (name) SELECT 'Doctor' WHERE NOT EXISTS (SELECT 1 FROM roles WHERE name = 'Doctor');
