newClientSubmit.php 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. <?php
  2. /**
  3. * controllers/newClientSubmit.php
  4. *
  5. * Handle new client creation from modal form.
  6. */
  7. // Start session if not already started
  8. if (session_status() === PHP_SESSION_NONE) {
  9. session_start();
  10. }
  11. // Include dependencies
  12. require_once __DIR__ . '/../config/database.php';
  13. require_once __DIR__ . '/../lib/auth.php';
  14. require_once __DIR__ . '/../lib/validation.php';
  15. require_once __DIR__ . '/../lib/csrf.php';
  16. // Check authentication
  17. if (!isLoggedIn()) {
  18. http_response_code(403);
  19. die(json_encode(['success' => false, 'message' => 'Authentication required']));
  20. }
  21. // Check CSRF token
  22. if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
  23. http_response_code(403);
  24. die(json_encode(['success' => false, 'message' => 'CSRF token validation failed']));
  25. }
  26. // Only process POST requests
  27. if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['NCsubmit'])) {
  28. http_response_code(405);
  29. die(json_encode(['success' => false, 'message' => 'Method not allowed']));
  30. }
  31. header('Content-Type: application/json');
  32. try {
  33. // Validate and sanitize input data
  34. $input = validateNewClientData($_POST);
  35. // Check if client with this email already exists for this user
  36. if (clientEmailExists($input['email'], $_SESSION['user_id'])) {
  37. throw new ValidationException('A client with this email address already exists');
  38. }
  39. // Insert new client
  40. $clientId = insertNewClient($input);
  41. // Return success response with client data for dropdown update
  42. echo json_encode([
  43. 'success' => true,
  44. 'message' => 'Client added successfully',
  45. 'client' => [
  46. 'id' => $clientId,
  47. 'name' => $input['name'],
  48. 'company' => $input['company'],
  49. 'email' => $input['email'],
  50. 'address' => $input['address'] . ', ' . $input['state']
  51. ]
  52. ]);
  53. } catch (ValidationException $e) {
  54. http_response_code(400);
  55. echo json_encode(['success' => false, 'message' => $e->getMessage()]);
  56. } catch (PDOException $e) {
  57. error_log("Database error in new client creation: " . $e->getMessage());
  58. http_response_code(500);
  59. echo json_encode(['success' => false, 'message' => 'Database error occurred. Please try again later.']);
  60. } catch (Exception $e) {
  61. error_log("Unexpected error in new client creation: " . $e->getMessage());
  62. http_response_code(500);
  63. echo json_encode(['success' => false, 'message' => 'An unexpected error occurred. Please try again later.']);
  64. }
  65. /**
  66. * Validate and sanitize new client form data
  67. */
  68. function validateNewClientData(array $post): array
  69. {
  70. $validated = [];
  71. // Required fields
  72. $validated['name'] = sanitizeString($post['Nname'] ?? '', 100);
  73. if (empty($validated['name'])) {
  74. throw new ValidationException('Client name is required');
  75. }
  76. $validated['email'] = filter_var($post['Nemail'] ?? '', FILTER_VALIDATE_EMAIL);
  77. if (!$validated['email']) {
  78. throw new ValidationException('Valid email address is required');
  79. }
  80. $validated['address'] = sanitizeString($post['Naddress'] ?? '', 255);
  81. if (empty($validated['address'])) {
  82. throw new ValidationException('Address is required');
  83. }
  84. $validated['state'] = sanitizeString($post['Nstate'] ?? '', 255);
  85. if (empty($validated['state'])) {
  86. throw new ValidationException('Town/State/Postcode is required');
  87. }
  88. // Optional fields
  89. $validated['company'] = sanitizeString($post['Ncompany'] ?? '', 100);
  90. $validated['mobile'] = sanitizeString($post['Nmobile'] ?? '', 20);
  91. return $validated;
  92. }
  93. /**
  94. * Check if client email already exists for this user
  95. */
  96. function clientEmailExists(string $email, int $userId): bool
  97. {
  98. global $pdo;
  99. $stmt = $pdo->prepare("SELECT id FROM client_records WHERE email = ? AND modx_user_id = ?");
  100. $stmt->execute([$email, $userId]);
  101. return $stmt->fetch() !== false;
  102. }
  103. /**
  104. * Insert new client into database
  105. */
  106. function insertNewClient(array $data): int
  107. {
  108. global $pdo;
  109. $sql = "INSERT INTO client_records (
  110. modx_user_id,
  111. modx_user_attributes,
  112. client,
  113. company,
  114. email,
  115. address,
  116. mobile,
  117. created_at
  118. ) VALUES (
  119. :modx_user_id,
  120. :modx_user_attributes,
  121. :client,
  122. :company,
  123. :email,
  124. :address,
  125. :mobile,
  126. NOW()
  127. )";
  128. $stmt = $pdo->prepare($sql);
  129. $stmt->execute([
  130. 'modx_user_id' => $_SESSION['user_id'],
  131. 'modx_user_attributes' => $_SESSION['user_id'],
  132. 'client' => $data['name'],
  133. 'company' => $data['company'],
  134. 'email' => $data['email'],
  135. 'address' => $data['address'] . ', ' . $data['state'],
  136. 'mobile' => $data['mobile']
  137. ]);
  138. return $pdo->lastInsertId();
  139. }
  140. ?>