<?php
/**
 * KiviCare seed data for CVE-2026-2991 PoC environment.
 * Run via: wp eval-file /seed.php --path=/var/www/html --allow-root
 *
 * Creates:
 *  - 1 clinic
 *  - 3 doctors linked to the clinic
 *  - 5 patients linked to the clinic
 */

global $wpdb;

// ── helpers ──────────────────────────────────────────────────────────────────

function seed_log( string $msg ): void {
    echo $msg . PHP_EOL;
}

function create_wp_user( string $username, string $email, string $password,
                          string $first, string $last, string $role ): int {
    $existing = get_user_by( 'email', $email );
    if ( $existing ) {
        seed_log( "    [~] User already exists: {$email} (ID {$existing->ID})" );
        return $existing->ID;
    }

    $id = wp_insert_user( [
        'user_login'   => $username,
        'user_email'   => $email,
        'user_pass'    => $password,
        'first_name'   => $first,
        'last_name'    => $last,
        'display_name' => "{$first} {$last}",
        'role'         => $role,
    ] );

    if ( is_wp_error( $id ) ) {
        seed_log( "    [-] Failed to create {$email}: " . $id->get_error_message() );
        return 0;
    }

    return $id;
}

function set_basic_data( int $user_id, array $data ): void {
    update_user_meta( $user_id, 'basic_data', $data );
}

function map_to_clinic( string $table, string $id_col, int $user_id, int $clinic_id ): void {
    global $wpdb;
    $t = $wpdb->prefix . $table;
    $exists = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM `{$t}` WHERE `{$id_col}` = %d AND clinic_id = %d",
        $user_id, $clinic_id
    ) );
    if ( ! $exists ) {
        $wpdb->insert( $t, [
            $id_col    => $user_id,
            'clinic_id' => $clinic_id,
            'created_at' => current_time( 'mysql' ),
        ] );
    }
}


// ── 1. clinic ─────────────────────────────────────────────────────────────────

seed_log( '[*] Seeding clinic...' );

$clinic_table = $wpdb->prefix . 'kc_clinics';
$clinic_id    = (int) $wpdb->get_var( "SELECT id FROM `{$clinic_table}` LIMIT 1" );

if ( ! $clinic_id ) {
    $wpdb->insert( $clinic_table, [
        'name'          => 'Greenfield Medical Centre',
        'email'         => 'clinic@greenfield.test',
        'telephone_no'  => '+1-555-010-0100',
        'specialties'   => json_encode( [ 'General Practice', 'Cardiology', 'Neurology' ] ),
        'address'       => '42 Elm Street',
        'city'          => 'Springfield',
        'state'         => 'IL',
        'country'       => 'US',
        'postal_code'   => '62701',
        'status'        => 1,
        'clinic_admin_id' => 1,
        'created_at'    => current_time( 'mysql' ),
    ] );
    $clinic_id = (int) $wpdb->insert_id;
    seed_log( "    [+] Clinic created (ID {$clinic_id})" );
} else {
    seed_log( "    [~] Clinic already exists (ID {$clinic_id})" );
}


// ── 2. doctors ────────────────────────────────────────────────────────────────

seed_log( '[*] Seeding doctors...' );

$doctors = [
    [
        'username' => 'dr.harris',
        'email'    => 'dr.harris@greenfield.test',
        'password' => 'Doctor@123',
        'first'    => 'Marcus',
        'last'     => 'Harris',
        'meta'     => [
            'mobile_number'    => '+1-555-201-0001',
            'gender'           => 'Male',
            'dob'              => '1978-04-12',
            'address'          => '10 Oak Avenue',
            'city'             => 'Springfield',
            'country'          => 'US',
            'postal_code'      => '62702',
            'qualifications'   => [ 'MBBS', 'MD (Cardiology)' ],
            'no_of_experience' => 18,
            'specialties'      => [ 'Cardiology' ],
        ],
    ],
    [
        'username' => 'dr.chen',
        'email'    => 'dr.chen@greenfield.test',
        'password' => 'Doctor@123',
        'first'    => 'Ling',
        'last'     => 'Chen',
        'meta'     => [
            'mobile_number'    => '+1-555-201-0002',
            'gender'           => 'Female',
            'dob'              => '1985-09-23',
            'address'          => '8 Maple Drive',
            'city'             => 'Springfield',
            'country'          => 'US',
            'postal_code'      => '62703',
            'qualifications'   => [ 'MBBS', 'MD (Neurology)', 'PhD' ],
            'no_of_experience' => 11,
            'specialties'      => [ 'Neurology' ],
        ],
    ],
    [
        'username' => 'dr.okonkwo',
        'email'    => 'dr.okonkwo@greenfield.test',
        'password' => 'Doctor@123',
        'first'    => 'Emeka',
        'last'     => 'Okonkwo',
        'meta'     => [
            'mobile_number'    => '+1-555-201-0003',
            'gender'           => 'Male',
            'dob'              => '1982-01-07',
            'address'          => '3 Pine Road',
            'city'             => 'Springfield',
            'country'          => 'US',
            'postal_code'      => '62704',
            'qualifications'   => [ 'MBBS', 'MRCGP' ],
            'no_of_experience' => 14,
            'specialties'      => [ 'General Practice' ],
        ],
    ],
];

$doctor_mapping_table = 'kc_doctor_clinic_mappings';

foreach ( $doctors as $d ) {
    $uid = create_wp_user( $d['username'], $d['email'], $d['password'],
                           $d['first'], $d['last'], 'kiviCare_doctor' );
    if ( ! $uid ) continue;

    set_basic_data( $uid, $d['meta'] );
    map_to_clinic( $doctor_mapping_table, 'doctor_id', $uid, $clinic_id );
    seed_log( "    [+] Doctor: {$d['first']} {$d['last']} <{$d['email']}> (ID {$uid})" );
}


// ── 3. patients ───────────────────────────────────────────────────────────────

seed_log( '[*] Seeding patients...' );

$patients = [
    [
        'username' => 'james.ford',
        'email'    => 'james.ford@patients.test',
        'password' => 'Patient@123',
        'first'    => 'James',
        'last'     => 'Ford',
        'meta'     => [
            'mobile_number' => '+1-555-300-0001',
            'gender'        => 'Male',
            'dob'           => '1990-06-15',
            'address'       => '55 Birch Lane',
            'city'          => 'Springfield',
            'country'       => 'US',
            'postal_code'   => '62701',
            'blood_group'   => 'O+',
        ],
    ],
    [
        'username' => 'sofia.reyes',
        'email'    => 'sofia.reyes@patients.test',
        'password' => 'Patient@123',
        'first'    => 'Sofia',
        'last'     => 'Reyes',
        'meta'     => [
            'mobile_number' => '+1-555-300-0002',
            'gender'        => 'Female',
            'dob'           => '1995-11-30',
            'address'       => '12 Cedar Court',
            'city'          => 'Springfield',
            'country'       => 'US',
            'postal_code'   => '62702',
            'blood_group'   => 'A-',
        ],
    ],
    [
        'username' => 'oliver.knight',
        'email'    => 'oliver.knight@patients.test',
        'password' => 'Patient@123',
        'first'    => 'Oliver',
        'last'     => 'Knight',
        'meta'     => [
            'mobile_number' => '+1-555-300-0003',
            'gender'        => 'Male',
            'dob'           => '1973-03-08',
            'address'       => '7 Willow Way',
            'city'          => 'Springfield',
            'country'       => 'US',
            'postal_code'   => '62703',
            'blood_group'   => 'B+',
        ],
    ],
    [
        'username' => 'amara.diallo',
        'email'    => 'amara.diallo@patients.test',
        'password' => 'Patient@123',
        'first'    => 'Amara',
        'last'     => 'Diallo',
        'meta'     => [
            'mobile_number' => '+1-555-300-0004',
            'gender'        => 'Female',
            'dob'           => '1988-07-19',
            'address'       => '29 Aspen Close',
            'city'          => 'Springfield',
            'country'       => 'US',
            'postal_code'   => '62704',
            'blood_group'   => 'AB+',
        ],
    ],
    [
        'username' => 'dan.walsh',
        'email'    => 'dan.walsh@patients.test',
        'password' => 'Patient@123',
        'first'    => 'Daniel',
        'last'     => 'Walsh',
        'meta'     => [
            'mobile_number' => '+1-555-300-0005',
            'gender'        => 'Male',
            'dob'           => '2001-12-04',
            'address'       => '61 Hawthorn Street',
            'city'          => 'Springfield',
            'country'       => 'US',
            'postal_code'   => '62705',
            'blood_group'   => 'O-',
        ],
    ],
];

$patient_mapping_table = 'kc_patient_clinic_mappings';

foreach ( $patients as $p ) {
    $uid = create_wp_user( $p['username'], $p['email'], $p['password'],
                           $p['first'], $p['last'], 'kiviCare_patient' );
    if ( ! $uid ) continue;

    set_basic_data( $uid, $p['meta'] );
    update_user_meta( $uid, 'patient_added_by', 1 );
    map_to_clinic( $patient_mapping_table, 'patient_id', $uid, $clinic_id );
    seed_log( "    [+] Patient: {$p['first']} {$p['last']} <{$p['email']}> (ID {$uid})" );
}


// ── done ──────────────────────────────────────────────────────────────────────

seed_log( '' );
seed_log( '[+] Seed complete.' );
seed_log( '' );
seed_log( '    Clinic  : Greenfield Medical Centre' );
seed_log( '    Doctors : dr.harris, dr.chen, dr.okonkwo  (password: Doctor@123)' );
seed_log( '    Patients: james.ford, sofia.reyes, oliver.knight, amara.diallo, dan.walsh' );
seed_log( '              (password: Patient@123)' );
