'API key is not configured.']); exit; } $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; if (strpos($authHeader, 'Bearer ') !== 0) { http_response_code(401); echo json_encode(['error' => 'Authorization header missing or invalid.']); exit; } $token = substr($authHeader, 7); if ($token !== $apiKey) { http_response_code(401); echo json_encode(['error' => 'Invalid API key.']); exit; } log_api_request('calendar-events'); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = json_decode(file_get_contents('php://input'), true); // Basic validation $required_fields = ['google_event_id', 'start_datetime', 'end_datetime']; foreach ($required_fields as $field) { if (empty($data[$field])) { http_response_code(400); echo json_encode(['error' => "Missing required field: $field"]); exit; } } try { $pdo = db(); $stmt = $pdo->prepare( "INSERT INTO calendar_events (google_event_id, google_calendar_id, event_title, event_description, event_location, start_datetime, end_datetime, customer_name, customer_phone, service_type, assigned_technician, event_status, booking_id) VALUES (:google_event_id, :google_calendar_id, :event_title, :event_description, :event_location, :start_datetime, :end_datetime, :customer_name, :customer_phone, :service_type, :assigned_technician, :event_status, :booking_id)" ); $stmt->execute([ ':google_event_id' => $data['google_event_id'], ':google_calendar_id' => $data['google_calendar_id'] ?? null, ':event_title' => $data['event_title'] ?? null, ':event_description' => $data['event_description'] ?? null, ':event_location' => $data['event_location'] ?? null, ':start_datetime' => $data['start_datetime'], ':end_datetime' => $data['end_datetime'], ':customer_name' => $data['customer_name'] ?? null, ':customer_phone' => $data['customer_phone'] ?? null, ':service_type' => $data['service_type'] ?? null, ':assigned_technician' => $data['assigned_technician'] ?? null, ':event_status' => $data['event_status'] ?? null, ':booking_id' => $data['booking_id'] ?? null, ]); http_response_code(201); echo json_encode(['success' => true, 'message' => 'Calendar event created successfully.']); } catch (PDOException $e) { if ($e->getCode() == 23000) { // Duplicate entry http_response_code(409); echo json_encode(['error' => 'Duplicate google_event_id.']); } else { error_log("DB Error: " . $e->getMessage()); http_response_code(500); echo json_encode(['error' => 'Database error.']); } } } else { http_response_code(405); // Method Not Allowed echo json_encode(['error' => 'Only POST method is accepted.']); }