Jake Vanderwerf
2025-11-04 42fa8304ddb811b0f725f245130f70c0f5e86a6c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<?php
namespace JVBase\importers;
 
use WP_Error;
 
if (!defined('ABSPATH')) {
    exit;
}
 
/**
 * JaneApp Client List Importer
 *
 * Imports client data from JaneApp CSV exports and maps to WordPress users
 */
class JaneAppClientImporter
{
    protected $wpdb;
    protected string $jane_clients_table;
    protected array $import_stats = [];
 
    // CSV column mapping
    protected array $column_map = [
        'patient_guid' => 'patient_guid',
        'first_name' => 'First Name',
        'last_name' => 'Last Name',
        'email' => 'Email',
    ];
 
    public function __construct()
    {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->jane_clients_table = $wpdb->prefix . BASE . 'jane_clients';
    }
 
    /**
     * Import client list from CSV file
     *
     * @param string $file_path Path to the CSV file
     * @param array $options Import options (e.g., update_existing, send_welcome_email)
     * @return array Import results with stats and errors
     */
    public function importFromCSV(string $file_path, array $options = []): array
    {
        // Initialize stats
        $this->import_stats = [
            'total_rows' => 0,
            'processed' => 0,
            'created' => 0,
            'updated' => 0,
            'skipped' => 0,
            'errors' => [],
            'unmatched_emails' => []
        ];
 
        // Validate file exists
        if (!file_exists($file_path)) {
            return new WP_Error('file_not_found', 'CSV file not found');
        }
 
        // Parse options
        $update_existing = $options['update_existing'] ?? true;
        $send_welcome_email = $options['send_welcome_email'] ?? false;
        $create_users = $options['create_users'] ?? true;
 
        // Open and parse CSV
        $handle = fopen($file_path, 'r');
        if (!$handle) {
            return new WP_Error('file_open_error', 'Could not open CSV file');
        }
 
        // Get header row
        $headers = fgetcsv($handle);
        if (!$headers) {
            fclose($handle);
            return new WP_Error('invalid_csv', 'CSV file is empty or invalid');
        }
 
        // Map column indices
        $column_indices = $this->mapColumnIndices($headers);
        if (is_wp_error($column_indices)) {
            fclose($handle);
            return $column_indices;
        }
 
        // Start transaction for data integrity
        $this->wpdb->query('START TRANSACTION');
 
        try {
            // Process each row
            while (($row = fgetcsv($handle)) !== false) {
                $this->import_stats['total_rows']++;
 
                $result = $this->processClientRow($row, $column_indices, [
                    'update_existing' => $update_existing,
                    'send_welcome_email' => $send_welcome_email,
                    'create_users' => $create_users
                ]);
 
                if (is_wp_error($result)) {
                    $this->import_stats['errors'][] = [
                        'row' => $this->import_stats['total_rows'],
                        'error' => $result->get_error_message()
                    ];
                    $this->import_stats['skipped']++;
                } else {
                    $this->import_stats['processed']++;
                    if ($result['action'] === 'created') {
                        $this->import_stats['created']++;
                    } elseif ($result['action'] === 'updated') {
                        $this->import_stats['updated']++;
                    }
                }
            }
 
            // Commit transaction
            $this->wpdb->query('COMMIT');
 
        } catch (\Exception $e) {
            // Rollback on error
            $this->wpdb->query('ROLLBACK');
            fclose($handle);
            return new WP_Error('import_error', 'Import failed: ' . $e->getMessage());
        }
 
        fclose($handle);
 
        return $this->import_stats;
    }
 
    /**
     * Map CSV column headers to internal field names
     *
     * @param array $headers CSV header row
     * @return array|WP_Error Column index mapping or error
     */
    protected function mapColumnIndices(array $headers): array|WP_Error
    {
        $indices = [];
 
        foreach ($this->column_map as $field => $csv_column) {
            $index = array_search($csv_column, $headers);
            if ($index === false) {
                return new WP_Error(
                    'missing_column',
                    sprintf('Required column "%s" not found in CSV', $csv_column)
                );
            }
            $indices[$field] = $index;
        }
 
        return $indices;
    }
 
    /**
     * Process a single client row from CSV
     *
     * @param array $row CSV row data
     * @param array $column_indices Column mapping
     * @param array $options Processing options
     * @return array|WP_Error Result of processing
     */
    protected function processClientRow(array $row, array $column_indices, array $options): array|WP_Error
    {
        // Extract data from row
        $patient_guid = trim($row[$column_indices['patient_guid']] ?? '');
        $first_name = trim($row[$column_indices['first_name']] ?? '');
        $last_name = trim($row[$column_indices['last_name']] ?? '');
        $email = trim($row[$column_indices['email']] ?? '');
 
        // Validate required fields
        if (empty($patient_guid) || empty($email)) {
            return new WP_Error('invalid_data', 'Missing patient_guid or email');
        }
 
        // Sanitize email
        $email = sanitize_email($email);
        if (!is_email($email)) {
            return new WP_Error('invalid_email', 'Invalid email address: ' . $email);
        }
 
        // Check if client already exists in mapping table
        $existing_mapping = $this->getClientByGuid($patient_guid);
 
        // Find or create WordPress user
        $user = get_user_by('email', $email);
 
        if (!$user && $options['create_users']) {
            // Create new user
            $user_id = $this->createWordPressUser($email, $first_name, $last_name, $options['send_welcome_email']);
 
            if (is_wp_error($user_id)) {
                return $user_id;
            }
 
            $user = get_user_by('ID', $user_id);
            $action = 'created';
 
        } elseif (!$user) {
            // User doesn't exist and we're not creating users
            $this->import_stats['unmatched_emails'][] = $email;
            return new WP_Error('user_not_found', 'User not found and create_users is false');
 
        } else {
            $action = 'existing';
        }
 
        // Update or insert client mapping
        if ($existing_mapping) {
            if ($options['update_existing']) {
                $this->updateClientMapping($existing_mapping->id, [
                    'user_id' => $user->ID,
                    'first_name' => $first_name,
                    'last_name' => $last_name,
                    'email' => $email
                ]);
                $action = 'updated';
            }
        } else {
            $this->insertClientMapping([
                'patient_guid' => $patient_guid,
                'user_id' => $user->ID,
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email
            ]);
            if ($action !== 'created') {
                $action = 'mapped';
            }
        }
 
        return [
            'action' => $action,
            'user_id' => $user->ID,
            'patient_guid' => $patient_guid
        ];
    }
 
    /**
     * Create a new WordPress user
     *
     * @param string $email User email
     * @param string $first_name First name
     * @param string $last_name Last name
     * @param bool $send_welcome_email Whether to send welcome email
     * @return int|WP_Error User ID or error
     */
    protected function createWordPressUser(string $email, string $first_name, string $last_name, bool $send_welcome_email = false): int|WP_Error
    {
        // Generate username from email
        $username = $this->generateUsername($email);
 
        // Generate random password
        $password = wp_generate_password(12, true, true);
 
        $userdata = [
            'user_login' => $username,
            'user_email' => $email,
            'user_pass' => $password,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'display_name' => trim($first_name . ' ' . $last_name),
            'role' => apply_filters(BASE . 'jane_import_default_role', 'customer')
        ];
 
        $user_id = wp_insert_user($userdata);
 
        if (is_wp_error($user_id)) {
            return $user_id;
        }
 
        // Send welcome email if requested
        if ($send_welcome_email) {
            wp_send_new_user_notifications($user_id, 'both');
        }
 
        do_action(BASE . 'jane_client_created', $user_id, $userdata);
 
        return $user_id;
    }
 
    /**
     * Generate unique username from email
     *
     * @param string $email Email address
     * @return string Unique username
     */
    protected function generateUsername(string $email): string
    {
        $base_username = sanitize_user(substr($email, 0, strpos($email, '@')));
        $username = $base_username;
        $counter = 1;
 
        while (username_exists($username)) {
            $username = $base_username . $counter;
            $counter++;
        }
 
        return $username;
    }
 
    /**
     * Get client by patient GUID
     *
     * @param string $patient_guid Patient GUID
     * @return object|null Client data or null
     */
    protected function getClientByGuid(string $patient_guid): ?object
    {
        return $this->wpdb->get_row($this->wpdb->prepare(
            "SELECT * FROM {$this->jane_clients_table} WHERE patient_guid = %s",
            $patient_guid
        ));
    }
 
    /**
     * Get client by user ID
     *
     * @param int $user_id WordPress user ID
     * @return object|null Client data or null
     */
    public function getClientByUserId(int $user_id): ?object
    {
        return $this->wpdb->get_row($this->wpdb->prepare(
            "SELECT * FROM {$this->jane_clients_table} WHERE user_id = %d",
            $user_id
        ));
    }
 
    /**
     * Insert new client mapping
     *
     * @param array $data Client data
     * @return int|false Insert ID or false on failure
     */
    protected function insertClientMapping(array $data): int|false
    {
        $result = $this->wpdb->insert(
            $this->jane_clients_table,
            $data,
            ['%s', '%d', '%s', '%s', '%s']
        );
 
        return $result ? $this->wpdb->insert_id : false;
    }
 
    /**
     * Update existing client mapping
     *
     * @param int $id Mapping ID
     * @param array $data Updated data
     * @return bool Success
     */
    protected function updateClientMapping(int $id, array $data): bool
    {
        return (bool) $this->wpdb->update(
            $this->jane_clients_table,
            $data,
            ['id' => $id],
            ['%d', '%s', '%s', '%s'],
            ['%d']
        );
    }
 
    /**
     * Get user ID by patient GUID
     *
     * @param string $patient_guid Patient GUID
     * @return int|null User ID or null if not found
     */
    public function getUserIdByGuid(string $patient_guid): ?int
    {
        $client = $this->getClientByGuid($patient_guid);
        return $client ? (int) $client->user_id : null;
    }
 
    /**
     * Get import statistics
     *
     * @return array Import statistics
     */
    public function getImportStats(): array
    {
        return $this->import_stats;
    }
}