-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatchday_setup.php
More file actions
1296 lines (1118 loc) · 57.1 KB
/
matchday_setup.php
File metadata and controls
1296 lines (1118 loc) · 57.1 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
// matchday_setup.php - Tournament and Matchday Setup
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';
// Initialize CSV files
if (!file_exists($matchdays_file)) {
$fp = fopen($matchdays_file, 'w');
fputcsv($fp, ['id', 'date', 'location']);
fclose($fp);
}
if (!file_exists($matches_file)) {
$fp = fopen($matches_file, 'w');
fputcsv($fp, ['id', 'matchdayid', 'phase', 'firsttosets', 'firsttolegs', 'player1id', 'player2id', 'sets1', 'sets2']);
fclose($fp);
}
// Load data
$players = loadPlayers();
$matchdays = loadMatchdays();
$all_matches = loadMatches();
// Separate individuals and teams
$individuals = array_filter($players, function($p) { return $p['isteam'] == 0; });
$teams = array_filter($players, function($p) { return $p['isteam'] == 1; });
// Handle form submission
$setup_complete = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['generate_tournament'])) {
// Determine tournament type
$tournament_type = isset($_POST['tournament_type']) ? $_POST['tournament_type'] : 'singles';
// Get selected participants based on tournament type
$selected_entities = [];
if ($tournament_type == 'singles') {
// Singles: use selected individual players
if (isset($_POST['selected_players']) && is_array($_POST['selected_players'])) {
foreach ($_POST['selected_players'] as $id) {
foreach ($individuals as $p) {
if ($p['id'] == $id) {
$selected_entities[] = $p;
break;
}
}
}
} else {
$selected_entities = array_values($individuals);
}
} else {
// Doubles: use selected teams
if (isset($_POST['selected_teams']) && is_array($_POST['selected_teams'])) {
foreach ($_POST['selected_teams'] as $id) {
foreach ($teams as $t) {
if ($t['id'] == $id) {
$selected_entities[] = $t;
break;
}
}
}
} else {
$selected_entities = array_values($teams);
}
// NOTE: We allow overlapping teams in the tournament
// Match generation will ensure overlapping teams don't play each other
}
if (!isset($validation_error)) {
$selected_count = count($selected_entities);
// For doubles, playoffs are not allowed
if ($tournament_type == 'doubles') {
$_POST['regular_has_playoffs'] = '0';
$_POST['special_has_playoffs'] = '0';
}
// Check playoff settings
$regular_has_playoffs = isset($_POST['regular_has_playoffs']) && $_POST['regular_has_playoffs'] == '1';
$has_special = isset($_POST['has_special']) && $_POST['has_special'] == '1';
$special_has_playoffs = $has_special && isset($_POST['special_has_playoffs']) && $_POST['special_has_playoffs'] == '1';
// If ANY matchday has playoffs, need at least 4 participants
$any_playoffs = $regular_has_playoffs || $special_has_playoffs;
$min_participants = $any_playoffs ? 4 : 2;
if ($selected_count < $min_participants) {
if ($any_playoffs) {
$playoff_source = [];
if ($regular_has_playoffs) $playoff_source[] = "regular matchdays";
if ($special_has_playoffs) $playoff_source[] = "special matchday";
$entity_word = $tournament_type == 'singles' ? 'player(s)' : 'team(s)';
$validation_error = "Cannot create tournament with playoffs (" . implode(' and ', $playoff_source) . ") and fewer than 4 $entity_word. Selected: $selected_count $entity_word. Either select at least 4 $entity_word or disable playoffs.";
} else {
$entity_word = $tournament_type == 'singles' ? 'player(s)' : 'team(s)';
$validation_error = "Cannot create tournament with fewer than 2 $entity_word. Selected: $selected_count $entity_word.";
}
} else {
// Store selected entities in a format generateTournament expects
$entity_ids = array_map(function($e) { return $e['id']; }, $selected_entities);
$_POST['selected_players'] = $entity_ids; // Use existing field name
generateTournament($_POST);
$setup_complete = true;
}
}
}
if (isset($_POST['add_matchday'])) {
$result = addSingleMatchday($matchdays, $all_matches, $matchdays_file, $matches_file);
if ($result['success']) {
$add_success = $result['message'];
// Reload data
$matchdays = loadMatchdays();
$all_matches = loadMatches();
} else {
$add_error = $result['message'];
}
}
}
// 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[] = [
'id' => $row[0],
'name' => $row[1],
'nickname' => isset($row[2]) ? $row[2] : '',
'isteam' => isset($row[3]) ? intval($row[3]) : 0,
'player1id' => isset($row[4]) ? $row[4] : '',
'player2id' => isset($row[5]) ? $row[5] : ''
];
}
fclose($fp);
}
return $players;
}
function getPlayerById($id, $all_players) {
foreach ($all_players as $p) {
if ($p['id'] == $id) {
return $p;
}
}
return null;
}
function teamsSharePlayers($team1, $team2) {
// Check if two teams share any players
if ($team1['isteam'] != 1 || $team2['isteam'] != 1) {
return false; // Not both teams
}
$team1_players = [$team1['player1id'], $team1['player2id']];
$team2_players = [$team2['player1id'], $team2['player2id']];
foreach ($team1_players as $p) {
if (in_array($p, $team2_players)) {
return true;
}
}
return false;
}
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],
'standingsmethod' => isset($row[3]) ? $row[3] : 'points',
'winpoints' => isset($row[4]) ? intval($row[4]) : 2
];
}
fclose($fp);
}
return $matchdays;
}
function generateTournament($config) {
global $matchdays_file, $matches_file;
// Clear existing tournament data
if (file_exists($matchdays_file)) {
$fp = fopen($matchdays_file, 'w');
fputcsv($fp, ['id', 'date', 'location']);
fclose($fp);
}
// Save scoring scheme
$scoring_file = 'tables/scoringscheme.csv';
$fp_score = fopen($scoring_file, 'w');
fputcsv($fp_score, ['stat', 'rank', 'points']);
// Group phase positions
fputcsv($fp_score, ['pos_group_phase', '1', $config['score_group_1']]);
fputcsv($fp_score, ['pos_group_phase', '2', $config['score_group_2']]);
fputcsv($fp_score, ['pos_group_phase', '3', $config['score_group_3']]);
fputcsv($fp_score, ['pos_group_phase', '4', $config['score_group_4']]);
// Final positions
fputcsv($fp_score, ['pos_final', '1', $config['score_final_1']]);
fputcsv($fp_score, ['pos_final', '2', $config['score_final_2']]);
fputcsv($fp_score, ['pos_final', '3', $config['score_final_3']]);
fputcsv($fp_score, ['pos_final', '4', $config['score_final_4']]);
// Best statistics
fputcsv($fp_score, ['best_3da', '1', $config['score_best_3da']]);
fputcsv($fp_score, ['best_dbl', '1', $config['score_best_dbl']]);
fputcsv($fp_score, ['best_hs', '1', $config['score_best_hs']]);
fputcsv($fp_score, ['best_hco', '1', $config['score_best_hco']]);
fputcsv($fp_score, ['best_leg', '1', isset($config['score_best_leg']) ? $config['score_best_leg'] : 0]);
fputcsv($fp_score, ['most_180s', '1', isset($config['score_most_180s']) ? $config['score_most_180s'] : 0]);
fputcsv($fp_score, ['most_140s', '1', isset($config['score_most_140s']) ? $config['score_most_140s'] : 0]);
fputcsv($fp_score, ['most_100s', '1', isset($config['score_most_100s']) ? $config['score_most_100s'] : 0]);
fclose($fp_score);
$all_players = loadPlayers();
if (file_exists($matches_file)) {
$fp = fopen($matches_file, 'w');
fputcsv($fp, ['id', 'matchdayid', 'phase', 'firsttosets', 'firsttolegs', 'player1id', 'player2id', 'sets1', 'sets2']);
fclose($fp);
}
$sets_file = 'tables/sets.csv';
if (file_exists($sets_file)) {
$fp = fopen($sets_file, 'w');
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']);
fclose($fp);
}
$all_players = loadPlayers();
// Filter selected players
$players = [];
if (isset($config['selected_players']) && is_array($config['selected_players'])) {
foreach ($all_players as $player) {
if (in_array($player['id'], $config['selected_players'])) {
$players[] = $player;
}
}
} else {
$players = $all_players;
}
$num_regular_matchdays = intval($config['num_matchdays']);
$has_special = isset($config['has_special']) && $config['has_special'] == '1';
// Create matchdays
$fp = fopen($matchdays_file, 'w');
fputcsv($fp, ['id', 'date', 'location', 'standingsmethod', 'winpoints']);
$total_matchdays = $has_special ? $num_regular_matchdays + 1 : $num_regular_matchdays;
// Regular matchdays
for ($i = 1; $i <= $num_regular_matchdays; $i++) {
$standingsmethod = isset($config['regular_standingsmethod']) ? $config['regular_standingsmethod'] : 'points';
$winpoints = isset($config['regular_winpoints']) ? intval($config['regular_winpoints']) : 2;
fputcsv($fp, [$i, '', '', $standingsmethod, $winpoints]);
}
// Special matchday (if exists)
if ($has_special) {
$standingsmethod = isset($config['special_standingsmethod']) ? $config['special_standingsmethod'] : 'points';
$winpoints = isset($config['special_winpoints']) ? intval($config['special_winpoints']) : 2;
fputcsv($fp, [$num_regular_matchdays + 1, '', '', $standingsmethod, $winpoints]);
}
fclose($fp);
// Create matches
$fp = fopen($matches_file, 'w');
fputcsv($fp, ['id', 'matchdayid', 'phase', 'firsttosets', 'firsttolegs', 'player1id', 'player2id', 'sets1', 'sets2']);
$match_id = 1;
// Regular matchdays
for ($day = 1; $day <= $num_regular_matchdays; $day++) {
$match_id = generateMatchdayMatches(
$fp,
$match_id,
$day,
$players,
$config['regular_group_rounds'],
$config['regular_group_sets'],
$config['regular_group_legs'],
isset($config['regular_has_playoffs']) && $config['regular_has_playoffs'] == '1',
$config['regular_playoff_sets'],
$config['regular_playoff_legs'],
isset($config['regular_has_third']) && $config['regular_has_third'] == '1',
isset($config['regular_different_final']) && $config['regular_different_final'] == '1',
isset($config['regular_final_sets']) ? $config['regular_final_sets'] : $config['regular_playoff_sets'],
isset($config['regular_final_legs']) ? $config['regular_final_legs'] : $config['regular_playoff_legs']
);
}
// Special matchday
if ($has_special) {
$special_day = $num_regular_matchdays + 1;
$match_id = generateMatchdayMatches(
$fp,
$match_id,
$special_day,
$players,
$config['special_group_rounds'],
$config['special_group_sets'],
$config['special_group_legs'],
isset($config['special_has_playoffs']) && $config['special_has_playoffs'] == '1',
$config['special_playoff_sets'],
$config['special_playoff_legs'],
isset($config['special_has_third']) && $config['special_has_third'] == '1',
isset($config['special_different_final']) && $config['special_different_final'] == '1',
isset($config['special_final_sets']) ? $config['special_final_sets'] : $config['special_playoff_sets'],
isset($config['special_final_legs']) ? $config['special_final_legs'] : $config['special_playoff_legs']
);
}
fclose($fp);
}
function generateMatchdayMatches($fp, $match_id, $day, $players, $group_rounds, $group_sets, $group_legs, $has_playoffs, $playoff_sets, $playoff_legs, $has_third, $different_final, $final_sets, $final_legs) {
// Generate group phase matches
$all_group_matches = [];
for ($round = 1; $round <= intval($group_rounds); $round++) {
for ($i = 0; $i < count($players); $i++) {
for ($j = $i + 1; $j < count($players); $j++) {
// Skip if both are teams and they share players
if (isset($players[$i]['isteam']) && $players[$i]['isteam'] == 1 &&
isset($players[$j]['isteam']) && $players[$j]['isteam'] == 1) {
if (teamsSharePlayers($players[$i], $players[$j])) {
continue; // Skip this pairing
}
}
$all_group_matches[] = [
'player1' => $players[$i]['id'],
'player2' => $players[$j]['id']
];
}
}
}
// Reorder matches to ensure no player plays more than twice in a row
$ordered_matches = [];
$player_consecutive_count = [];
while (!empty($all_group_matches)) {
$placed = false;
$best_match = null;
$best_key = null;
$best_score = -1;
foreach ($all_group_matches as $key => $match) {
$p1 = $match['player1'];
$p2 = $match['player2'];
// Get consecutive play count for both players
$p1_consecutive = isset($player_consecutive_count[$p1]) ? $player_consecutive_count[$p1] : 0;
$p2_consecutive = isset($player_consecutive_count[$p2]) ? $player_consecutive_count[$p2] : 0;
// Skip if either player has already played twice consecutively
if ($p1_consecutive >= 2 || $p2_consecutive >= 2) {
continue;
}
// Score this match (prefer players who haven't played recently)
$score = (10 - $p1_consecutive) + (10 - $p2_consecutive);
if ($score > $best_score) {
$best_score = $score;
$best_match = $match;
$best_key = $key;
}
}
// If we found a valid match, place it
if ($best_match !== null) {
$ordered_matches[] = $best_match;
// Update consecutive counts for ALL players
$new_consecutive_count = [];
foreach ($players as $player) {
$pid = $player['id'];
if ($pid == $best_match['player1'] || $pid == $best_match['player2']) {
// Players in this match: increment their count
$new_consecutive_count[$pid] = (isset($player_consecutive_count[$pid]) ? $player_consecutive_count[$pid] : 0) + 1;
} else {
// Players NOT in this match: reset to 0
$new_consecutive_count[$pid] = 0;
}
}
$player_consecutive_count = $new_consecutive_count;
unset($all_group_matches[$best_key]);
$all_group_matches = array_values($all_group_matches); // Re-index
$placed = true;
} else {
// No valid match found - reset all counters and try again
$player_consecutive_count = [];
// Take first available match
if (!empty($all_group_matches)) {
$match = array_shift($all_group_matches);
$ordered_matches[] = $match;
foreach ($players as $player) {
$pid = $player['id'];
if ($pid == $match['player1'] || $pid == $match['player2']) {
$player_consecutive_count[$pid] = 1;
} else {
$player_consecutive_count[$pid] = 0;
}
}
}
}
}
// Write ordered matches to CSV
foreach ($ordered_matches as $match) {
fputcsv($fp, [
$match_id++,
$day,
'group',
$group_sets,
$group_legs,
$match['player1'],
$match['player2'],
0,
0
]);
}
// Generate playoff matches if enabled
if ($has_playoffs == '1') {
// Semi-finals: 1st vs 4th, 2nd vs 3rd
fputcsv($fp, [$match_id++, $day, 'semi1', $playoff_sets, $playoff_legs, 0, 0, 0, 0]);
fputcsv($fp, [$match_id++, $day, 'semi2', $playoff_sets, $playoff_legs, 0, 0, 0, 0]);
// 3rd place match if enabled
if ($has_third) {
fputcsv($fp, [$match_id++, $day, 'third', $playoff_sets, $playoff_legs, 0, 0, 0, 0]);
}
// Final - use different format if specified
if ($different_final == '1') {
fputcsv($fp, [$match_id++, $day, 'final', $final_sets, $final_legs, 0, 0, 0, 0]);
} else {
fputcsv($fp, [$match_id++, $day, 'final', $playoff_sets, $playoff_legs, 0, 0, 0, 0]);
}
}
return $match_id;
// Generate playoff matches if enabled
if ($has_playoffs == '1') {
// Semi-finals: 1st vs 4th, 2nd vs 3rd
fputcsv($fp, [$match_id++, $day, 'semi1', $playoff_sets, $playoff_legs, 0, 0, 0, 0]); // 1st vs 4th
fputcsv($fp, [$match_id++, $day, 'semi2', $playoff_sets, $playoff_legs, 0, 0, 0, 0]); // 2nd vs 3rd
// 3rd place match if enabled
if ($has_third) {
fputcsv($fp, [$match_id++, $day, 'third', $playoff_sets, $playoff_legs, 0, 0, 0, 0]);
}
// Final
fputcsv($fp, [$match_id++, $day, 'final', $playoff_sets, $playoff_legs, 0, 0, 0, 0]);
}
return $match_id;
}
function getPlayerName($player_id) {
$all_players = loadPlayers();
if ($player_id == 0) return 'TBD';
foreach ($all_players as $p) {
if ($p['id'] == $player_id) {
return $p['nickname'] ? $p['name'] . ' (' . $p['nickname'] . ')' : $p['name'];
}
}
return 'Unknown';
}
function canAddMatchday($matchdays, $all_matches) {
if (empty($matchdays)) return false;
// Check if special matchday exists
// Assumption: if matchday count doesn't match expected pattern, there's a special one
// Better approach: check if all matchdays have identical format
$formats = [];
foreach ($matchdays as $md) {
$md_id = $md['id'];
$md_matches = array_filter($all_matches, function($m) use ($md_id) {
return $m['matchdayid'] == $md_id;
});
$group_matches = array_filter($md_matches, function($m) { return $m['phase'] == 'group'; });
$playoff_matches = array_filter($md_matches, function($m) { return $m['phase'] != 'group'; });
if (empty($group_matches)) continue;
$first_group = array_values($group_matches)[0];
$format_key = $first_group['firsttosets'] . '_' . $first_group['firsttolegs'] . '_' . count($group_matches);
if (!empty($playoff_matches)) {
$first_playoff = array_values($playoff_matches)[0];
$format_key .= '_p_' . $first_playoff['firsttosets'] . '_' . $first_playoff['firsttolegs'] . '_' . count($playoff_matches);
}
$formats[$format_key] = isset($formats[$format_key]) ? $formats[$format_key] + 1 : 1;
}
// If more than one format exists, don't allow adding (indicates special matchday)
if (count($formats) > 1) {
return false;
}
return true;
}
function getMatchdayFormat($matchday_id, $all_matches) {
// Extract complete format from an existing matchday
$md_matches = array_filter($all_matches, function($m) use ($matchday_id) {
return $m['matchdayid'] == $matchday_id;
});
$group_matches = array_filter($md_matches, function($m) { return $m['phase'] == 'group'; });
$playoff_matches = array_filter($md_matches, function($m) { return $m['phase'] != 'group'; });
if (empty($group_matches)) return null;
$first_group = array_values($group_matches)[0];
// Extract players from group matches
$players = [];
foreach ($group_matches as $match) {
if (!in_array($match['player1id'], $players)) {
$players[] = $match['player1id'];
}
if (!in_array($match['player2id'], $players)) {
$players[] = $match['player2id'];
}
}
// Calculate number of rounds
$num_players = count($players);
$matches_per_round = ($num_players * ($num_players - 1)) / 2;
$group_rounds = $matches_per_round > 0 ? count($group_matches) / $matches_per_round : 1;
$format = [
'players' => $players,
'group_rounds' => $group_rounds,
'group_sets' => $first_group['firsttosets'],
'group_legs' => $first_group['firsttolegs'],
'has_playoffs' => !empty($playoff_matches) ? '1' : '0',
'playoff_sets' => 0,
'playoff_legs' => 0,
'has_third' => false,
'different_final' => false,
'final_sets' => 0,
'final_legs' => 0
];
if (!empty($playoff_matches)) {
$first_playoff = array_values($playoff_matches)[0];
$format['playoff_sets'] = $first_playoff['firsttosets'];
$format['playoff_legs'] = $first_playoff['firsttolegs'];
// Check for third place match
foreach ($playoff_matches as $pm) {
if ($pm['phase'] == 'third') {
$format['has_third'] = true;
}
if ($pm['phase'] == 'final') {
// Check if final has different format
if ($pm['firsttosets'] != $format['playoff_sets'] || $pm['firsttolegs'] != $format['playoff_legs']) {
$format['different_final'] = true;
$format['final_sets'] = $pm['firsttosets'];
$format['final_legs'] = $pm['firsttolegs'];
}
}
}
}
return $format;
}
function addSingleMatchday($matchdays, $all_matches, $matchdays_file, $matches_file) {
// Get format from first matchday
$format = getMatchdayFormat(1, $all_matches);
if (!$format) {
return ['success' => false, 'message' => 'Could not determine matchday format.'];
}
// Get next matchday ID
$next_matchday_id = count($matchdays) + 1;
// Get standings configuration from first matchday
$first_md = $matchdays[0];
$standingsmethod = isset($first_md['standingsmethod']) ? $first_md['standingsmethod'] : 'points';
$winpoints = isset($first_md['winpoints']) ? $first_md['winpoints'] : 2;
// Find max match ID
$max_match_id = 0;
foreach ($all_matches as $m) {
if ($m['id'] > $max_match_id) {
$max_match_id = $m['id'];
}
}
$next_match_id = $max_match_id + 1;
// Append new matchday to matchdays.csv
$fp = fopen($matchdays_file, 'a');
fputcsv($fp, [$next_matchday_id, '', '', $standingsmethod, $winpoints]);
fclose($fp);
// Append new matches to matches.csv
$fp = fopen($matches_file, 'a');
// Get full player objects for generateMatchdayMatches
$all_players = loadPlayers();
$selected_players = [];
foreach ($all_players as $player) {
if (in_array($player['id'], $format['players'])) {
$selected_players[] = $player;
}
}
// Generate matches using existing function
generateMatchdayMatches(
$fp,
$next_match_id,
$next_matchday_id,
$selected_players,
$format['group_rounds'],
$format['group_sets'],
$format['group_legs'],
$format['has_playoffs'],
$format['playoff_sets'],
$format['playoff_legs'],
$format['has_third'],
$format['different_final'],
$format['final_sets'],
$format['final_legs']
);
fclose($fp);
return ['success' => true, 'message' => "Matchday $next_matchday_id added successfully."];
}
function loadMatches() {
$matches_file = 'tables/matches.csv';
$matches = [];
if (file_exists($matches_file) && ($fp = fopen($matches_file, 'r')) !== false) {
$header = fgetcsv($fp);
while (($row = fgetcsv($fp)) !== false) {
$matches[] = [
'id' => $row[0],
'matchdayid' => $row[1],
'phase' => $row[2],
'firsttosets' => $row[3],
'firsttolegs' => $row[4],
'player1id' => $row[5],
'player2id' => $row[6],
'sets1' => $row[7],
'sets2' => $row[8]
];
}
fclose($fp);
}
return $matches;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Tournament Setup</title>
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function togglePlayoffs(prefix) {
var checkbox = document.getElementById(prefix + '_has_playoffs');
var settings = document.getElementById(prefix + '_playoff_settings');
if (checkbox.checked) {
settings.style.display = 'block';
} else {
settings.style.display = 'none';
}
// Update playoff scoring section visibility (checks BOTH regular and special)
updatePlayoffScoringVisibility();
}
function updatePlayoffScoringVisibility() {
var regularPlayoffs = document.getElementById('regular_has_playoffs');
var specialEnabled = document.getElementById('has_special');
var specialPlayoffs = document.getElementById('special_has_playoffs');
var scoringSection = document.getElementById('regular_playoff_scoring');
if (!scoringSection) return;
// Check if ANY matchday type has playoffs enabled
var regularHasPlayoffs = regularPlayoffs && regularPlayoffs.checked;
var specialHasPlayoffs = specialEnabled && specialEnabled.checked &&
specialPlayoffs && specialPlayoffs.checked;
// Show scoring section if ANY matchday has playoffs
if (regularHasPlayoffs || specialHasPlayoffs) {
scoringSection.style.display = 'block';
} else {
scoringSection.style.display = 'none';
}
}
function toggleSpecial() {
var checkbox = document.getElementById('has_special');
var specialSettings = document.getElementById('special_settings');
specialSettings.style.display = checkbox.checked ? 'block' : 'none';
updatePlayoffScoringVisibility();
}
function toggleFinalFormat(prefix) {
var checkbox = document.getElementById(prefix + '_different_final');
var finalSettings = document.getElementById(prefix + '_final_settings');
finalSettings.style.display = checkbox.checked ? 'block' : 'none';
}
function toggleTournamentType() {
var isSingles = document.getElementById('type_singles').checked;
var singlesSection = document.getElementById('singles_selection');
var doublesSection = document.getElementById('doubles_selection');
var playoffCheckbox = document.getElementById('regular_has_playoffs');
var playoffSettings = document.getElementById('regular_playoff_settings');
var specialPlayoffCheckbox = document.getElementById('special_has_playoffs');
if (isSingles) {
singlesSection.style.display = 'block';
doublesSection.style.display = 'none';
// Playoffs allowed for singles
if (playoffCheckbox) playoffCheckbox.disabled = false;
if (specialPlayoffCheckbox) specialPlayoffCheckbox.disabled = false;
} else {
singlesSection.style.display = 'none';
doublesSection.style.display = 'block';
// Disable and uncheck playoffs for doubles
if (playoffCheckbox) {
playoffCheckbox.checked = false;
playoffCheckbox.disabled = true;
playoffSettings.style.display = 'none';
}
if (specialPlayoffCheckbox) {
specialPlayoffCheckbox.checked = false;
specialPlayoffCheckbox.disabled = true;
}
updatePlayoffScoringVisibility();
}
}
</script>
</head>
<body>
<?php if (isset($validation_error)): ?>
<div class="warning" style="margin: 20px; padding: 15px; background-color: #fff3cd; border: 2px solid #ff0000;">
<strong>Error:</strong> <?php echo $validation_error; ?>
</div>
<?php endif; ?>
<nav>
<a href="index.php">Tournament Overview</a>
<?php if (!empty($matchdays)): ?>
<?php foreach ($matchdays as $md): ?>
| <a href="matchdays.php?view=<?php echo $md['id']; ?>">Matchday <?php echo $md['id']; ?></a>
<?php endforeach; ?>
<?php endif; ?>
</nav>
<h1>Tournament Setup</h1>
<?php if ($setup_complete): ?>
<div class="info">
<strong>Setup Complete!</strong> Tournament structure has been created.<br>
<a href="matchdays.php"><button type="button">Go to Matchday Management</button></a>
<a href="matchday_setup.php"><button type="button">Start New Setup</button></a>
</div>
<?php else: ?>
<?php if (empty($players)): ?>
<div class="warning">
<strong>Warning:</strong> No players found! Please add players before setting up the tournament.<br>
<a href="players.php"><button type="button">Go to Player Management</button></a>
</div>
<?php elseif (count($individuals) < 2 && count($teams) < 2): ?>
<div class="warning">
<strong>Error:</strong> You need at least 2 players or 2 teams to create a tournament.<br>
Currently registered: <?php echo count($individuals); ?> individual player(s) and <?php echo count($teams); ?> team(s).<br><br>
<a href="players.php"><button type="button">Add More Players or Create Teams</button></a>
</div>
<?php else: ?>
<?php
// Check if tournament already exists
$tournament_exists = !empty($matchdays);
$can_add = $tournament_exists && canAddMatchday($matchdays, $all_matches);
?>
<?php if (isset($add_success)): ?>
<div class="info" style="margin: 20px; padding: 15px; background-color: #d4edda; border: 2px solid #28a745;">
<strong>Success:</strong> <?php echo $add_success; ?><br><br>
<a href="matchdays.php"><button type="button">View Matchdays</button></a>
</div>
<?php endif; ?>
<?php if (isset($add_error)): ?>
<div class="warning" style="margin: 20px; padding: 15px;">
<strong>Error:</strong> <?php echo $add_error; ?>
</div>
<?php endif; ?>
<?php if ($can_add): ?>
<div id="add_matchday_section" class="section" style="margin-bottom: 30px;">
<h2>Add New Matchday</h2>
<?php
// Get format info to display
$format = getMatchdayFormat(1, $all_matches);
$num_players = count($format['players']);
$player_names = [];
foreach ($format['players'] as $pid) {
foreach ($players as $p) {
if ($p['id'] == $pid) {
$player_names[] = $p['name'];
break;
}
}
}
?>
<div class="info">
<p><strong>Add matchday <?php echo count($matchdays) + 1; ?> with the same format as existing matchdays:</strong></p>
<ul>
<li><strong>Players:</strong> <?php echo implode(', ', $player_names); ?> (<?php echo $num_players; ?> players)</li>
<li><strong>Group Phase:</strong> <?php echo $format['group_rounds']; ?> round(s), Best of <?php echo $format['group_sets']; ?> sets, First to <?php echo $format['group_legs']; ?> legs</li>
<?php if ($format['has_playoffs'] == '1'): ?>
<li><strong>Playoffs:</strong> Semi-Finals (Best of <?php echo $format['playoff_sets']; ?> sets, First to <?php echo $format['playoff_legs']; ?> legs)</li>
<?php if ($format['has_third']): ?>
<li><strong>3rd Place Match:</strong> Yes</li>
<?php endif; ?>
<?php if ($format['different_final']): ?>
<li><strong>Final:</strong> Best of <?php echo $format['final_sets']; ?> sets, First to <?php echo $format['final_legs']; ?> legs</li>
<?php else: ?>
<li><strong>Final:</strong> Same format as Semi-Finals</li>
<?php endif; ?>
<?php else: ?>
<li><strong>Playoffs:</strong> No playoffs</li>
<?php endif; ?>
<li><strong>Standings Method:</strong>
<?php
$first_md = $matchdays[0];
if (isset($first_md['standingsmethod']) && $first_md['standingsmethod'] == 'leg_diff') {
echo 'Leg Difference';
} else {
echo 'Points-based (' . (isset($first_md['winpoints']) ? $first_md['winpoints'] : 2) . ' points per win)';
}
?>
</li>
</ul>
</div>
<form method="POST" onsubmit="return confirm('Add matchday <?php echo count($matchdays) + 1; ?> with the format shown above?');">
<input type="submit" name="add_matchday" value="Add Matchday <?php echo count($matchdays) + 1; ?>" style="background-color: #28a745; color: white; padding: 10px 20px; font-size: 16px;">
</form>
</div>
<hr style="margin: 30px 0;">
<?php endif; ?>
<?php if ($tournament_exists && !$can_add): ?>
<div class="warning" style="margin-bottom: 30px;">
<strong>Cannot add matchdays:</strong> Your tournament has matchdays with different formats (possibly a special matchday).<br>
Adding matchdays is only allowed when all existing matchdays have identical format.<br><br>
<strong>Option:</strong> You can rebuild the entire tournament below.
</div>
<?php endif; ?>
<?php if ($tournament_exists): ?>
<div class="warning">
<strong>Warning:</strong> A tournament structure already exists with <?php echo count($matchdays); ?> matchdays.<br>
Creating a new tournament will overwrite all existing matchdays and matches.<br><br>
<strong>Options:</strong><br>
<a href="matchdays.php"><button type="button">Edit Existing Tournament</button></a>
<button type="button" onclick="showSetupForm()">Create New Tournament (Overwrite)</button>
</div>
<div id="setup_form" style="display: none;">
<?php else: ?>
<div id="setup_form">
<?php endif; ?>
<div class="info">
<strong>Players registered:</strong> <?php echo count($players); ?>
</div>
<?php endif; ?>
<?php if (count($players) >= 4): ?>
<form method="POST">
<div class="form-section">
<h2>Tournament Type</h2>
<p>Select tournament type:</p>
<label class="inline">
<input type="radio" name="tournament_type" value="singles" id="type_singles" checked onchange="toggleTournamentType()">
Singles (Individual Players)
</label><br>
<label class="inline">
<input type="radio" name="tournament_type" value="doubles" id="type_doubles" onchange="toggleTournamentType()">
Doubles (Teams)
</label>
</div>
<div class="form-section" id="singles_selection">
<h2>Select Participating Players</h2>
<p>Select which players will participate in this tournament:</p>
<?php foreach ($individuals as $player): ?>
<label class="inline">
<input type="checkbox" name="selected_players[]" value="<?php echo $player['id']; ?>" checked>
<?php echo htmlspecialchars($player['name']); ?>
</label><br>
<?php endforeach; ?>
</div>
<div class="form-section" id="doubles_selection" style="display: none;">
<h2>Select Participating Teams</h2>
<?php if (empty($teams)): ?>
<div class="warning">
<strong>No teams available!</strong> Please create teams in <a href="players.php">Player Management</a> before setting up a doubles tournament.
</div>
<?php else: ?>
<p>Select which teams will participate in this tournament:</p>
<?php foreach ($teams as $team): ?>
<label class="inline">
<input type="checkbox" name="selected_teams[]" value="<?php echo $team['id']; ?>" checked>
<?php echo htmlspecialchars($team['name']); ?>
</label><br>
<?php endforeach; ?>
<?php endif; ?>
</div>
<div class="form-section">
<h2>Regular Matchdays</h2>
<label>Number of regular matchdays:</label>
<input type="number" name="num_matchdays" min="1" value="6" required>
<div class="subsection">
<h3>Group Phase Settings</h3>
<label>Number of rounds (everyone plays everyone X times):</label>
<select name="regular_group_rounds" required>
<option value="1">1 (single round-robin)</option>
<option value="2">2 (double round-robin)</option>
</select>
<label>Group match format - First to X sets:</label>
<input type="number" name="regular_group_sets" min="1" value="1" required>
<label>Each set - First to X legs:</label>
<input type="number" name="regular_group_legs" min="1" value="3" required>
<h3>Group Standings Configuration</h3>
<table>
<tr>
<th>Setting</th>
<th>Value</th>
</tr>
<tr>
<td>Standings Method</td>
<td>