<?php
require_once 'db/config.php';

try {
    $db = db();
    
    // Create tables
    $sql = "
    CREATE TABLE IF NOT EXISTS departments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS doctors (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL,
        specialization_en VARCHAR(255),
        specialization_ar VARCHAR(255),
        department_id INT,
        tel VARCHAR(20),
        email VARCHAR(100),
        FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS nurses (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL,
        department_id INT,
        tel VARCHAR(20),
        email VARCHAR(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS insurance_companies (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL,
        email VARCHAR(255),
        phone VARCHAR(50),
        contact_info TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS patients (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        phone VARCHAR(50),
        dob DATE,
        gender VARCHAR(10),
        blood_group VARCHAR(5),
        address TEXT,
        insurance_company_id INT NULL,
        policy_number VARCHAR(100) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (insurance_company_id) REFERENCES insurance_companies(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS appointments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        patient_id INT,
        doctor_id INT,
        nurse_id INT,
        visit_type ENUM('Clinic', 'Home') DEFAULT 'Clinic',
        address TEXT,
        start_time DATETIME NOT NULL,
        end_time DATETIME NOT NULL,
        status ENUM('Scheduled', 'Completed', 'Cancelled') DEFAULT 'Scheduled',
        reason TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (patient_id) REFERENCES patients(id) ON DELETE CASCADE,
        FOREIGN KEY (doctor_id) REFERENCES doctors(id) ON DELETE CASCADE,
        FOREIGN KEY (nurse_id) REFERENCES nurses(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS visits (
        id INT AUTO_INCREMENT PRIMARY KEY,
        patient_id INT,
        doctor_id INT,
        appointment_id INT NULL,
        visit_date DATETIME DEFAULT CURRENT_TIMESTAMP,
        weight VARCHAR(50),
        blood_pressure VARCHAR(50),
        heart_rate VARCHAR(50),
        temperature VARCHAR(50),
        symptoms TEXT,
        diagnosis TEXT,
        treatment_plan TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (patient_id) REFERENCES patients(id) ON DELETE CASCADE,
        FOREIGN KEY (doctor_id) REFERENCES doctors(id) ON DELETE CASCADE,
        FOREIGN KEY (appointment_id) REFERENCES appointments(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS provisional_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        visit_id INT,
        report_type VARCHAR(255),
        findings TEXT,
        recommendations TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (visit_id) REFERENCES visits(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS bills (
        id INT AUTO_INCREMENT PRIMARY KEY,
        patient_id INT,
        visit_id INT NULL,
        total_amount DECIMAL(10, 2) DEFAULT 0.00,
        insurance_covered DECIMAL(10, 2) DEFAULT 0.00,
        patient_payable DECIMAL(10, 2) DEFAULT 0.00,
        status ENUM('Pending', 'Paid') DEFAULT 'Pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (patient_id) REFERENCES patients(id) ON DELETE CASCADE,
        FOREIGN KEY (visit_id) REFERENCES visits(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS bill_items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        bill_id INT,
        description VARCHAR(255),
        amount DECIMAL(10, 2),
        FOREIGN KEY (bill_id) REFERENCES bills(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS employees (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL,
        dob DATE,
        mobile VARCHAR(50),
        email VARCHAR(100),
        department_id INT,
        passion_en TEXT,
        passion_ar TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS positions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL,
        description_en TEXT,
        description_ar TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS test_groups (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS laboratory_tests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        group_id INT,
        name_en VARCHAR(255) NOT NULL,
        name_ar VARCHAR(255) NOT NULL,
        price DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
        normal_range VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (group_id) REFERENCES test_groups(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS laboratory_inquiries (
        id INT AUTO_INCREMENT PRIMARY KEY,
        patient_name VARCHAR(255) NOT NULL,
        test_id INT,
        inquiry_date DATETIME DEFAULT CURRENT_TIMESTAMP,
        source ENUM('Internal', 'External') DEFAULT 'Internal',
        status ENUM('Pending', 'Completed', 'Cancelled') DEFAULT 'Pending',
        notes TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (test_id) REFERENCES laboratory_tests(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    ";
    
    $db->exec($sql);

    // Migration for existing tables
    try {
        $db->exec("ALTER TABLE insurance_companies ADD COLUMN IF NOT EXISTS email VARCHAR(255)");
        $db->exec("ALTER TABLE insurance_companies ADD COLUMN IF NOT EXISTS phone VARCHAR(50)");
    } catch (Exception $e) {}

    try {
        $db->exec("ALTER TABLE patients ADD COLUMN IF NOT EXISTS insurance_company_id INT NULL");
        $db->exec("ALTER TABLE patients ADD COLUMN IF NOT EXISTS policy_number VARCHAR(100) NULL");
        $db->exec("ALTER TABLE patients ADD CONSTRAINT fk_patient_insurance FOREIGN KEY (insurance_company_id) REFERENCES insurance_companies(id) ON DELETE SET NULL");
    } catch (Exception $e) {}

    try {
        $db->exec("ALTER TABLE bills ADD COLUMN IF NOT EXISTS insurance_covered DECIMAL(10, 2) DEFAULT 0.00");
        $db->exec("ALTER TABLE bills ADD COLUMN IF NOT EXISTS patient_payable DECIMAL(10, 2) DEFAULT 0.00");
    } catch (Exception $e) {}

    try {
        $db->exec("ALTER TABLE doctors ADD COLUMN IF NOT EXISTS tel VARCHAR(20)");
        $db->exec("ALTER TABLE doctors ADD COLUMN IF NOT EXISTS email VARCHAR(100)");
    } catch (Exception $e) {}

    try {
        $db->exec("ALTER TABLE laboratory_tests ADD COLUMN IF NOT EXISTS normal_range VARCHAR(255)");
    } catch (Exception $e) {}
    
    // Seed departments
    $stmt = $db->query("SELECT COUNT(*) FROM departments");
    if ($stmt->fetchColumn() == 0) {
        $db->exec("INSERT INTO departments (id, name_en, name_ar) VALUES 
        (1, 'Cardiology', 'قسم القلب'),
        (2, 'Pediatrics', 'طب الأطفال'),
        (3, 'Emergency', 'الطوارئ'),
        (4, 'Neurology', 'الأعصاب')");
    }
    
    // Seed doctors
    $stmt = $db->query("SELECT COUNT(*) FROM doctors");
    if ($stmt->fetchColumn() == 0) {
        $db->exec("INSERT INTO doctors (id, name_en, name_ar, specialization_en, specialization_ar, department_id) VALUES 
        (1, 'Dr. Ahmed Ali', 'د. أحمد علي', 'Cardiologist', 'طبيب قلب', 1),
        (2, 'Dr. Sarah Smith', 'د. سارة سميث', 'Pediatrician', 'طبيب أطفال', 2),
        (3, 'Dr. John Doe', 'د. جون دو', 'Neurologist', 'طبيب أعصاب', 4)");
    }

    // Seed insurance companies
    $stmt = $db->query("SELECT COUNT(*) FROM insurance_companies");
    if ($stmt->fetchColumn() == 0) {
        $db->exec("INSERT INTO insurance_companies (name_en, name_ar, contact_info) VALUES 
        ('Bupa Arabia', 'بوبا العربية', '920000456'),
        ('Tawuniya', 'التعاونية', '920019990'),
        ('MedGulf', 'ميدغلف', '8004414444')");
    }

    // Seed test groups (Clear and re-seed with comprehensive list and normal ranges)
    // $db->exec("SET FOREIGN_KEY_CHECKS = 0");
    // $db->exec("TRUNCATE TABLE laboratory_tests");
    // $db->exec("TRUNCATE TABLE test_groups");
    // $db->exec("SET FOREIGN_KEY_CHECKS = 1");

    // Check if test groups exist before seeding
    $stmt = $db->query("SELECT COUNT(*) FROM test_groups");
    if ($stmt->fetchColumn() == 0) {
        $db->exec("INSERT INTO test_groups (id, name_en, name_ar) VALUES 
        (1, 'Hematology', 'علم الدم'),
        (2, 'Biochemistry', 'الكيمياء الحيوية'),
        (3, 'Microbiology', 'علم الأحياء الدقيقة'),
        (4, 'Serology', 'علم المصل'),
        (5, 'Immunology', 'علم المناعة'),
        (6, 'Hormones', 'الهرمونات'),
        (7, 'Coagulation', 'التخثر'),
        (8, 'Electrolytes', 'الأملاح والمعادن'),
        (9, 'Urine & Stool', 'البول والبراز'),
        (10, 'Cardiac Markers', 'واصمات القلب')");

        $db->exec("INSERT INTO laboratory_tests (group_id, name_en, name_ar, price, normal_range) VALUES 
        (1, 'Complete Blood Count (CBC)', 'عد دم كامل', 150.00, 'WBC: 4.5-11.0, RBC: 4.2-6.1, HGB: 12.0-17.5'),
        (1, 'ESR', 'سرعة الترسيب', 40.00, 'Men: <15 mm/hr, Women: <20 mm/hr'),
        (1, 'Reticulocyte count', 'عد الخلايا الشبكية', 60.00, '0.5% - 1.5%'),
        (1, 'Blood film', 'فيلم الدم', 80.00, 'Normal morphology'),
        
        (2, 'Fast Blood Sugar (FBS)', 'سكر الدم الصائم', 50.00, '70 - 99 mg/dL'),
        (2, 'HbA1c', 'السكر التراكمي', 120.00, '4.0% - 5.6%'),
        (2, 'Lipid Profile', 'فحص الدهون', 200.00, 'Chol: <200, Trig: <150, HDL: >40'),
        (2, 'Liver Function Test (LFT)', 'وظائف الكبد', 180.00, 'ALT: 7-55 U/L, AST: 8-48 U/L'),
        (2, 'Kidney Function Test (KFT)', 'وظائف الكلى', 150.00, 'Creatinine: 0.6-1.3 mg/dL'),
        (2, 'Uric Acid', 'حمض اليوريك', 60.00, 'Men: 3.4-7.0, Women: 2.4-6.0 mg/dL'),

        (3, 'Urine Culture', 'مزرعة البول', 250.00, 'No growth'),
        (3, 'Stool Culture', 'مزرعة البراز', 250.00, 'No growth'),
        (3, 'Blood Culture', 'مزرعة الدم', 450.00, 'No growth'),
        (3, 'Throat Swab', 'مسحة الحلق', 200.00, 'Negative for Strep A'),

        (4, 'CRP (C-Reactive Protein)', 'البروتين التفاعلي C', 90.00, '< 10 mg/L'),
        (4, 'RF (Rheumatoid Factor)', 'عامل الروماتويد', 100.00, '< 14 IU/mL'),
        (4, 'ASO Titre', 'فحص أجسام مضادة للستربتوليسين', 110.00, '< 200 IU/mL'),
        (4, 'HBsAg', 'التهاب الكبد ب', 120.00, 'Non-reactive'),
        (4, 'HIV I & II', 'فيروس نقص المناعة البشرية', 180.00, 'Non-reactive'),
        (4, 'HCV Antibodies', 'فيروس التهاب الكبد ج', 150.00, 'Non-reactive'),

        (5, 'ANA', 'الأجسام المضادة للنواة', 220.00, 'Negative'),
        (5, 'Anti-dsDNA', 'الأجسام المضادة للحمض النووي', 280.00, '< 30 IU/mL'),
        (5, 'Total IgE', 'الغلوبولين المناعي الكلي E', 190.00, '< 100 kU/L'),

        (6, 'TSH', 'الهرمون المنبه للدرقية', 130.00, '0.4 - 4.0 mIU/L'),
        (6, 'Free T3', 'T3 الحر', 130.00, '2.3 - 4.2 pg/mL'),
        (6, 'Free T4', 'T4 الحر', 130.00, '0.8 - 1.8 ng/dL'),
        (6, 'Prolactin', 'هرمون الحليب', 150.00, 'Men: 2-18, Women: 2-29 ng/mL'),
        (6, 'Testosterone', 'هرمون التستوستيرون', 180.00, 'Men: 300-1000, Women: 15-70 ng/dL'),
        (6, 'Vitamin D', 'فيتامين د', 350.00, '30 - 100 ng/mL'),

        (7, 'PT (Prothrombin Time)', 'وقت البروثرومبين', 100.00, '11 - 13.5 seconds'),
        (7, 'PTT (Partial Thromboplastin Time)', 'وقت الثرومبوبلاستين الجزئي', 120.00, '25 - 35 seconds'),
        (7, 'INR', 'النسبة المعيارية الدولية', 100.00, '0.8 - 1.1'),
        (7, 'D-Dimer', 'دي دايمر', 300.00, '< 500 ng/mL'),

        (8, 'Sodium (Na)', 'الصوديوم', 70.00, '135 - 145 mEq/L'),
        (8, 'Potassium (K)', 'البوتاسيوم', 70.00, '3.6 - 5.2 mEq/L'),
        (8, 'Chloride (Cl)', 'الكلوريد', 70.00, '96 - 106 mEq/L'),
        (8, 'Calcium (Ca)', 'الكالسيوم', 80.00, '8.5 - 10.2 mg/dL'),
        (8, 'Magnesium (Mg)', 'المغنيسيوم', 90.00, '1.7 - 2.2 mg/dL'),

        (9, 'Urine Analysis', 'تحليل البول', 50.00, 'Normal'),
        (9, 'Stool Analysis', 'تحليل البراز', 60.00, 'Normal'),
        (9, 'Occult Blood in Stool', 'الدم الخفي في البراز', 80.00, 'Negative'),

        (10, 'Troponin I', 'تروبونين I', 250.00, '< 0.04 ng/mL'),
        (10, 'CK-MB', 'انزيم القلب CK-MB', 180.00, '< 5.0 ng/mL')");
    }
    
    echo "Database setup completed successfully.";
} catch (PDOException $e) {
    die("Database setup failed: " . $e->getMessage());
}