<?php

function fulcrm_shoppingcart_permission() {
  return array( 'administer fulcrm shoppingcart' => array( 'title' => t('Administer fulcrm shopping cart'),
                                                           'description' => t('Perform main installation/administration tasks for fulcrm shopping cart.'),
                                                           ),                          
                );
}

function fulcrm_shoppingcart_menu() {
    /*
    $items[ 'admin/config/services/fulcrm' ] = array( 'page callback' => 'system_admin_menu_block_page',
                                                      'file' => 'system.admin.inc',
                                                      'file path' => drupal_get_path('module', 'system'),
                                                      'title' => 'fulcrm',
                                                      'description' => 'Configuration integration with fulcrm.org.',
                                                      'position' => 'right',
                                                      'access callback' => 'user_access',
                                                      'access arguments' => array('access administration pages'),
                                                      );
   */
    $items[ 'admin/config/services/fulcrm/shoppingcart' ] = array( 'page callback' => 'fulcrm_shoppingcart_admin',
                                                                   'file' => 'fulcrm_shoppingcart.admin.inc',
                                                                   'title' => 'fulcrm Shopping Cart',
                                                                   'description' => 'Configure Shopping Cart for fulcrm.org.',
                                                                   'access callback' => 'user_access',
                                                                   'access arguments' => array('administer fulcrm shoppingcart'),
                                                                   );

    $items[ 'fulcrm/buy/%/%' ] = array( 'page callback' => 'fulcrm_shoppingcart_buy',
                                        'page arguments' => array(2,3),
                                        'type' => MENU_CALLBACK,
                                        'access callback' => 'user_access',
                                        'access arguments' => array('access content'),
                                        );
    $items[ 'fulcrm/cart/remove/%/%' ] = array( 'page callback' => 'fulcrm_shoppingcart_remove',
                                                'page arguments' => array(3,4),
                                                'type' => MENU_CALLBACK,
                                                'access callback' => 'user_access',
                                                'access arguments' => array('access content'),
                                                );
    $items[ 'fulcrm/cart' ] = array( 'page callback' => 'fulcrm_shoppingcart_cart',
                                     'type' => MENU_CALLBACK,
                                     'access callback' => 'user_access',
                                     'access arguments' => array('access content'),
                                     );
    $items[ 'fulcrm/checkout' ] = array( 'page callback' => 'fulcrm_shoppingcart_checkout',
                                         'type' => MENU_CALLBACK,
                                         'access callback' => 'user_access',
                                         'access arguments' => array('access content'),
                                         );
    $items[ 'fulcrm/checkout/success/%/%' ] = array( 'page callback' => 'fulcrm_shoppingcart_checkout_success',
                                                     'page arguments' => array(3,4),
                                                     'type' => MENU_CALLBACK,
                                                     'access callback' => 'user_access',
                                                     'access arguments' => array('access content'),
                                                     );
    $items[ 'fulcrm/checkout/failure/%/%' ] = array( 'page callback' => 'fulcrm_shoppingcart_checkout_failure',
                                                     'page arguments' => array(3,4),
                                                     'type' => MENU_CALLBACK,
                                                     'access callback' => 'user_access',
                                                     'access arguments' => array('access content'),
                                                     );

    return $items;
}

function fulcrm_shoppingcart_theme( $existing, $type, $theme, $path ) {
    return array( 'fulcrm_shoppingcart_cart' => array( 'variables' => array( 'shoppingcart' => null ), // data returned from fulcrm API
                                                       'template' => 'fulcrm_shoppingcart_cart',
                                                        ),
                  'fulcrm_shoppingcart_cart_items' => array( 'variables' => array( 'shoppingitems' => null ), // data returned from fulcrm API
                                                             'template' => 'fulcrm_shoppingcart_cart_items',
                                                             ),
                  'fulcrm_shoppingcart_cart_item' => array( 'variables' => array( 'shoppingitem' => null ), // data returned from fulcrm API
                                                            'template' => 'fulcrm_shoppingcart_cart_item',
                                                            ),
                  'fulcrm_shoppingcart_transaction_checkout' => array( 'variables' => array( 'transaction' => null ), // data returned from fulcrm API
                                                                       'template' => 'fulcrm_shoppingcart_transaction_checkout',
                                                                        ),
                  'fulcrm_shoppingcart_transaction_items' => array( 'variables' => array( 'items' => null ), // data returned from fulcrm API
                                                                    'template' => 'fulcrm_shoppingcart_transaction_items',
                                                                     ),
                  'fulcrm_shoppingcart_transaction_item' => array( 'variables' => array( 'item' => null ), // data returned from fulcrm API
                                                                   'template' => 'fulcrm_shoppingcart_transaction_item',
                                                                    ),
                  );
}

function fulcrm_shoppingcart_get_session_cart( $create = true ) {
    global $user;

    drupal_session_start();

    if ( array_key_exists( 'fulcrm_shoppingcart_id', $_SESSION ) ) {
        $api_data = fulcrm_apiv2_GET( 'shoppingcart/' . $_SESSION[ 'fulcrm_shoppingcart_id' ] . '/',
                                      $query = array( 'expand' => implode( ',', array( 'shoppingitems',
                                                                                       'shoppingitems.d',
                                                                                       'shoppingitems.content_object',
                                                                                       'shoppingitems.product' ) ) ) );
        if ( $api_data[ 'success' ] ) {
            if ( ( $api_data[ 'data' ][ 'completed' ] === null ) && ( $api_data[ 'data' ][ 'abandoned' ] === null ) ) {
                return $api_data[ 'data' ];
            }
        }
    }

    if ( $create ) {
        $person_url = null;
        if ( !user_is_anonymous() ) {
            $person_id = fulcrm_webhook_get_pk_for_entity_type( 'user', $user->uid, 'person' );

            if ( $person_id )
                $person_url = fulcrm_apiv2_make_url( 'person', $person_id );
        }

        $cart_data = array( 'person' => $person_url, 'd' => array( 'fulcrm_testing_data' => 'this is a test' ) );

        $api_data = fulcrm_apiv2_POST( 'shoppingcart/', $cart_data );
        if ( $api_data[ 'success' ] ) {
            $_SESSION[ 'fulcrm_shoppingcart_id' ] = $api_data[ 'data' ][ 'id' ];
            return $api_data[ 'data' ];
        }
    }
}

function fulcrm_shoppingcart_buy_url( $product_id ) {
    $hmac = fulcrm_crypto_object_id_hmac( 'product', $product_id );
    return url( 'fulcrm/buy/' . $product_id . '/' . $hmac );
}

function fulcrm_shoppingcart_remove_url( $shoppingitem_id ) {
    $hmac = fulcrm_crypto_object_id_hmac( 'shoppingitem', $shoppingitem_id );
    return url( 'fulcrm/cart/remove/' . $shoppingitem_id . '/' . $hmac );
}

function fulcrm_shoppingcart_buy_eventbookingtype_form_submit( $form, &$form_state ) {
    // $person_d = fulcrm_collection_form_values_to_d( 'person', $form_state[ 'values' ] );

    $product_id = $form_state[ 'fulcrm_shoppingcart' ][ 'product' ][ 'id' ];
    $eventbookingtype_id = $form_state[ 'fulcrm_shoppingcart' ][ 'eventbookingtype' ][ 'id' ];

    $person_id = NULL;
    $person_uuid = NULL;
    if ( array_key_exists( 'id', $form_state[ 'fulcrm_shoppingcart' ] ) )
        $person_id = $form_state[ 'fulcrm_shoppingcart' ][ 'person' ][ 'id' ];
    if ( array_key_exists( 'uuid', $form_state[ 'fulcrm_shoppingcart' ] ) )
        $person_uuid = $form_state[ 'fulcrm_shoppingcart' ][ 'person' ][ 'uuid' ];

    if ( array_key_exists( 'shoppingcart', $form_state[ 'fulcrm_shoppingcart' ] ) )
        $cart = $form_state[ 'fulcrm_shoppingcart' ][ 'shoppingcart' ];
    else
        $cart = fulcrm_shoppingcart_get_session_cart();

    if ( is_array( $cart ) ) {
        if ( $person_uuid ) {
            $api_data = fulcrm_apiv2_PATCH( $cart[ 'url' ], 
                                            array( 'd' => array( 'fulcrm' => array( 'transaction' => array( 'person' => $person_uuid,
                                                                                                            ),
                                                                                    'person' => array( $person_uuid => array() ),
                                                                                    ),
                                                                 ),
                                                   ),
                                            $query = array( 'expand' => 'd' ) );
        }

        foreach ( $form_state[ 'values' ][ 'ticket_for_persons' ] as $ticket_for_person ) {
            if ( $ticket_for_person === 'myself' ) {
                $person_uuid = $form_state[ 'fulcrm_shoppingcart' ][ 'person' ][ 'uuid' ];
                $person_name = $form_state[ 'fulcrm_shoppingcart' ][ 'person' ][ 'name' ];
            } else {
                $person_uuid = fulcrm_crypto_get_object_id_form_value( 'person.uuid', $ticket_for_person );
                if ( $person_uuid )
                    $person_name = $form_state[ 'fulcrm_shoppingcart' ][ 'persons' ][ $person_uuid ][ 'name' ];
            }

            $shoppingitem_name = ( $form_state[ 'fulcrm_shoppingcart' ][ 'product' ][ 'name' ] . ', ' . $person_name . "\r\n" .
                                   $form_state[ 'fulcrm_shoppingcart' ][ 'eventbookingtype' ][ 'name' ] . "\r\n" .
                                   $form_state[ 'fulcrm_shoppingcart' ][ 'eventbookingtype' ][ 'event' ][ 'name' ] );

            $eventslotbookings = array();
            if ( array_key_exists( 'eventbookingtypeslots', $form_state[ 'fulcrm_shoppingcart' ][ 'eventbookingtype' ] ) ) {
                foreach ( $form_state[ 'fulcrm_shoppingcart' ][ 'eventbookingtype' ][ 'eventbookingtypeslots' ] as $eventbookingtypeslots ) {
                    $eventpart_id = fulcrm_apiv2_url_to_pk( $eventbookingtypeslots[ 'eventslot' ][ 'eventpart' ] );
                    $eventslot_id = fulcrm_apiv2_url_to_pk( $eventbookingtypeslots[ 'eventslot' ][ 'url' ] );

                    if ( array_key_exists( $eventpart_id, $eventslotbookings ) )
                        drupal_set_message( 'XXX cannot yet cope with multiple choice event slot bookings; defaulting to first.', 'warning' );

                    $eventslotbookings[ $eventpart_id ] = $eventslot_id;
                }
            } else {
                drupal_set_message( 'XXX no eventbookingtypeslots to choose from?', 'warning' );
            }

            if ( $person_uuid ) {
                $item = array( 'shoppingcart' => $cart[ 'url' ],
                               'product' => fulcrm_apiv2_make_url( 'product', $product_id ),
                               'quantity' => 1.0,
                               'd' => array( 'fulcrm' => array( 'eventbooking' => array( 'eventbooking' => array(),
                                                                                         'eventslotbookings' => $eventslotbookings,
                                                                                         'person' => $person_uuid,
                                                                                         ),
                                                                ),
                                             'name' => $shoppingitem_name,
                                             ),
                               );

                $api_data = fulcrm_apiv2_POST( 'shoppingitem/', $item, $query = array( 'expand' => 'd' ) );
                if ( $api_data[ 'success' ] ) {
                    drupal_set_message( t('Added "%item" to shopping cart.', array( '%item' => $item[ 'd' ][ 'name' ] ) ), 'status' );
                    $form_state[ 'redirect' ] = 'fulcrm/cart';
                } else {
                    drupal_set_message( t('There was a problem adding your item to the shopping cart.'), 'error' );
                }
            }
        }
    } else {
        drupal_set_message( t('There was a problem adding your item to the shopping cart.'), 'error' );
    }

    $form_state[ 'fulcrm_shoppingcart' ][ 'shoppingcart' ] = $cart;
}

function fulcrm_shoppingcart_buy_eventbookingtype_form( $form, &$form_state, $person, $eventbookingtype, $product ) {
    $form_state[ 'fulcrm_shoppingcart' ][ 'person' ] = $person;
    $form_state[ 'fulcrm_shoppingcart' ][ 'eventbookingtype' ] = $eventbookingtype;
    $form_state[ 'fulcrm_shoppingcart' ][ 'product' ] = $product;

    $form = array();

    $form[ 'title_event' ] = array( '#type' => 'markup',
                                    '#markup' => '<h1>' . check_plain( $eventbookingtype[ 'event' ][ 'name' ] ) . '</h1>',
                                    );
    $form[ 'title_eventbookingtype' ] = array( '#type' => 'markup',
                                               '#markup' => '<h2>' . check_plain( $eventbookingtype[ 'name' ] ) . '</h2>',
                                               );
    $form[ 'title_product' ] = array( '#type' => 'markup',
                                      '#markup' => '<h3>' . check_plain( $product[ 'name' ] ) . '</h3>',
                                      );

    // $form[ 'person' ] = fulcrm_collection_to_form( 'person', $eventbookingtype[ 'person_ddatacollection' ], $person[ 'd' ] );

    $persons = array();

    if ( array_key_exists( 'related_from_person2persons', $person ) ) {
        foreach ( $person[ 'related_from_person2persons' ] as $p2p ) {
            $form_state[ 'fulcrm_shoppingcart' ][ 'persons' ][ $p2p[ 'related_from' ][ 'uuid' ] ] = $p2p[ 'related_from' ];
            $persons[ fulcrm_crypto_object_id_form_value( 'person.uuid', $p2p[ 'related_from' ][ 'uuid' ] ) ] = $p2p[ 'related_from' ][ 'name' ] . ' (your ' . $p2p[ 'relationship' ][ 'name' ] . ')';
        }
    }
    if ( array_key_exists( 'related_to_person2persons', $person ) ) {
        foreach ( $person[ 'related_to_person2persons' ] as $p2p ) {
            $form_state[ 'fulcrm_shoppingcart' ][ 'persons' ][ $p2p[ 'related_to' ][ 'uuid' ] ] = $p2p[ 'related_to' ];
            $persons[ fulcrm_crypto_object_id_form_value( 'person.uuid', $p2p[ 'related_to' ][ 'uuid' ] ) ] = $p2p[ 'related_to' ][ 'name' ] . ' (your ' . $p2p[ 'relationship' ][ 'name' ] . ')';
        }
    }

    $persons[ 'myself' ] = 'myself';

    $form[ 'ticket_for_persons' ] = array( '#type' => 'checkboxes',
                                           '#title' => 'Who is coming to the event?',
                                           '#description' => 'Tick the box next to each person for whom you want to buy a ticket.',
                                           '#options' => $persons,
                                           );
    $form[ 'tickets_for_others' ] = array( '#type' => 'select',
                                           '#title' => 'How many tickets would you like for other people?',
                                           '#description' => 'Choose how many tickets you are getting for other people. You\'ll be asked their names soon.',
                                           '#options' => array( 0 => 'just the named people above',
                                                                1 => '1 more',
                                                                2 => '2 more',
                                                                3 => '3 more',
                                                                4 => '4 more',
                                                                ),
                                           );

    $form[ 'actions' ] = array( '#type' => 'actions' );
    $form[ 'actions' ][ 'save' ] = array( '#type' => 'submit',
                                          '#value' => t('Add to Basket'),
                                          '#submit' => array( 'fulcrm_shoppingcart_buy_eventbookingtype_form_submit' ),
                                          );

    return $form;
}

function fulcrm_shoppingcart_buy( $product_id, $hmac ) {
    global $user;

    if ( fulcrm_crypto_check_object_id_hmac( 'product', $product_id, $hmac ) ) {
        $product_data = fulcrm_apiv2_GET( 'product/' . $product_id . '/',
                                          $query = array( 'expand' => implode( ',', array( 'content_object',
                                                                                           'selector_object',
                                                                                           'person_ddatacollection',
                                                                                           'organisation_ddatacollection',
                                                                                           'thing_ddatacollection',
                                                                                           'transaction_ddatacollection',
                                                                                           'lineitem_ddatacollection',
                                                                                           ) ) ) );
        if ( user_is_logged_in() )
            $person_id = fulcrm_webhook_get_pk_for_entity_type( 'user', $user->uid, 'person' );
        else
            $person_id = null;

        if ( $person_id ) {
            $person_data = fulcrm_apiv2_GET( 'person/' . $person_id . '/',
                                             $query = array( 'expand' => implode( ',', array( 'd',
                                                                                              'related_from_person2persons',
                                                                                              'related_from_person2persons.related_from',
                                                                                              'related_from_person2persons.related_from.d',
                                                                                              'related_from_person2persons.relationship',
                                                                                              'related_to_person2persons',
                                                                                              'related_to_person2persons.related_to',
                                                                                              'related_to_person2persons.related_to.d',
                                                                                              'related_to_person2persons.relationship',
                                                                                              ) ) ) );
        } else {
            $person_data = array( 'data' => array() );
        }

        if ( $product_data[ 'success' ] ) {
            switch ( fulcrm_apiv2_url_to_type( $product_data[ 'data' ][ 'content_object' ][ 'url' ] ) ) {
            case 'eventbookingtype':
                $eventbookingtype_data = fulcrm_apiv2_GET( $product_data[ 'data' ][ 'content_object' ][ 'url' ],
                                                           $query = array( 'expand' => implode( ',', array( 'event',
                                                                                                            'person_ddatacollection',
                                                                                                            'eventbooking_ddatacollection',
                                                                                                            'eventbookingtypeslots',
                                                                                                            'eventbookingtypeslots.eventslot' ) ) ) );
                if ( $eventbookingtype_data[ 'success' ] ) {
                    return drupal_get_form( 'fulcrm_shoppingcart_buy_eventbookingtype_form', $person_data[ 'data' ], $eventbookingtype_data[ 'data' ], $product_data[ 'data' ] );
                }
                break;
            default:
                return 'cannot handle these products yet';
            }

            return 'ok!';
        } else {
            return 'error adding item to shopping basket';
        }
    } else {
        drupal_not_found();
    }
}

function fulcrm_shoppingcart_remove_shoppingitem_confirm_submit( $form, &$form_state ) {
    $api_data = fulcrm_apiv2_DELETE( $form_state[ 'fulcrm_shoppingcart' ][ 'shoppingitem' ][ 'url' ] );

    if ( $api_data[ 'success' ] )
        drupal_set_message( t('Removed "%item" from cart.', array( '%item' => ( array_key_exists( 'name', $form_state[ 'fulcrm_shoppingcart' ][ 'shoppingitem' ][ 'd' ] ) ? $form_state[ 'fulcrm_shoppingcart' ][ 'shoppingitem' ][ 'd' ][ 'name' ] : $form_state[ 'fulcrm_shoppingcart' ][ 'shoppingitem' ][ 'product' ][ 'name' ] ) ) ), 'status' );

    $form_state[ 'redirect' ] = 'fulcrm/cart';
}

function fulcrm_shoppingcart_remove_shoppingitem_confirm( $form, &$form_state, $shoppingitem ) {
    $form_state[ 'fulcrm_shoppingcart' ][ 'shoppingitem' ] = $shoppingitem;

    return confirm_form( $form, 
                         t('Remove from cart?'), 
                         'fulcrm/cart',
                         t('Are you sure you want to remove "%item" from your shopping cart?', array( '%item' => ( array_key_exists( 'name', $shoppingitem[ 'd' ] ) ? $shoppingitem[ 'd' ][ 'name' ] : $shoppingitem[ 'product' ][ 'name' ] ) ) ), 
                         t('Remove'), 
                         t('Cancel')
                         );
}

function fulcrm_shoppingcart_remove( $shoppingitem_id, $hmac ) {
    if ( fulcrm_crypto_check_object_id_hmac( 'shoppingitem', $shoppingitem_id, $hmac ) ) {
        $shoppingitem_data = fulcrm_apiv2_GET( 'shoppingitem/' . $shoppingitem_id . '/',
                                               $query = array( 'expand' => implode( ',', array( 'd',
                                                                                                'product',
                                                                                                'content_object',
                                                                                                'shoppingcart',
                                                                                                ) ) ) );

        if ( $shoppingitem_data[ 'success' ] ) {
            if ( $shoppingitem_data[ 'data' ][ 'shoppingcart' ][ 'completed' ] ) {
                drupal_set_message( t('Shopping cart has been ordered. You can\'t remove things now!'), 'error' );
                drupal_goto( '<front>' );
                return;
            }

            if ( $shoppingitem_data[ 'data' ][ 'shoppingcart' ][ 'abandoned' ] ) {
                drupal_set_message( t('Sorry, your shopping cart has timed out. Please restart your purchase.'), 'error' );
                drupal_goto( variable_get( 'fulcrm_shoppingcart_proceed_url', '<front>' ) );
                return;
            }

            return drupal_get_form( 'fulcrm_shoppingcart_remove_shoppingitem_confirm', $shoppingitem_data[ 'data' ] );
        } else {
            drupal_set_message( t('Cannot remove item: it\'s already gone?'), 'error' );;
            drupal_goto( 'fulcrm/cart' );
        }
    }
}

function fulcrm_shoppingcart_cart() {
    $cart = fulcrm_shoppingcart_get_session_cart( false );
    return theme( 'fulcrm_shoppingcart_cart', array( 'cart' => $cart ) );
}

function fulcrm_shoppingcart_checkout() {
    $cart = fulcrm_shoppingcart_get_session_cart( false );
    if ( $cart && array_key_exists( 'url', $cart ) ) {
        $transaction_data = fulcrm_apiv2_POST( $cart[ 'url' ] . 'transaction/', array(), array( 'expand' => implode( ',', array( 'd' ) ) ) );
        if ( $transaction_data[ 'success' ] ) {
            $hmac = fulcrm_crypto_object_id_hmac( 'transaction', $transaction_data[ 'data' ][ 'id' ] );

            $transaction_push = array( 'd' => array( 'fulcrm_fund_transaction_pay_failure_url' => url( 'fulcrm/checkout/failure/' . $transaction_data[ 'data' ][ 'id' ]. '/' . $hmac, array( 'absolute' => TRUE ) ),
                                                     'fulcrm_fund_transaction_complete_success_url' => url( 'fulcrm/checkout/success/' . $transaction_data[ 'data' ][ 'id' ]. '/' . $hmac, array( 'absolute' => TRUE ) ),
                                                     'fulcrm_fund_transaction_complete_failure_url' => url( 'fulcrm/checkout/failure/' . $transaction_data[ 'data' ][ 'id' ]. '/' . $hmac, array( 'absolute' => TRUE ) ),
                                                     ),
                                       );

            $transaction_data2 = fulcrm_apiv2_PATCH( $transaction_data[ 'data' ][ 'url' ],
                                                     $transaction_push, $query = array( 'expand' => implode( ',', array( 'd',
                                                                                                                         'lineitems',
                                                                                                                         'lineitems.d',
                                                                                                                         'lineitems.content_object',
                                                                                                                         // XXX 'lineitems.content_object.d',
                                                                                                                         'paymentitems',
                                                                                                                         'paymentitems.d',
                                                                                                                         ) ) ) );
            if ( $transaction_data2[ 'success' ] ) {
                return theme( 'fulcrm_shoppingcart_transaction_checkout', array( 'transaction' => $transaction_data2[ 'data' ] ) );
            }
            return 'problem 3';
        }
        return 'problem 2';
    }
    return 'problem 1';
}

function fulcrm_shoppingcart_checkout_success( $transaction_id, $hmac ) {
    return 'success';
}

function fulcrm_shoppingcart_checkout_failure( $transaction_id, $hmac ) {
    return 'failure';
}