<?php
// File: web/mobile/Flutter/register_training.php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Enable CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Start a database transaction
$pdo->beginTransaction();
try {
// Validate required fields
$requiredFields = ['training_id', 'user_id', 'full_name', 'mobile_number', 'payment_status'];
foreach ($requiredFields as $field) {
if (!isset($_POST[$field]) || empty($_POST[$field])) {
throw new Exception("Missing required field: $field");
}
}
// Sanitize and prepare input data
$trainingId = intval($_POST['training_id']);
$userId = intval($_POST['user_id']);
$fullName = $_POST['full_name'];
$mobileNumber = $_POST['mobile_number'];
$paymentStatus = $_POST['payment_status'];
$razorpayPaymentId = $_POST['razorpay_payment_id'] ?? null;
// Check if user is already registered for this training
$checkRegistrationStmt = $pdo->prepare("
SELECT COUNT(*) as registration_count
FROM training_participants
WHERE training_id = :training_id AND user_id = :user_id
");
$checkRegistrationStmt->execute([
'training_id' => $trainingId,
'user_id' => $userId
]);
$registrationCheck = $checkRegistrationStmt->fetch(PDO::FETCH_ASSOC);
if ($registrationCheck['registration_count'] > 0) {
throw new Exception("You are already registered for this training");
}
// Prepare and execute registration insert
$insertStmt = $pdo->prepare("
INSERT INTO training_participants
(training_id, user_id, full_name, mobile_number, registration_date, payment_status, razorpay_payment_id)
VALUES
(:training_id, :user_id, :full_name, :mobile_number, NOW(), :payment_status, :razorpay_payment_id)
");
$insertStmt->execute([
'training_id' => $trainingId,
'user_id' => $userId,
'full_name' => $fullName,
'mobile_number' => $mobileNumber,
'payment_status' => $paymentStatus,
'razorpay_payment_id' => $razorpayPaymentId
]);
// Commit the transaction
$pdo->commit();
// Prepare success response
$response = [
'status' => 'success',
'message' => 'Training registration successful',
'registrationDetails' => [
'trainingId' => $trainingId,
'userId' => $userId,
'fullName' => $fullName,
'paymentStatus' => $paymentStatus
]
];
echo json_encode($response);
} catch (Exception $e) {
// Rollback the transaction in case of error
$pdo->rollBack();
// Prepare error response
$response = [
'status' => 'error',
'message' => $e->getMessage()
];
echo json_encode($response);
exit;
}
} else {
// Method not allowed
http_response_code(405);
echo json_encode([
'status' => 'error',
'message' => 'Method Not Allowed'
]);
}
?>