-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_stats.php
More file actions
1445 lines (1251 loc) · 59 KB
/
import_stats.php
File metadata and controls
1445 lines (1251 loc) · 59 KB
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// import_stats.php - Import Statistics from SQLite Scoring App
session_start();
$is_admin = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'];
// Redirect non-admins
if (!$is_admin) {
header('Location: index.php');
exit;
}
$players_file = 'tables/players.csv';
$matchdays_file = 'tables/matchdays.csv';
$matches_file = 'tables/matches.csv';
$sets_file = 'tables/sets.csv';
// Initialize session variables for import process
if (!isset($_SESSION['import_step'])) {
$_SESSION['import_step'] = 'upload';
}
// If coming back after completion (e.g., navigating away and returning), reset to upload step
if ($_SESSION['import_step'] == 'complete' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
// Clear all import-related session data
unset($_SESSION['import_step']);
unset($_SESSION['sqlite_data']);
unset($_SESSION['player_mapping']);
unset($_SESSION['selected_matchday']);
unset($_SESSION['selected_sets']);
unset($_SESSION['match_selections']);
$_SESSION['import_step'] = 'upload';
}
// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['upload_file'])) {
handleFileUpload();
} elseif (isset($_POST['confirm_players'])) {
handlePlayerMapping();
} elseif (isset($_POST['select_matchday'])) {
handleMatchdaySelection();
} elseif (isset($_POST['confirm_matches'])) {
handleConfirmMatches();
} elseif (isset($_POST['import_stats'])) {
handleStatsImport();
} elseif (isset($_POST['reset_import'])) {
resetImport();
}
}
// Load CSV data
$csv_players = loadPlayers();
$matchdays = loadMatchdays();
$all_matches = loadMatches();
// Functions
function loadPlayers() {
global $players_file;
$players = [];
if (file_exists($players_file) && ($fp = fopen($players_file, 'r')) !== false) {
$header = fgetcsv($fp);
while (($row = fgetcsv($fp)) !== false) {
$players[$row[0]] = ['id' => $row[0], 'name' => $row[1], 'nickname' => $row[2]];
}
fclose($fp);
}
return $players;
}
function loadMatchdays() {
global $matchdays_file;
$matchdays = [];
if (file_exists($matchdays_file) && ($fp = fopen($matchdays_file, 'r')) !== false) {
$header = fgetcsv($fp);
while (($row = fgetcsv($fp)) !== false) {
$matchdays[] = ['id' => $row[0], 'date' => $row[1], 'location' => $row[2]];
}
fclose($fp);
}
return $matchdays;
}
function loadMatches() {
global $matches_file;
$matches = [];
if (file_exists($matches_file) && ($fp = fopen($matches_file, 'r')) !== false) {
$header = fgetcsv($fp);
while (($row = fgetcsv($fp)) !== false) {
$matches[] = [
'id' => $row[0],
'matchday_id' => $row[1],
'phase' => $row[2],
'firsttosets' => $row[3],
'firsttolegs' => $row[4],
'player1_id' => $row[5],
'player2_id' => $row[6],
'sets1' => $row[7],
'sets2' => $row[8]
];
}
fclose($fp);
}
return $matches;
}
function loadSets() {
global $sets_file;
$sets = [];
if (file_exists($sets_file) && ($fp = fopen($sets_file, 'r')) !== false) {
$header = fgetcsv($fp);
while (($row = fgetcsv($fp)) !== false) {
// Skip empty rows - now expecting 24 columns
if (empty($row) || count($row) < 24) {
continue;
}
$sets[] = [
'id' => $row[0],
'matchid' => $row[1],
'player1id' => $row[2],
'player2id' => $row[3],
'legs1' => $row[4],
'legs2' => $row[5],
'darts1' => isset($row[6]) ? $row[6] : '',
'darts2' => isset($row[7]) ? $row[7] : '',
'3da1' => isset($row[8]) ? $row[8] : '',
'3da2' => isset($row[9]) ? $row[9] : '',
'dblattempts1' => isset($row[10]) ? $row[10] : '',
'dblattempts2' => isset($row[11]) ? $row[11] : '',
'highscore1' => isset($row[12]) ? $row[12] : '',
'highscore2' => isset($row[13]) ? $row[13] : '',
'highco1' => isset($row[14]) ? $row[14] : '',
'highco2' => isset($row[15]) ? $row[15] : '',
// NEW FIELDS ADDED:
'bestleg1' => isset($row[16]) ? $row[16] : '',
'bestleg2' => isset($row[17]) ? $row[17] : '',
'180s1' => isset($row[18]) ? $row[18] : '',
'180s2' => isset($row[19]) ? $row[19] : '',
'140s1' => isset($row[20]) ? $row[20] : '',
'140s2' => isset($row[21]) ? $row[21] : '',
'100s1' => isset($row[22]) ? $row[22] : '',
'100s2' => isset($row[23]) ? $row[23] : ''
];
}
fclose($fp);
}
return $sets;
}
function handleFileUpload() {
if (isset($_FILES['sqlite_file']) && $_FILES['sqlite_file']['error'] === UPLOAD_ERR_OK) {
$tmp_file = $_FILES['sqlite_file']['tmp_name'];
// Read the entire file into memory
$file_content = file_get_contents($tmp_file);
if ($file_content === false) {
$_SESSION['error'] = 'Failed to read uploaded file.';
return;
}
// Store in session as base64
$_SESSION['sqlite_data'] = base64_encode($file_content);
$_SESSION['import_step'] = 'map_players';
header('Location: import_stats.php');
exit;
} else {
$_SESSION['error'] = 'Please select a file to upload.';
}
}
function handlePlayerMapping() {
if (!isset($_POST['player_mapping']) || empty($_POST['player_mapping'])) {
$_SESSION['error'] = 'Please map all players before continuing.';
return;
}
// Check for duplicate mappings
$mapped_sqlite_ids = array_values($_POST['player_mapping']);
if (count($mapped_sqlite_ids) !== count(array_unique($mapped_sqlite_ids))) {
$_SESSION['error'] = 'Each SQLite player can only be mapped once. Please check your selections.';
return;
}
$_SESSION['player_mapping'] = $_POST['player_mapping'];
$_SESSION['import_step'] = 'select_matchday';
header('Location: import_stats.php');
exit;
}
function handleMatchdaySelection() {
$_SESSION['selected_matchday'] = intval($_POST['matchday_id']);
$_SESSION['import_step'] = 'match_sets';
header('Location: import_stats.php');
exit;
}
function handleConfirmMatches() {
if (!isset($_POST['selected_sets']) || empty($_POST['selected_sets'])) {
$_SESSION['error'] = 'Please select at least one set to import.';
$_SESSION['import_step'] = 'match_sets';
header('Location: import_stats.php');
exit;
}
$_SESSION['selected_sets'] = $_POST['selected_sets'];
// Store match selections (which SQLite set to use for each CSV set)
if (isset($_POST['match_selection'])) {
$_SESSION['match_selections'] = $_POST['match_selection'];
} else {
$_SESSION['match_selections'] = [];
}
$_SESSION['import_step'] = 'confirm_import';
header('Location: import_stats.php');
exit;
}
function handleStatsImport() {
if (!isset($_SESSION['selected_sets']) || empty($_SESSION['selected_sets'])) {
$_SESSION['error'] = 'No sets selected for import.';
return;
}
if (!isset($_SESSION['sqlite_data'])) {
$_SESSION['error'] = 'SQLite data not found. Please start over.';
return;
}
$player_mapping = $_SESSION['player_mapping'];
$selected_sets = $_SESSION['selected_sets'];
$match_selections = isset($_SESSION['match_selections']) ? $_SESSION['match_selections'] : [];
try {
// Create temporary file for PDO
$tmp_file = tempnam(sys_get_temp_dir(), 'sqlite_import_');
file_put_contents($tmp_file, base64_decode($_SESSION['sqlite_data']));
$db = new PDO('sqlite:' . $tmp_file);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Load current sets
$csv_sets = loadSets();
$imported_count = 0;
foreach ($selected_sets as $set_id) {
// Find the set in CSV
$csv_set = null;
foreach ($csv_sets as &$s) {
if ($s['id'] == $set_id) {
$csv_set = &$s;
break;
}
}
unset($s); // Important: unset reference after foreach loop
if (!$csv_set) {
continue;
}
// Get match details
$match_id = $csv_set['matchid'];
$player1_csv_id = $csv_set['player1id'];
$player2_csv_id = $csv_set['player2id'];
// Get SQLite player IDs from mapping
$player1_sqlite_id = isset($player_mapping[$player1_csv_id]) ? $player_mapping[$player1_csv_id] : null;
$player2_sqlite_id = isset($player_mapping[$player2_csv_id]) ? $player_mapping[$player2_csv_id] : null;
if ($player1_sqlite_id === null || $player2_sqlite_id === null) {
continue;
}
// Get matchday date for filtering
$matchday_date = null;
foreach ($GLOBALS['matchdays'] as $md) {
if ($md['id'] == $_SESSION['selected_matchday']) {
$matchday_date = $md['date'];
break;
}
}
// Find matching set(s) in SQLite
$result = findSetStatsWithInfo($db, $player1_sqlite_id, $player2_sqlite_id, $csv_set['legs1'], $csv_set['legs2'], $matchday_date);
if ($result && isset($result['matches']) && !empty($result['matches'])) {
// Get the user's selected match index (default to 0)
$selected_index = isset($match_selections[$set_id]) ? intval($match_selections[$set_id]) : 0;
// Make sure the index is valid
if ($selected_index >= 0 && $selected_index < count($result['matches'])) {
$stats = $result['matches'][$selected_index]['stats'];
// Update the CSV set with the stats
$csv_set['darts1'] = $stats['darts1'];
$csv_set['darts2'] = $stats['darts2'];
$csv_set['3da1'] = $stats['3da1'];
$csv_set['3da2'] = $stats['3da2'];
$csv_set['dblattempts1'] = $stats['dblattempts1'];
$csv_set['dblattempts2'] = $stats['dblattempts2'];
$csv_set['highscore1'] = $stats['highscore1'];
$csv_set['highscore2'] = $stats['highscore2'];
$csv_set['highco1'] = $stats['highco1'];
$csv_set['highco2'] = $stats['highco2'];
// NEW ASSIGNMENTS:
$csv_set['bestleg1'] = $stats['bestleg1'];
$csv_set['bestleg2'] = $stats['bestleg2'];
$csv_set['180s1'] = $stats['180s1'];
$csv_set['180s2'] = $stats['180s2'];
$csv_set['140s1'] = $stats['140s1'];
$csv_set['140s2'] = $stats['140s2'];
$csv_set['100s1'] = $stats['100s1'];
$csv_set['100s2'] = $stats['100s2'];
$imported_count++;
}
}
unset($csv_set);
}
// Write back to CSV
saveSets($csv_sets);
// Clean up temporary file
unlink($tmp_file);
$_SESSION['success'] = "Successfully imported statistics for {$imported_count} set(s).";
$_SESSION['import_step'] = 'complete';
} catch (Exception $e) {
// Clean up temporary file on error
if (isset($tmp_file) && file_exists($tmp_file)) {
unlink($tmp_file);
}
$_SESSION['error'] = 'Import failed: ' . $e->getMessage();
}
header('Location: import_stats.php');
exit;
}
function findSetStats($db, $player1_id, $player2_id, $expected_legs1, $expected_legs2, $matchday_date = null) {
// Build query to find all sets where these two players played
// If we have a matchday date, filter by date proximity (within 7 days)
$date_filter = '';
$params = [$player1_id, $player2_id];
if ($matchday_date && !empty($matchday_date)) {
$date_filter = " AND s.created_at >= date(?, '-2 days') AND s.created_at <= date(?, '+2 days')";
$params[] = $matchday_date;
$params[] = $matchday_date;
}
$stmt = $db->prepare("
SELECT DISTINCT s.id as set_id, s.setNummer, s.created_at
FROM xGameMpSet s
JOIN xGameMpLeg l ON l.setId = s.id
JOIN xGameSpieler gs ON gs.legId = l.id
WHERE gs.spielerId IN (?, ?)
$date_filter
GROUP BY s.id
HAVING COUNT(DISTINCT gs.spielerId) = 2
ORDER BY s.created_at DESC
");
$stmt->execute($params);
$potential_sets = $stmt->fetchAll(PDO::FETCH_ASSOC);
// For each potential set, check if the leg counts match
foreach ($potential_sets as $set_info) {
$set_id = $set_info['set_id'];
// Count legs won by each player
$stmt = $db->prepare("
SELECT l.siegerId, COUNT(*) as legs_won
FROM xGameMpLeg l
WHERE l.setId = ?
GROUP BY l.siegerId
");
$stmt->execute([$set_id]);
$leg_counts = $stmt->fetchAll(PDO::FETCH_ASSOC);
$legs1 = 0;
$legs2 = 0;
foreach ($leg_counts as $lc) {
if ($lc['siegerId'] == $player1_id) {
$legs1 = $lc['legs_won'];
} elseif ($lc['siegerId'] == $player2_id) {
$legs2 = $lc['legs_won'];
}
}
// Check if this matches our expected leg counts (in either order)
$match_forward = ($legs1 == $expected_legs1 && $legs2 == $expected_legs2);
$match_reverse = ($legs1 == $expected_legs2 && $legs2 == $expected_legs1);
if ($match_forward || $match_reverse) {
// This is our set! Extract stats
// If reversed, swap the player IDs when extracting stats
if ($match_reverse) {
return extractSetStats($db, $set_id, $player2_id, $player1_id);
} else {
return extractSetStats($db, $set_id, $player1_id, $player2_id);
}
}
}
return null;
}
function extractSetStats($db, $set_id, $player1_id, $player2_id) {
$stats = [
'darts1' => 0,
'darts2' => 0,
'3da1' => 0,
'3da2' => 0,
'dblattempts1' => 0,
'dblattempts2' => 0,
'highscore1' => 0,
'highscore2' => 0,
'highco1' => 0,
'highco2' => 0,
'bestleg1' => 0,
'bestleg2' => 0,
'180s1' => 0,
'180s2' => 0,
'140s1' => 0,
'140s2' => 0,
'100s1' => 0,
'100s2' => 0
];
$total_score1 = 0;
$total_score2 = 0;
// Get all legs in this set
$stmt = $db->prepare("
SELECT id FROM xGameMpLeg WHERE setId = ? ORDER BY legNummer
");
$stmt->execute([$set_id]);
$legs = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($legs as $leg_id) {
// Get player stats for this leg
$stmt = $db->prepare("
SELECT spielerId, gesamtScore, gesamtDarts
FROM xGameSpieler
WHERE legId = ? AND spielerId IN (?, ?)
");
$stmt->execute([$leg_id, $player1_id, $player2_id]);
$player_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Get the winner of this leg
$stmt = $db->prepare("SELECT siegerId FROM xGameMpLeg WHERE id = ?");
$stmt->execute([$leg_id]);
$leg_winner = $stmt->fetchColumn();
foreach ($player_stats as $ps) {
$is_player1 = ($ps['spielerId'] == $player1_id);
if ($is_player1) {
$stats['darts1'] += $ps['gesamtDarts'];
$total_score1 += $ps['gesamtScore'];
// Track best leg (fewest darts to checkout) - only for winning legs
if ($leg_winner == $player1_id) {
if ($stats['bestleg1'] == 0 || $ps['gesamtDarts'] < $stats['bestleg1']) {
$stats['bestleg1'] = $ps['gesamtDarts'];
}
}
} else {
$stats['darts2'] += $ps['gesamtDarts'];
$total_score2 += $ps['gesamtScore'];
// Track best leg (fewest darts to checkout) - only for winning legs
if ($leg_winner == $player2_id) {
if ($stats['bestleg2'] == 0 || $ps['gesamtDarts'] < $stats['bestleg2']) {
$stats['bestleg2'] = $ps['gesamtDarts'];
}
}
}
}
// Get throw statistics for each player in this leg
// For each player in this leg, get their xGameSpieler ID to query throws
$stmt = $db->prepare("
SELECT gs.id, gs.spielerId
FROM xGameSpieler gs
WHERE gs.legId = ? AND gs.spielerId IN (?, ?)
");
$stmt->execute([$leg_id, $player1_id, $player2_id]);
$player_entities = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($player_entities as $entity) {
$entity_id = $entity['id'];
$is_player1 = ($entity['spielerId'] == $player1_id);
// Get highest score (any throw)
$stmt = $db->prepare("
SELECT MAX(score) as max_score
FROM aufnahmeMp
WHERE entityId = ? AND entityName = 'XGame'
");
$stmt->execute([$entity_id]);
$result = $stmt->fetchColumn();
if ($result !== null && $result !== false) {
if ($is_player1) {
if ($result > $stats['highscore1']) {
$stats['highscore1'] = $result;
}
} else {
if ($result > $stats['highscore2']) {
$stats['highscore2'] = $result;
}
}
}
// Get highest checkout (only throws where checkout = 1)
$stmt = $db->prepare("
SELECT MAX(beginnScore) as max_checkout
FROM aufnahmeMp
WHERE entityId = ? AND entityName = 'XGame' AND checkout = 1
");
$stmt->execute([$entity_id]);
$result = $stmt->fetchColumn();
if ($result !== null && $result !== false) {
if ($is_player1) {
if ($result > $stats['highco1']) {
$stats['highco1'] = $result;
}
} else {
if ($result > $stats['highco2']) {
$stats['highco2'] = $result;
}
}
}
// Get total double attempts (sum of dartsOnDouble from all throws)
$stmt = $db->prepare("
SELECT SUM(dartsOnDouble) as total_dbl_attempts
FROM aufnahmeMp
WHERE entityId = ? AND entityName = 'XGame'
");
$stmt->execute([$entity_id]);
$result = $stmt->fetchColumn();
if ($result !== null && $result !== false) {
if ($is_player1) {
$stats['dblattempts1'] += $result;
} else {
$stats['dblattempts2'] += $result;
}
}
// Count 180s
$stmt = $db->prepare("
SELECT COUNT(*) as count_180s
FROM aufnahmeMp
WHERE entityId = ? AND entityName = 'XGame' AND score = 180
");
$stmt->execute([$entity_id]);
$result = $stmt->fetchColumn();
if ($result !== null && $result !== false) {
if ($is_player1) {
$stats['180s1'] += $result;
} else {
$stats['180s2'] += $result;
}
}
// Count 140+ scores (140-179)
$stmt = $db->prepare("
SELECT COUNT(*) as count_140s
FROM aufnahmeMp
WHERE entityId = ? AND entityName = 'XGame' AND score >= 140 AND score <= 179
");
$stmt->execute([$entity_id]);
$result = $stmt->fetchColumn();
if ($result !== null && $result !== false) {
if ($is_player1) {
$stats['140s1'] += $result;
} else {
$stats['140s2'] += $result;
}
}
// Count 100+ scores (100-139)
$stmt = $db->prepare("
SELECT COUNT(*) as count_100s
FROM aufnahmeMp
WHERE entityId = ? AND entityName = 'XGame' AND score >= 100 AND score <= 139
");
$stmt->execute([$entity_id]);
$result = $stmt->fetchColumn();
if ($result !== null && $result !== false) {
if ($is_player1) {
$stats['100s1'] += $result;
} else {
$stats['100s2'] += $result;
}
}
}
}
// Calculate 3-dart averages
$stats['3da1'] = ($stats['darts1'] > 0) ? round(($total_score1 / $stats['darts1']) * 3, 2) : 0;
$stats['3da2'] = ($stats['darts2'] > 0) ? round(($total_score2 / $stats['darts2']) * 3, 2) : 0;
return $stats;
}
function saveSets($sets) {
global $sets_file;
$fp = fopen($sets_file, 'w');
if (!$fp) {
return;
}
// NEW HEADER with 8 additional columns:
fputcsv($fp, ['id', 'matchid', 'player1id', 'player2id', 'legs1', 'legs2', 'darts1', 'darts2', '3da1', '3da2', 'dblattempts1', 'dblattempts2', 'highscore1', 'highscore2', 'highco1', 'highco2', 'bestleg1', 'bestleg2', '180s1', '180s2', '140s1', '140s2', '100s1', '100s2']);
foreach ($sets as $set) {
fputcsv($fp, [
$set['id'],
$set['matchid'],
$set['player1id'],
$set['player2id'],
$set['legs1'],
$set['legs2'],
isset($set['darts1']) ? $set['darts1'] : '',
isset($set['darts2']) ? $set['darts2'] : '',
isset($set['3da1']) ? $set['3da1'] : '',
isset($set['3da2']) ? $set['3da2'] : '',
isset($set['dblattempts1']) ? $set['dblattempts1'] : '',
isset($set['dblattempts2']) ? $set['dblattempts2'] : '',
isset($set['highscore1']) ? $set['highscore1'] : '',
isset($set['highscore2']) ? $set['highscore2'] : '',
isset($set['highco1']) ? $set['highco1'] : '',
isset($set['highco2']) ? $set['highco2'] : '',
// NEW FIELDS ADDED:
isset($set['bestleg1']) ? $set['bestleg1'] : '',
isset($set['bestleg2']) ? $set['bestleg2'] : '',
isset($set['180s1']) ? $set['180s1'] : '',
isset($set['180s2']) ? $set['180s2'] : '',
isset($set['140s1']) ? $set['140s1'] : '',
isset($set['140s2']) ? $set['140s2'] : '',
isset($set['100s1']) ? $set['100s1'] : '',
isset($set['100s2']) ? $set['100s2'] : ''
]);
}
fclose($fp);
}
function getSQLitePlayers() {
if (!isset($_SESSION['sqlite_data'])) {
return [];
}
try {
// Create temporary file for PDO
$tmp_file = tempnam(sys_get_temp_dir(), 'sqlite_import_');
file_put_contents($tmp_file, base64_decode($_SESSION['sqlite_data']));
$db = new PDO('sqlite:' . $tmp_file);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->query("SELECT id, name FROM Spieler ORDER BY name");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Clean up temporary file
unlink($tmp_file);
return $result;
} catch (Exception $e) {
// Clean up temporary file on error
if (isset($tmp_file) && file_exists($tmp_file)) {
unlink($tmp_file);
}
$_SESSION['error'] = 'Failed to read SQLite file: ' . $e->getMessage();
return [];
}
}
function findBestMatch($csv_player, $sqlite_players) {
$best_match_id = null;
$best_score = 0;
// We'll compare using the nickname if it exists, otherwise use the name
$csv_compare = !empty($csv_player['nickname']) ? $csv_player['nickname'] : $csv_player['name'];
foreach ($sqlite_players as $sp) {
$score = similarityScore($csv_compare, $sp['name']);
if ($score > $best_score) {
$best_score = $score;
$best_match_id = $sp['id'];
}
}
return $best_match_id;
}
function similarityScore($str1, $str2) {
$str1 = strtolower(trim($str1));
$str2 = strtolower(trim($str2));
// Exact match
if ($str1 === $str2) {
return 100;
}
// Contains match (substring)
if (strpos($str2, $str1) !== false || strpos($str1, $str2) !== false) {
return 90;
}
// Check for similarity using levenshtein distance
$lev = levenshtein($str1, $str2);
$max_len = max(strlen($str1), strlen($str2));
if ($max_len == 0) {
return 0;
}
$similarity = (1 - $lev / $max_len) * 100;
// Also check similar_text for better matching
similar_text($str1, $str2, $percent);
// Return the higher of the two scores
return max($similarity, $percent);
}
function isMatchdayComplete($matchday_id) {
global $all_matches;
$matchday_matches = array_filter($all_matches, function($m) use ($matchday_id) {
return $m['matchday_id'] == $matchday_id;
});
foreach ($matchday_matches as $match) {
// Check if the match has been played (at least one set score entered)
if ($match['sets1'] == 0 && $match['sets2'] == 0) {
return false;
}
}
return count($matchday_matches) > 0;
}
function getMatchdaySets($matchday_id) {
global $all_matches;
$matchday_matches = array_filter($all_matches, function($m) use ($matchday_id) {
return $m['matchday_id'] == $matchday_id;
});
$csv_sets = loadSets();
$result = [];
foreach ($matchday_matches as $match) {
$match_sets = array_filter($csv_sets, function($s) use ($match) {
return $s['matchid'] == $match['id'];
});
foreach ($match_sets as $set) {
$set['match'] = $match;
$result[] = $set;
}
}
return $result;
}
function hasStats($set) {
return $set['darts1'] > 0 || $set['darts2'] > 0 || $set['3da1'] > 0 || $set['3da2'] > 0;
}
function matchAllSets($matchday_id) {
global $all_matches;
if (!isset($_SESSION['sqlite_data']) || !isset($_SESSION['player_mapping'])) {
return [];
}
$player_mapping = $_SESSION['player_mapping'];
$matchday_date = null;
// Get matchday date
foreach ($GLOBALS['matchdays'] as $md) {
if ($md['id'] == $matchday_id) {
$matchday_date = $md['date'];
break;
}
}
try {
// Create temporary file for PDO
$tmp_file = tempnam(sys_get_temp_dir(), 'sqlite_import_');
file_put_contents($tmp_file, base64_decode($_SESSION['sqlite_data']));
$db = new PDO('sqlite:' . $tmp_file);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Get all sets for this matchday
$matchday_sets = getMatchdaySets($matchday_id);
$matches_info = [];
foreach ($matchday_sets as $set) {
$player1_csv_id = $set['player1id'];
$player2_csv_id = $set['player2id'];
// Get SQLite player IDs from mapping
// The mapping is: player_mapping[csv_player_id] = sqlite_player_id
$player1_sqlite_id = isset($player_mapping[$player1_csv_id]) ? $player_mapping[$player1_csv_id] : null;
$player2_sqlite_id = isset($player_mapping[$player2_csv_id]) ? $player_mapping[$player2_csv_id] : null;
$match_info = [
'set' => $set,
'matched' => false,
'matches' => [],
'selected_match_index' => 0,
'multiple' => false
// 'debug' => []
];
if ($player1_sqlite_id !== null && $player2_sqlite_id !== null) {
// Try to find matching set(s)
$result = findSetStatsWithInfo($db, $player1_sqlite_id, $player2_sqlite_id, $set['legs1'], $set['legs2'], $matchday_date);
if ($result && isset($result['matches']) && !empty($result['matches'])) {
$match_info['matched'] = true;
$match_info['matches'] = $result['matches'];
$match_info['multiple'] = $result['multiple'];
$match_info['selected_match_index'] = 0; // Default to first (most recent)
}
// Always store debug info
// if (isset($result['debug'])) {
// $match_info['debug'] = $result['debug'];
// }
} else {
// $match_info['debug'][] = "Player mapping failed: Player1=$player1_csv_id -> SQLite=" . ($player1_sqlite_id !== null ? $player1_sqlite_id : 'NOT FOUND') . ", Player2=$player2_csv_id -> SQLite=" . ($player2_sqlite_id !== null ? $player2_sqlite_id : 'NOT FOUND');
}
$matches_info[] = $match_info;
}
// Clean up temporary file
unlink($tmp_file);
return $matches_info;
} catch (Exception $e) {
// Clean up temporary file on error
if (isset($tmp_file) && file_exists($tmp_file)) {
unlink($tmp_file);
}
$_SESSION['error'] = 'Matching failed: ' . $e->getMessage();
return [];
}
}
function findSetStatsWithInfo($db, $player1_id, $player2_id, $expected_legs1, $expected_legs2, $matchday_date = null) {
// Build query to find all sets where these two players played
$date_filter = '';
$params = [$player1_id, $player2_id];
// $debug_info = [];
// $debug_info[] = "Searching for: Player1 ID=$player1_id, Player2 ID=$player2_id, Legs: $expected_legs1-$expected_legs2";
// $debug_info[] = "Matchday date: " . ($matchday_date ?: 'Not set');
if ($matchday_date && !empty($matchday_date)) {
$date_filter = " AND s.created_at >= date(?, '-2 days') AND s.created_at <= date(?, '+2 days')";
$params[] = $matchday_date;
$params[] = $matchday_date;
// $debug_info[] = "Date filter: ±2 days from $matchday_date";
}
$stmt = $db->prepare("
SELECT DISTINCT s.id as set_id, s.setNummer, s.created_at
FROM xGameMpSet s
JOIN xGameMpLeg l ON l.setId = s.id
JOIN xGameSpieler gs ON gs.legId = l.id
WHERE gs.spielerId IN (?, ?)
$date_filter
GROUP BY s.id
HAVING COUNT(DISTINCT gs.spielerId) = 2
ORDER BY s.created_at DESC
");
$stmt->execute($params);
$potential_sets = $stmt->fetchAll(PDO::FETCH_ASSOC);
// $debug_info[] = "Found " . count($potential_sets) . " potential sets with these players";
$all_matches = [];
// For each potential set, check if the leg counts match
foreach ($potential_sets as $set_info) {
$set_id = $set_info['set_id'];
// Count legs won by each player
$stmt = $db->prepare("
SELECT l.siegerId, COUNT(*) as legs_won
FROM xGameMpLeg l
WHERE l.setId = ?
GROUP BY l.siegerId
");
$stmt->execute([$set_id]);
$leg_counts = $stmt->fetchAll(PDO::FETCH_ASSOC);
$legs1 = 0;
$legs2 = 0;
foreach ($leg_counts as $lc) {
if ($lc['siegerId'] == $player1_id) {
$legs1 = $lc['legs_won'];
} elseif ($lc['siegerId'] == $player2_id) {
$legs2 = $lc['legs_won'];
}
}
// $debug_info[] = "Set ID $set_id (created: {$set_info['created_at']}): Legs $legs1-$legs2";
// Check if this matches our expected leg counts (in either order)
$match_forward = ($legs1 == $expected_legs1 && $legs2 == $expected_legs2);
$match_reverse = ($legs1 == $expected_legs2 && $legs2 == $expected_legs1);
if ($match_forward || $match_reverse) {
// This is a potential match! Extract stats and add to list
// If reversed, we need to swap the player IDs when extracting stats
if ($match_reverse) {
// $debug_info[] = "✓ MATCH FOUND (reversed player order)!";
$stats = extractSetStats($db, $set_id, $player2_id, $player1_id);
} else {
// $debug_info[] = "✓ MATCH FOUND!";
$stats = extractSetStats($db, $set_id, $player1_id, $player2_id);
}
$all_matches[] = [
'set_id' => $set_id,
'created_at' => $set_info['created_at'],
'stats' => $stats,
'reversed' => $match_reverse
];
}
}
// Return all matches found
if (count($all_matches) > 0) {
return [
'matches' => $all_matches,
'multiple' => count($all_matches) > 1
// 'debug' => $debug_info
];
}
// $debug_info[] = "✗ No matching set found";
return [
'matches' => [],
'multiple' => false
// 'debug' => $debug_info
];
}
function getPlayerName($player_id) {
global $csv_players;
if ($player_id == 0) return 'TBD';
if (isset($csv_players[$player_id])) {
$p = $csv_players[$player_id];
return $p['nickname'] ? $p['name'] . ' (' . $p['nickname'] . ')' : $p['name'];
}
return 'Unknown';
}
function resetImport() {
// Clear session data
unset($_SESSION['sqlite_data']);
unset($_SESSION['player_mapping']);
unset($_SESSION['selected_matchday']);
unset($_SESSION['import_step']);
header('Location: import_stats.php');
exit;
}