-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
3449 lines (3175 loc) · 154 KB
/
Copy pathapi.php
File metadata and controls
3449 lines (3175 loc) · 154 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
/**
* CINEMAX EGYPT — BACKEND API (api.php)
* ============================================================
* Single entry point for all requests from the frontend.
*
* GET requests: api.php?action=X¶m=Y
* POST requests: api.php with JSON body { "action": "X", ... }
*
* All responses are JSON:
* Success: { "status": "success", ... }
* Failure: { "status": "error", "message": "..." }
*
* ACTIONS:
* Cinemas: governorates, cinemas, movie_cinemas
* Shows: showtimes, showtime_details
* Booking: book, my_bookings
* Reviews: get_comments, add_comment
* Auth: login, register, logout, session, csrf_token
* TMDB: movies_now_showing, movies_upcoming, movie_trailer,
* movie_cast, movie_details, streaming_providers,
* person_details
* Other: support, sync_status, trigger_sync
* ============================================================
*/
header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');
const PENDING_CASH_EXPIRY_MINUTES = 30;
// ── Session isolation ─────────────────────────────────────────
// The admin dashboard and the public website must keep completely
// separate logins. They run in the same PHP app, so by default they
// would share one session cookie — signing into the admin panel would
// also sign you in on the main site, and vice versa. To prevent that,
// the admin pages send ctx=manager_admin or ctx=regional_admin (see admin.js)
// and each context receives its own named session cookie.
$clientCtx = $_GET['ctx'] ?? '';
// Three separated login areas:
// - public website users use CINEMAXUSER
// - manager admin uses CINEMAXMANAGER
// - regional/staff admins use CINEMAXREGIONAL
// This prevents a manager login from replacing a regional admin login,
// and prevents both admin logins from replacing the normal website login.
if ($clientCtx === 'manager_admin') {
session_name('CINEMAXMANAGER');
} elseif ($clientCtx === 'regional_admin') {
session_name('CINEMAXREGIONAL');
} elseif ($clientCtx === 'admin') {
// Backward compatibility for older admin.js files.
session_name('CINEMAXADMIN');
} else {
session_name('CINEMAXUSER');
}
// Detect HTTPS, including when behind the Cloudflare tunnel (which terminates
// TLS and forwards over plain HTTP with an X-Forwarded-Proto header). Without
// this, the session cookie can be dropped on the public HTTPS URL.
$isHttps = (
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
(($_SERVER['SERVER_PORT'] ?? '') == 443) ||
(strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')
);
$cookieParams = [
'lifetime' => 0,
'path' => '/',
'secure' => $isHttps,
'httponly' => true,
'samesite' => 'Lax',
];
session_set_cookie_params($cookieParams);
ini_set('session.gc_maxlifetime', '86400'); // keep idle sessions for 24h
ini_set('session.use_strict_mode', '1');
session_start();
require_once 'db.php';
require_once 'tmdb_service.php';
// ── Read action ───────────────────────────────────────────────
$data = [];
$action = $_GET['action'] ?? '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true) ?? [];
if (isset($data['action'])) $action = $data['action'];
}
// ── Helper functions ──────────────────────────────────────────
/** Send a success JSON response and stop. */
function ok(array $payload): void {
echo json_encode(['status' => 'success'] + $payload);
exit;
}
/** Send an error JSON response and stop. */
function fail(string $msg, int $code = 200): void {
http_response_code($code);
echo json_encode(['status' => 'error', 'message' => $msg]);
exit;
}
/**
* Validate that a newly entered email uses a real public email provider.
* This does not prove the mailbox exists; that would require sending a
* confirmation email. It blocks fake/demo domains such as test.com, x.com,
* localhost, cinemax.local, and random invalid domains during registration
* or admin account creation.
*/
function allowedPublicEmailDomains(): array {
return [
'gmail.com', 'googlemail.com',
'yahoo.com', 'yahoo.co.uk', 'yahoo.com.eg', 'ymail.com', 'rocketmail.com',
'outlook.com', 'hotmail.com', 'live.com', 'msn.com',
'icloud.com', 'me.com', 'mac.com',
'proton.me', 'protonmail.com',
'aol.com', 'mail.com', 'zoho.com', 'yandex.com', 'gmx.com', 'gmx.net'
];
}
function isAllowedPublicEmail(string $email): bool {
$email = trim(strtolower($email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
$domain = substr(strrchr($email, '@') ?: '', 1);
return in_array($domain, allowedPublicEmailDomains(), true);
}
function requirePublicEmail(string $email): void {
if (!isAllowedPublicEmail($email)) {
fail('Please use a real email from Gmail, Yahoo, Outlook, Hotmail, iCloud, Proton, Zoho, Mail.com, Yandex, AOL, or GMX.');
}
}
function requireStrongPassword(string $password, string $label = 'Password'): void {
if (strlen($password) < 6) {
fail($label . ' must be at least 6 characters.');
}
if (!preg_match('/[A-Za-z]/', $password) || !preg_match('/\d/', $password)) {
fail($label . ' must contain both letters and numbers. It cannot be only letters or only numbers.');
}
}
function normalizePhoneNumber(string $phone): string {
$phone = trim($phone);
$phone = preg_replace('/[^0-9+]/', '', $phone);
if (strpos($phone, '00') === 0) {
$phone = '+' . substr($phone, 2);
}
return $phone;
}
function requireRecoveryChannel(string $channel, string $phone = ''): array {
$channel = strtolower(trim($channel ?: 'email'));
if (!in_array($channel, ['email', 'phone'], true)) {
fail('Choose how you want to receive the code: email or WhatsApp/SMS.');
}
$phone = normalizePhoneNumber($phone);
if ($channel === 'phone') {
// Accept Egyptian/international style numbers for manual WhatsApp/SMS delivery.
// This validates the shape only; the admin must still verify that the number belongs to the user.
if (!preg_match('/^\+?[0-9]{10,15}$/', $phone)) {
fail('Please enter a valid phone number for WhatsApp/SMS, for example +201001234567.');
}
}
return [$channel, $phone];
}
function publicBaseUrl(): string {
$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
$scheme = $https ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
return $scheme . '://' . $host . ($path ? $path : '');
}
function sendCinemaxEmail(PDO $pdo, string $to, string $subject, string $body): bool {
$fromAddress = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'no-reply@cinemax.local';
$fromName = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : 'CINEMAX Support';
$headers = "From: {$fromName} <{$fromAddress}>\r\n" .
"Reply-To: {$fromAddress}\r\n" .
"Content-Type: text/plain; charset=UTF-8\r\n";
$sent = false;
$error = null;
try {
$sent = @mail($to, $subject, $body, $headers);
if (!$sent) $error = 'PHP mail() is not configured on this server.';
} catch (Throwable $e) {
$sent = false;
$error = $e->getMessage();
}
try {
$stmt = $pdo->prepare("INSERT INTO email_outbox (recipient_email, subject, body, status, error_message) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$to, $subject, $body, $sent ? 'sent' : 'local_only', $error]);
} catch (Throwable $e) {}
return $sent;
}
function createPasswordResetCode(PDO $pdo, int $userId, string $email): string {
$code = (string)random_int(100000, 999999);
$hash = password_hash($code, PASSWORD_DEFAULT);
$expiresAt = date('Y-m-d H:i:s', time() + 10 * 60);
$pdo->prepare("UPDATE password_reset_codes SET used_at = NOW() WHERE user_id = ? AND used_at IS NULL")->execute([$userId]);
$stmt = $pdo->prepare("INSERT INTO password_reset_codes (user_id, email, code_hash, expires_at, ip_address) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$userId, $email, $hash, $expiresAt, $_SERVER['REMOTE_ADDR'] ?? null]);
return $code;
}
function sendPasswordResetCode(PDO $pdo, array $user): array {
$code = createPasswordResetCode($pdo, (int)$user['id'], $user['email']);
$expiresAt = date('Y-m-d H:i:s', time() + 10 * 60);
$subject = 'CINEMAX password reset code';
$body = "Hello {$user['username']},\n\n" .
"Your CINEMAX password reset code is: {$code}\n\n" .
"This code expires in 10 minutes. If you did not request this, ignore this message.\n\n" .
"CINEMAX";
// For the university/local project, the code is generated by the system
// and shown to the manager/admin, so the admin can send it manually by
// WhatsApp, Gmail, Outlook, Yahoo, etc. We also attempt PHP mail when it
// is configured, and always keep a copy in email_outbox for testing.
$sent = sendCinemaxEmail($pdo, $user['email'], $subject, $body);
return [
'mail_sent' => $sent,
'manual_code' => $code,
'expires_at' => $expiresAt,
'manual_message' => "CINEMAX password reset code for {$user['email']}: {$code}. This code expires in 10 minutes."
];
}
/** Remove login-only session data while keeping the PHP session usable for CSRF. */
function clearAuthSession(): void {
unset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['role'], $_SESSION['governorate_id'], $_SESSION['governorate_name'], $_SESSION['governorate_ids']);
}
/** Return the real database user for the active session, or null if it is stale. */
function currentSessionUser(PDO $pdo): ?array {
if (empty($_SESSION['user_id'])) {
return null;
}
$stmt = $pdo->prepare("
SELECT u.*, g.name_en AS governorate_name
FROM users u
LEFT JOIN governorates g ON u.governorate_id = g.id
WHERE u.id = ?
LIMIT 1
");
$stmt->execute([(int)$_SESSION['user_id']]);
$user = $stmt->fetch();
return $user ?: null;
}
/**
* Return every governorate id an admin/staff account is responsible for.
* Reads the admin_governorates many-to-many table and always includes the
* primary users.governorate_id, so single-region accounts keep working even
* if the table is empty.
*/
function loadAdminGovernorateIds(PDO $pdo, int $userId, ?int $primaryGovId): array {
$ids = [];
if (tableExists($pdo, 'admin_governorates')) {
try {
$stmt = $pdo->prepare("SELECT governorate_id FROM admin_governorates WHERE user_id = ?");
$stmt->execute([$userId]);
$ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
} catch (Throwable $e) { $ids = []; }
}
if ($primaryGovId) { $ids[] = (int)$primaryGovId; }
return array_values(array_unique(array_filter($ids)));
}
/** Accept governorate_ids (array or comma string) or a single governorate_id. */
function adminParseGovernorateIds(array $data): array {
$raw = $data['governorate_ids'] ?? null;
if ($raw === null && isset($data['governorate_id'])) {
$raw = $data['governorate_id'];
}
if (is_string($raw)) {
$raw = array_map('trim', explode(',', $raw));
}
if (!is_array($raw)) { $raw = $raw === null ? [] : [$raw]; }
$ids = array_values(array_unique(array_filter(array_map('intval', $raw))));
return $ids;
}
/** Keep only ids that exist in governorates, preserving the given order. */
function adminValidateGovernorateIds(PDO $pdo, array $ids): array {
if (!$ids) return [];
$ph = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT id FROM governorates WHERE id IN ($ph)");
$stmt->execute($ids);
$found = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
$ordered = [];
foreach ($ids as $id) {
if (in_array($id, $found, true) && !in_array($id, $ordered, true)) {
$ordered[] = $id;
}
}
return $ordered;
}
function adminGovernorateNames(PDO $pdo, array $ids): string {
$ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
if (!$ids) return 'no assigned region';
$ph = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT name_en FROM governorates WHERE id IN ($ph) ORDER BY name_en");
$stmt->execute($ids);
$names = $stmt->fetchAll(PDO::FETCH_COLUMN);
return $names ? implode(', ', $names) : 'assigned region';
}
/** Stop with 401 if no active valid database-backed session. Used by protected actions. */
function requireAuth(): void { global $pdo;
$user = currentSessionUser($pdo);
if (!$user) {
clearAuthSession();
fail('Your session expired. Please sign in again.', 401);
}
if (!empty($user['is_blocked'])) {
clearAuthSession();
fail('Your account is blocked.', 403);
}
$_SESSION['user_id'] = (int)$user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'] ?? 'user';
if (!empty($user['governorate_id'])) {
$_SESSION['governorate_id'] = (int)$user['governorate_id'];
$_SESSION['governorate_name'] = $user['governorate_name'] ?? '';
} else {
unset($_SESSION['governorate_id'], $_SESSION['governorate_name']);
}
$_SESSION['governorate_ids'] = loadAdminGovernorateIds(
$pdo, (int)$user['id'], !empty($user['governorate_id']) ? (int)$user['governorate_id'] : null
);
}
/** Stop with 403 if the current user is not an admin. */
function requireAdmin(): void {
requireAuth();
if (($_SESSION['role'] ?? '') !== 'admin') {
fail('Admin access required.', 403);
}
}
/** Stop with 403 if the current user is neither admin nor staff. */
function requireStaffOrAdmin(): void {
requireAuth();
$role = $_SESSION['role'] ?? '';
if (!in_array($role, ['admin', 'staff', 'regional_admin'], true)) {
fail('Staff access required.', 403);
}
}
/** Operational users handle cinema-day work. Manager admin is allowed as a fallback. */
function requireOperationalAdmin(): void {
requireAuth();
$role = $_SESSION['role'] ?? '';
if (!in_array($role, ['admin', 'staff', 'regional_admin'], true)) {
fail('Admin, regional, or staff access required.', 403);
}
}
function isRegionalAdmin(): bool {
return ($_SESSION['role'] ?? '') === 'regional_admin';
}
/** All governorate ids the current admin/staff account covers. */
function regionalAdminGovernorateIds(): array {
$ids = $_SESSION['governorate_ids'] ?? [];
if (!$ids && !empty($_SESSION['governorate_id'])) {
$ids = [(int)$_SESSION['governorate_id']];
}
return array_values(array_unique(array_map('intval', array_filter((array)$ids))));
}
/** Primary (first) region — kept for code paths that still expect one id. */
function regionalAdminGovernorateId(): int {
$ids = regionalAdminGovernorateIds();
if (isRegionalAdmin() && !$ids) {
fail('Regional admin account is missing an assigned region.', 403);
}
return $ids[0] ?? 0;
}
function enforceRegionalGovernorateAccess(int $governorateId): void {
if (isRegionalAdmin() && !in_array($governorateId, regionalAdminGovernorateIds(), true)) {
fail('This record belongs to another region.', 403);
}
}
function regionalScopeClause(string $cinemaAlias = 'c', string $prefix = 'WHERE'): array {
if (!isRegionalAdmin()) {
return ['', []];
}
$ids = regionalAdminGovernorateIds();
if (!$ids) {
fail('Regional admin account is missing an assigned region.', 403);
}
$placeholders = implode(',', array_fill(0, count($ids), '?'));
return [$prefix . " {$cinemaAlias}.governorate_id IN ($placeholders)", $ids];
}
function addSqlCondition(string $whereSql, string $condition): string {
return $whereSql ? ($whereSql . " AND " . $condition) : ("WHERE " . $condition);
}
function adminBookingRow(PDO $pdo, int $bookingId): array {
$stmt = $pdo->prepare("
SELECT b.*, c.governorate_id
FROM bookings b
JOIN showtimes s ON b.showtime_id = s.id
JOIN halls h ON s.hall_id = h.id
JOIN cinemas c ON h.cinema_id = c.id
WHERE b.id = ?
LIMIT 1
");
$stmt->execute([$bookingId]);
$booking = $stmt->fetch();
if (!$booking) {
fail('Booking not found.', 404);
}
enforceRegionalGovernorateAccess((int)$booking['governorate_id']);
return $booking;
}
/**
* requireCsrf($data)
* Verifies the csrf_token sent in a POST body matches the one
* stored in $_SESSION. Uses hash_equals to prevent timing attacks.
* Call this at the start of every state-changing POST action.
*/
function requireCsrf(array $data): void {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
$sent = $data['csrf_token'] ?? '';
$real = $_SESSION['csrf_token'] ?? '';
if (!$sent || !$real || !hash_equals($real, $sent)) {
fail('Invalid CSRF token. Refresh the page and try again.', 403);
}
}
/** Escape HTML to prevent XSS when inserting user data. */
function h(string $s): string {
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
/** Convert a numeric row + seat number into a human-readable label (A1, B12...). */
function seatLabel(int $row, int $number): string {
return chr(64 + $row) . $number;
}
/** Create a short ticket verification code that is safe to put inside a QR code. */
function makeTicketCode(int $bookingId): string {
// Every reserved ticket must have its own QR identity.
// The booking id links the code to one reservation, the date helps humans read it,
// and 8 random bytes make the code different even when many tickets are made quickly.
return 'CMX-' . date('Ymd') . '-' . $bookingId . '-' . strtoupper(bin2hex(random_bytes(8)));
}
/** Create a different ticket code for every individual reserved seat. */
function makeSeatTicketCode(int $bookingId, int $row, int $number): string {
$seat = seatLabel($row, $number);
return 'CMX-SEAT-' . date('Ymd') . '-' . $bookingId . '-' . $seat . '-' . strtoupper(bin2hex(random_bytes(6)));
}
/** Build the QR payload for one individual seat ticket. */
function makeSeatQrText(int $bookingId, string $seatCode, string $seatLabel, ?string $paymentReference = ''): string {
return 'CINEMAX|BOOKING=' . $bookingId . '|SEAT=' . $seatLabel . '|CODE=' . $seatCode . '|REF=' . ($paymentReference ?? '');
}
/** Return database failures as generic messages while preserving intentional validation errors. */
function failThrowable(Throwable $e, string $fallback = 'Request failed.'): void {
if ($e instanceof PDOException) {
fail('Database error.');
}
fail($e->getMessage() ?: $fallback);
}
/** Enforce database-friendly text lengths before inserts/updates. */
function requireMaxLength(string $value, int $max, string $label): void {
if (mb_strlen($value, 'UTF-8') > $max) {
fail("$label is too long. Maximum $max characters.");
}
}
/** Lightweight session throttle for public forms. */
function throttleSessionAction(string $key, int $seconds): void {
$now = time();
$_SESSION['throttle'] = $_SESSION['throttle'] ?? [];
$last = (int)($_SESSION['throttle'][$key] ?? 0);
if ($last && ($now - $last) < $seconds) {
fail('Please wait a moment before sending another request.', 429);
}
$_SESSION['throttle'][$key] = $now;
}
/** Limit repeated password-reset code guesses in the current browser session. */
function throttlePasswordResetCodeAttempt(string $email): void {
$now = time();
$key = 'reset_code:' . sha1(strtolower($email));
$_SESSION['reset_code_attempts'] = $_SESSION['reset_code_attempts'] ?? [];
$entry = $_SESSION['reset_code_attempts'][$key] ?? ['count' => 0, 'start' => $now];
if (($now - (int)$entry['start']) > 10 * 60) {
$entry = ['count' => 0, 'start' => $now];
}
if ((int)$entry['count'] >= 5) {
fail('Too many incorrect reset-code attempts. Request a new code and try again later.', 429);
}
$entry['count'] = (int)$entry['count'] + 1;
$_SESSION['reset_code_attempts'][$key] = $entry;
}
function clearPasswordResetCodeAttempts(string $email): void {
$key = 'reset_code:' . sha1(strtolower($email));
unset($_SESSION['reset_code_attempts'][$key]);
}
/** Store an in-app notification if the notifications table exists. */
function addNotification(PDO $pdo, int $userId, string $title, string $message): void {
try {
$stmt = $pdo->prepare("INSERT INTO notifications (user_id, title, message) VALUES (?, ?, ?)");
$stmt->execute([$userId, $title, $message]);
} catch (Throwable $e) {
// Notifications are helpful, but they must never break booking/payment.
}
}
/** Return true if a nullable table column exists. Used only for graceful migration compatibility. */
function columnExists(PDO $pdo, string $table, string $column): bool {
try {
$stmt = $pdo->prepare("
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?
");
$stmt->execute([$table, $column]);
return (int)$stmt->fetchColumn() > 0;
} catch (Throwable $e) { return false; }
}
/** Return true if a table exists. Used for migration-friendly optional features. */
function tableExists(PDO $pdo, string $table): bool {
try {
$stmt = $pdo->prepare("
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
");
$stmt->execute([$table]);
return (int)$stmt->fetchColumn() > 0;
} catch (Throwable $e) { return false; }
}
/** Final schema uses support_messages; older local installs may still have support_tickets. */
function supportMessagesTable(PDO $pdo): string {
return tableExists($pdo, 'support_messages') ? 'support_messages' : 'support_tickets';
}
function ensurePasswordResetAttemptColumns(PDO $pdo): void {
try {
if (!tableExists($pdo, 'password_reset_codes')) return;
if (!columnExists($pdo, 'password_reset_codes', 'failed_attempts')) {
$pdo->exec("ALTER TABLE password_reset_codes ADD COLUMN failed_attempts TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER used_at");
}
if (!columnExists($pdo, 'password_reset_codes', 'locked_at')) {
$pdo->exec("ALTER TABLE password_reset_codes ADD COLUMN locked_at DATETIME NULL AFTER failed_attempts");
}
} catch (Throwable $e) {
// Existing installs without ALTER privileges still have session throttling.
}
}
/** Delete expired seat holds and holds that became booked. */
function cleanupSeatLocks(PDO $pdo, ?int $showtimeId = null): void {
if (!tableExists($pdo, 'seat_locks')) {
return;
}
try {
if ($showtimeId) {
$expired = $pdo->prepare("DELETE FROM seat_locks WHERE showtime_id = ? AND expires_at < NOW()");
$expired->execute([$showtimeId]);
$booked = $pdo->prepare("
DELETE sl
FROM seat_locks sl
JOIN booking_seats bs
ON bs.showtime_id = sl.showtime_id
AND bs.seat_row = sl.seat_row
AND bs.seat_number = sl.seat_number
JOIN bookings b
ON b.id = bs.booking_id
AND b.status = 'confirmed'
WHERE sl.showtime_id = ?
");
$booked->execute([$showtimeId]);
} else {
$pdo->exec("DELETE FROM seat_locks WHERE expires_at < NOW()");
$pdo->exec("
DELETE sl
FROM seat_locks sl
JOIN booking_seats bs
ON bs.showtime_id = sl.showtime_id
AND bs.seat_row = sl.seat_row
AND bs.seat_number = sl.seat_number
JOIN bookings b
ON b.id = bs.booking_id
AND b.status = 'confirmed'
");
}
} catch (Throwable $e) {
// Locks are temporary; cleanup must never break the main action.
}
}
/** Validate and return the support region chosen by the customer. */
function requireSupportGovernorateId(PDO $pdo, array $data): int {
$govId = (int)($data['governorate_id'] ?? 0);
if (!$govId) {
fail('Choose the region that should receive this support request.');
}
$stmt = $pdo->prepare("SELECT id FROM governorates WHERE id = ? LIMIT 1");
$stmt->execute([$govId]);
if (!$stmt->fetchColumn()) {
fail('Selected support region was not found.');
}
return $govId;
}
/** Return a support ticket and enforce regional admin scope. */
function adminSupportTicketRow(PDO $pdo, int $ticketId): array {
$supportTable = supportMessagesTable($pdo);
$stmt = $pdo->prepare("
SELECT t.*, g.name_en AS governorate_name
FROM $supportTable t
LEFT JOIN governorates g ON t.governorate_id = g.id
WHERE t.id = ?
LIMIT 1
");
$stmt->execute([$ticketId]);
$ticket = $stmt->fetch();
if (!$ticket) {
fail('Support ticket not found.', 404);
}
if (isRegionalAdmin()) {
$ticketGovId = (int)($ticket['governorate_id'] ?? 0);
if (!$ticketGovId || !in_array($ticketGovId, regionalAdminGovernorateIds(), true)) {
fail('This support ticket belongs to another region.', 403);
}
}
return $ticket;
}
/** Keep an audit row when a seat is cancelled, while booking_seats stays active-only. */
function archiveCancelledBookingSeat(PDO $pdo, int $bookingId, int $showtimeId, ?int $userId, int $row, int $number, float $refundAmount, string $reason): void {
if (!tableExists($pdo, 'cancelled_booking_seats')) {
return;
}
try {
$seatTicketCode = null;
$seatTicketStatus = 'cancelled';
if (columnExists($pdo, 'booking_seats', 'seat_ticket_code')) {
$codeStmt = $pdo->prepare("
SELECT seat_ticket_code, seat_ticket_status
FROM booking_seats
WHERE booking_id = ? AND seat_row = ? AND seat_number = ?
LIMIT 1
");
$codeStmt->execute([$bookingId, $row, $number]);
$codeRow = $codeStmt->fetch();
if ($codeRow) {
$seatTicketCode = $codeRow['seat_ticket_code'] ?? null;
$seatTicketStatus = 'cancelled';
}
}
if (columnExists($pdo, 'cancelled_booking_seats', 'seat_ticket_code')) {
$stmt = $pdo->prepare("
INSERT INTO cancelled_booking_seats
(booking_id, showtime_id, seat_row, seat_number, seat_ticket_code, seat_ticket_status, cancelled_by_user_id, refund_amount, reason)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([$bookingId, $showtimeId, $row, $number, $seatTicketCode, $seatTicketStatus, $userId, $refundAmount, $reason]);
} else {
$stmt = $pdo->prepare("
INSERT INTO cancelled_booking_seats
(booking_id, showtime_id, seat_row, seat_number, cancelled_by_user_id, refund_amount, reason)
VALUES (?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([$bookingId, $showtimeId, $row, $number, $userId, $refundAmount, $reason]);
}
} catch (Throwable $e) {
// Cancellation itself must not fail just because the audit table is unavailable.
}
}
/**
* Load active booking seats and split them into refundable/cancellable vs used.
* A used seat QR must never be refunded or deleted as an unused seat.
*/
function refundableSeatMaps(PDO $pdo, int $bookingId, bool $forUpdate = false): array {
$statusSelect = columnExists($pdo, 'booking_seats', 'seat_ticket_status')
? 'seat_ticket_status'
: "'valid' AS seat_ticket_status";
$sql = "
SELECT seat_row, seat_number, $statusSelect
FROM booking_seats
WHERE booking_id = ?
ORDER BY seat_row, seat_number
";
if ($forUpdate) $sql .= " FOR UPDATE";
$stmt = $pdo->prepare($sql);
$stmt->execute([$bookingId]);
$rows = $stmt->fetchAll();
if (!$rows) {
throw new Exception('No active seats found for this booking.');
}
$refundable = [];
$used = [];
foreach ($rows as $seat) {
$row = (int)$seat['seat_row'];
$number = (int)$seat['seat_number'];
$key = "$row:$number";
if (($seat['seat_ticket_status'] ?? 'valid') === 'used') {
$used[$key] = true;
} else {
$refundable[$key] = true;
}
}
return [$refundable, $used, $rows];
}
function cleanRequestedRefundSeats(array $seats, array $refundable, array $used, string $missingMessage): array {
$cleanSeats = [];
foreach ($seats as $seat) {
$row = (int)($seat['row'] ?? 0);
$number = (int)($seat['number'] ?? 0);
$key = "$row:$number";
if ($row < 1 || $number < 1) {
throw new Exception($missingMessage);
}
if (!empty($used[$key])) {
throw new Exception('Seat ' . seatLabel($row, $number) . ' has already been used and cannot be refunded or cancelled.');
}
if (empty($refundable[$key])) {
throw new Exception($missingMessage);
}
$cleanSeats[$key] = ['row' => $row, 'number' => $number];
}
if (!$cleanSeats) {
throw new Exception('Choose at least one unused seat.');
}
return $cleanSeats;
}
/** Auto-cancel stale unpaid cash reservations so they cannot hold seats forever. */
function expireStaleCashBookings(PDO $pdo): void {
try {
if (!tableExists($pdo, 'bookings') || !tableExists($pdo, 'booking_seats')) return;
$stmt = $pdo->prepare("
SELECT b.id, b.user_id, b.showtime_id
FROM bookings b
WHERE b.status = 'confirmed'
AND b.payment_status = 'pending'
AND b.payment_method = 'cash'
AND b.created_at < (NOW() - INTERVAL " . PENDING_CASH_EXPIRY_MINUTES . " MINUTE)
LIMIT 50
");
$stmt->execute();
$bookings = $stmt->fetchAll();
if (!$bookings) return;
foreach ($bookings as $booking) {
$bookingId = (int)$booking['id'];
$pdo->beginTransaction();
$lock = $pdo->prepare("SELECT id FROM bookings WHERE id = ? AND status='confirmed' AND payment_status='pending' AND payment_method='cash' FOR UPDATE");
$lock->execute([$bookingId]);
if (!$lock->fetch()) {
$pdo->rollBack();
continue;
}
$seatStmt = $pdo->prepare("SELECT seat_row, seat_number FROM booking_seats WHERE booking_id = ? ORDER BY seat_row, seat_number");
$seatStmt->execute([$bookingId]);
foreach ($seatStmt->fetchAll() as $seat) {
archiveCancelledBookingSeat(
$pdo,
$bookingId,
(int)$booking['showtime_id'],
null,
(int)$seat['seat_row'],
(int)$seat['seat_number'],
0.00,
'cash_booking_expired'
);
}
$pdo->prepare("DELETE FROM booking_seats WHERE booking_id = ?")->execute([$bookingId]);
$pdo->prepare("
UPDATE bookings
SET status='cancelled', payment_status='failed', ticket_status='cancelled', total_price=0
WHERE id=?
")->execute([$bookingId]);
if (!empty($booking['user_id'])) {
addNotification($pdo, (int)$booking['user_id'], 'Cash reservation expired', "Booking #$bookingId was cancelled because the cash payment was not verified within " . PENDING_CASH_EXPIRY_MINUTES . " minutes.");
}
$pdo->commit();
}
} catch (Throwable $e) {
if ($pdo->inTransaction()) $pdo->rollBack();
// Expiry is best-effort; it must not break normal browsing.
}
}
/** Core transaction used by both legacy book and new create_payment. */
function createBookingTransaction(PDO $pdo, array $data, string $paymentMethod): array {
$stId = (int)($data['showtime_id'] ?? 0);
$seats = $data['seats'] ?? [];
$movieTitle = trim($data['movie_title'] ?? '');
$moviePoster = trim($data['movie_poster'] ?? '');
if (!$stId) throw new Exception('showtime_id required.');
if (empty($seats)) throw new Exception('Select at least one seat.');
if (!is_array($seats)) throw new Exception('Invalid seat data.');
if (!$movieTitle) throw new Exception('movie_title required.');
$allowedMethods = ['cash', 'simulated_card', 'simulated_wallet'];
if (!in_array($paymentMethod, $allowedMethods, true)) {
throw new Exception('Invalid payment method.');
}
$pdo->beginTransaction();
try {
cleanupSeatLocks($pdo, $stId);
$st = $pdo->prepare("SELECT s.*, h.total_rows, h.seats_per_row FROM showtimes s JOIN halls h ON s.hall_id = h.id WHERE s.id = ? AND s.show_datetime > NOW() FOR UPDATE");
$st->execute([$stId]);
$show = $st->fetch();
if (!$show) throw new Exception('Showtime not found or already passed.');
if ($paymentMethod === 'cash' && strtotime($show['show_datetime']) > time() + 86400) {
throw new Exception('Cash at Cinema is only available during the final 24 hours before the screening. Please choose simulated card/wallet or a nearer showtime.');
}
$hasShowtimeSeatCol = columnExists($pdo, 'booking_seats', 'showtime_id');
// Check every seat is valid and still free.
$checkBooked = $pdo->prepare("\n SELECT 1 FROM booking_seats bs\n JOIN bookings b ON bs.booking_id = b.id\n WHERE b.showtime_id = ? AND b.status = 'confirmed'\n AND bs.seat_row = ? AND bs.seat_number = ?\n LIMIT 1\n ");
$checkLock = $pdo->prepare("\n SELECT user_id FROM seat_locks\n WHERE showtime_id = ? AND seat_row = ? AND seat_number = ? AND expires_at > NOW()\n LIMIT 1\n ");
$cleanSeats = [];
foreach ($seats as $seat) {
$r = (int)($seat['row'] ?? 0);
$n = (int)($seat['number'] ?? 0);
if ($r < 1 || $n < 1 || $r > (int)$show['total_rows'] || $n > (int)$show['seats_per_row']) {
throw new Exception('Invalid seat coordinates.');
}
$checkBooked->execute([$stId, $r, $n]);
if ($checkBooked->fetch()) throw new Exception('Seat ' . seatLabel($r, $n) . ' was just taken.');
// Allow the current user to finish seats they already selected; block seats selected/booked by other users.
$checkLock->execute([$stId, $r, $n]);
$lock = $checkLock->fetch();
if ($lock && (int)$lock['user_id'] !== (int)$_SESSION['user_id']) {
throw new Exception('Seat ' . seatLabel($r, $n) . ' is already reserved by another user.');
}
$cleanSeats[] = ['row' => $r, 'number' => $n];
}
$total = round(((float)$show['price']) * count($cleanSeats), 2);
$paymentStatus = $paymentMethod === 'cash' ? 'pending' : 'paid';
$paymentRef = strtoupper($paymentMethod) . '-' . date('YmdHis') . '-' . random_int(1000, 9999);
$paidAt = $paymentStatus === 'paid' ? date('Y-m-d H:i:s') : null;
$cashExpiresAt = $paymentMethod === 'cash'
? date('Y-m-d H:i:s', time() + PENDING_CASH_EXPIRY_MINUTES * 60)
: null;
$ins = $pdo->prepare("\n INSERT INTO bookings\n (user_id, showtime_id, movie_title, movie_poster, total_price, status, payment_status, payment_method, payment_reference, paid_at, ticket_status)\n VALUES (?, ?, ?, ?, ?, 'confirmed', ?, ?, ?, ?, 'valid')\n ");
$ins->execute([$_SESSION['user_id'], $stId, $movieTitle, $moviePoster ?: null, $total, $paymentStatus, $paymentMethod, $paymentRef, $paidAt]);
$bookingId = (int)$pdo->lastInsertId();
$ticketCode = makeTicketCode($bookingId);
$updTicket = $pdo->prepare("UPDATE bookings SET ticket_code = ? WHERE id = ?");
$updTicket->execute([$ticketCode, $bookingId]);
$seatTickets = [];
$hasSeatTicketCol = columnExists($pdo, 'booking_seats', 'seat_ticket_code');
if ($hasShowtimeSeatCol && $hasSeatTicketCol) {
$seatIns = $pdo->prepare("INSERT INTO booking_seats (booking_id, showtime_id, seat_row, seat_number, seat_ticket_code) VALUES (?, ?, ?, ?, ?)");
foreach ($cleanSeats as $seat) {
$seatCode = makeSeatTicketCode($bookingId, (int)$seat['row'], (int)$seat['number']);
$seatLabel = seatLabel((int)$seat['row'], (int)$seat['number']);
$seatIns->execute([$bookingId, $stId, $seat['row'], $seat['number'], $seatCode]);
$seatTickets[] = ['row'=>(int)$seat['row'], 'number'=>(int)$seat['number'], 'seat'=>$seatLabel, 'ticket_code'=>$seatCode, 'qr_text'=>makeSeatQrText($bookingId, $seatCode, $seatLabel, $paymentRef)];
}
} elseif ($hasShowtimeSeatCol) {
$seatIns = $pdo->prepare("INSERT INTO booking_seats (booking_id, showtime_id, seat_row, seat_number) VALUES (?, ?, ?, ?)");
foreach ($cleanSeats as $seat) $seatIns->execute([$bookingId, $stId, $seat['row'], $seat['number']]);
} else {
$seatIns = $pdo->prepare("INSERT INTO booking_seats (booking_id, seat_row, seat_number) VALUES (?, ?, ?)");
foreach ($cleanSeats as $seat) $seatIns->execute([$bookingId, $seat['row'], $seat['number']]);
}
// Clear user's temporary seat holds for these seats after the booking is saved.
$delLock = $pdo->prepare("DELETE FROM seat_locks WHERE showtime_id = ? AND seat_row = ? AND seat_number = ? AND user_id = ?");
foreach ($cleanSeats as $seat) $delLock->execute([$stId, $seat['row'], $seat['number'], $_SESSION['user_id']]);
addNotification($pdo, (int)$_SESSION['user_id'], 'Booking confirmed', "Your booking #$bookingId for $movieTitle has been created.");
$pdo->commit();
return [
'id' => $bookingId,
'booking_id' => $bookingId,
'total_price' => $total,
'payment_status' => $paymentStatus,
'payment_method' => $paymentMethod,
'payment_reference' => $paymentRef,
'ticket_code' => $ticketCode,
'ticket_status' => 'valid',
'show_datetime' => $show['show_datetime'],
'cash_payment_deadline' => $cashExpiresAt ?: $show['show_datetime'],
'cash_payment_expires_minutes' => $paymentMethod === 'cash' ? PENDING_CASH_EXPIRY_MINUTES : null,
'qr_text' => "CINEMAX|BOOKING=$bookingId|CODE=$ticketCode",
'seat_tickets' => $seatTickets ?? [],
];
} catch (Throwable $e) {
if ($pdo->inTransaction()) $pdo->rollBack();
throw $e;
}
}
expireStaleCashBookings($pdo);
// ── Router ────────────────────────────────────────────────────
switch ($action) {
/* ============================================================
GOVERNORATES
Returns all Egypt governorates that have at least one cinema.
GET api.php?action=governorates
============================================================ */
case 'governorates':
try {
$stmt = $pdo->query("
SELECT g.id, g.name_en, g.name_ar, g.slug,
COUNT(c.id) AS cinema_count
FROM governorates g
LEFT JOIN cinemas c ON c.governorate_id = g.id
GROUP BY g.id
HAVING cinema_count > 0
ORDER BY g.name_en ASC
");
ok(['governorates' => $stmt->fetchAll()]);
} catch (PDOException $e) { fail('Database error.'); }
break;
/* ============================================================
CINEMAS
Returns all cinemas, optionally filtered by governorate.
GET api.php?action=cinemas[&gov_id=1]
============================================================ */
case 'cinemas':
$govId = (int)($_GET['gov_id'] ?? 0);
try {
$sql = "
SELECT c.*, g.name_en AS gov_name,
COUNT(h.id) AS hall_count
FROM cinemas c
JOIN governorates g ON c.governorate_id = g.id
LEFT JOIN halls h ON h.cinema_id = c.id
";
$params = [];
if ($govId) { $sql .= " WHERE c.governorate_id = ?"; $params[] = $govId; }
$sql .= " GROUP BY c.id ORDER BY g.name_en ASC, c.name ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
ok(['cinemas' => $stmt->fetchAll()]);
} catch (PDOException $e) { fail('Database error.'); }
break;