<?php

// A simplified (yes, really!) version of the add action in the membership controller

protected function _actionAdd(KCommandContext $context)
{
    // Start transaction
    $db = KService::get('koowa:database.adapter.mysqli');
    $db->execute('START TRANSACTION');
    
    // Add the member 
    $member     = KService::get('com://site/studio.controller.member')->add($data['member']);
    if (!($member instanceof KDatabaseRowInterface)) {
        $errors = true;
        // Member add failed, but we need the member object for age calculations when validation parent and membership details
        $member = KService::get('com://site/studio.model.members')->getItem()->setData($data['member']);
    } else {
        $data['parent']['child_id']      = $member->id;
        $data['membership']['member_id'] = $member->id;
    }

    // Add the parent, but only if the member is a minor
    if (!$member->isAdult()) {
        $parent = KService::get('com://site/studio.controller.parent')->add($data['parent']);
        if (!($parent instanceof KDatabaseRowInterface)) {
            $errors  = true;
        }
    }

    // Add the membership
    $membership = KService::get('com://site/studio.controller.membership')->add($membership_data); 
    if (!($membership instanceof KDatabaseRowInterface)) {
        $errors = true;
    }

    // Add the membership details
    $errors = $this->_addMembershipDetails($membership, $member); // Separate function deals with this

    // Finish transaction
    if ($errors) {
        $db->execute('ROLLBACK');
        $context->caller->setRedirect($this->_getReferrer($context), 'Validation errors', 'error' );
    } else {
        $db->execute('COMMIT');
        JFactory::getApplication()->redirect('https://my.payment.provider.com/payment_form/abc123');
    }

    return $membership;
}