<?php

function order_form_menu()
{
    $items = array();

    $items['order_form'] = array
    (
        'title'             => t('Order form'),
        'page callback'     => 'order_form_showform',
        'type'              => MENU_CALLBACK,
        'access arguments'  => array('access content')
    );

    $items['contact_form'] = array
    (
        'title'             => t('Order form'),
        'page callback'     => 'order_form_showcontactform',
        'type'              => MENU_CALLBACK,
        'access arguments'  => array('access content')
    );

    return $items;
}

function order_form_get_container_types()
{
    global $language ;
    $lang_name = $language->language ;

    $containerTypes = array();

    $result = db_query("SELECT * FROM node WHERE type = 'container' AND (language = '' OR language = '" . $lang_name . "')");

    //print "AAA";

    while ($obj = db_fetch_object($result))
    {
        //print_r($obj);

        $nn = node_load($obj->nid);
        $ss = null;

        //print_r($nn);

        //$nodes = order_form_get_node_reference_referrals('field_sideways', 'container', $obj->nid);
        //print_r($nodes);

        $containerTypes[$obj->nid] = array
        (
            'name'      => $obj->title
        );


        if (!empty($nn->field_sideways))
        {
            foreach ($nn->field_sideways as $sideways)
            {
                $ss = node_load($sideways['nid']);
                //print_r($ss);
                if ($ss)
                    $containerTypes[$obj->nid]['types'][] = $ss->title;
            }
        }


        if (empty($containerTypes[$obj->nid]['types']))
        {
           $containerTypes[$obj->nid]['types'][] = $obj->title;
        }

    }
    /*

    $containerTypes = array
    (
        "reefer"    => array
        (
            'name'  => t('Reefer Containers'),
            'types' => array
            (
                '20\'rf standard',
                '40\'rf standard',
                '40\'rf high cube',
            )
        ),
        "dry"       => array
        (
            'name'  => t('Dry Containers'),
            'types' => array
            (
                '20\' Dry',
                '20\' Open Top',
                '40\' Dry High Cube',
                '25\' Dry High Cube',
                '20\' Dry NEW',
                '40\' Dry',
                '40\' Open Top'
            )
        )
    );*/

    //print_r($containerTypes);

    return $containerTypes;
}

function order_form_form()
{
    $containerTypes = order_form_get_container_types();

    $form['order_delivery'] = array
    (
        '#type'         => 'fieldset',
        '#title'        => t('Order and Delivery'),
        '#tree'         => false
    );

    foreach ($containerTypes as $id => $type)
        $typeOptions[$id] = $type['name'];

    $form['order_delivery']["containers"] = array
    (
        '#type'         => 'checkboxes',
        '#title'        => t('Containers'),
        '#options'      => $typeOptions,
        '#attributes'   => array( 'class' => 'container' )
    );

    foreach ($containerTypes as $id => $type)
    {
        //$id = str_replace("'", "`", $id);
        $form['order_delivery']['container_type_' . $id] = array
        (
            '#type'         => 'fieldset',
            '#title'        => $type['name'],
            '#tree'         => true,
            '#collapsible'  => true,
            '#attributes'   => array( 'id' => 'container_type_' . $id, 'class' => 'container_type' )
        );

        foreach ($type['types'] as $currentType)
        {
            $i++;
            $ct = base64_encode($currentType);
            $form['order_delivery']['container_type_' . $id][$currentType] = array
            (
                '#id'           => 'zzz_' . $id . "_" . $i,
                '#type'         => 'textfield',
                '#title'        => $currentType,
                '#size'         => 3,
                '#attributes'   => array( 'class' => 'container_type_count')
            );
        }
    }

    $form['order_delivery']['texts'] = array
    (
        '#type'         => 'fieldset',
        '#title'        => '',
        '#tree'         => false
    );

    $form['order_delivery']['texts']['delivery'] = array
    (
        '#type'         => 'textarea',
        '#title'        => t('Delivery'),
        '#required'     => false
    );

    $form['order_delivery']['texts']['condition'] = array
    (
        '#type'         => 'textarea',
        '#title'        => t('Condition'),
        '#required'     => false
    );

    $form['order_delivery']['texts']['additional'] = array
    (
        '#type'         => 'textarea',
        '#title'        => t('Additional information'),
        '#required'     => false
    );


    $form['contacts'] = array
    (
        '#type'         => 'fieldset',
        '#title'        => t('Contacts'),
        '#tree'         => false
    );


    $form['contacts']['company'] = array
    (
        '#type'         => 'textfield',
        '#title'        => t('Company name'),
        '#size'         => '50'
    );

    $form['contacts']['person'] = array
    (
        '#type'         => 'textfield',
        '#title'        => t('Contact person'),
        '#size'         => '50'
    );

    $form['contacts']['phone'] = array
    (
        '#type'         => 'textfield',
        '#title'        => t('Phone'),
        '#size'         => '50'
    );

    $form['contacts']['email'] = array
    (
        '#type'         => 'textfield',
        '#title'        => t('E-mail'),
        '#size'         => '50'
    );

    $form['contacts']['country'] = array
    (
        '#type'         => 'textfield',
        '#title'        => t('Country'),
        '#size'         => '50'
    );

    $form['contacts']['contact_additional'] = array
    (
        '#type'         => 'textarea',
        '#title'        => t('Additional information'),
        '#required'     => false
    );

    $form['contacts']['how_did_you_find_us'] = array
    (
        '#type'         => 'textarea',
        '#title'        => t('How did you find us') . "?",
        '#required'     => false
    );

    $form['contacts']['captcha'] = array
    (
        '#type'         => 'captchaa',
        '#title'        => t('Security code'),
        '#required'     => false
    );

    $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));

    return $form;
}

function order_form_showform()
{
    $a = drupal_get_form("order_form_form");

    return $a;
}

function order_form_mail($key, &$message, $params)
{
    $headers = array
    (
        'MIME-Version'              => '1.0',
        'Content-Type'              => 'text/html; charset=UTF-8; format=flowed',
        'Content-Transfer-Encoding' => '8Bit',
        'X-Mailer'                  => 'Drupal'
    );

    foreach ($headers as $key => $value)
        $message['headers'][$key] = $value;

    $message['subject'] = $params['subject'];
    $message['body'] = $params['body'];
}

function order_form_form_submit($form, &$form_state)
{
    //print_r($form_state);

    $containerTypes = order_form_get_container_types();

    $site_email = variable_get('site_mail', '');

    $emailText = t("New order form submitted") . "<br><br>";


    foreach ($form_state['values']['containers'] as $id => $value)
    {
        if ($value != '0')
        {
            // Get the container's nice name
            $containerName = $containerTypes[$id]['name'];
            $emailText .= $containerName . ":<br>";
            foreach ($form_state['values']['container_type_' . $id] as $containerType => $quantity)
            {
                if (intval($quantity) > 0)
                    $emailText .= $containerType . ": " . $quantity . "<br>";
            }
            $emailText .= "<br>";
        }
    }

    if (!empty ($form_state['values']['delivery']))
        $emailText .= t("Delivery") . ": " . $form_state['values']['delivery'] . "<br>";

    if (!empty ($form_state['values']['condition']))
        $emailText .= t("Condition") . ": " . $form_state['values']['condition'] . "<br>";

    if (!empty ($form_state['values']['additional']))
        $emailText .= t("Additional information") . ": " . $form_state['values']['additional'] . "<br>";

    $emailText .= "<br>" . t("Contacts") . ":<br>";

    if (!empty ($form_state['values']['company']))
        $emailText .= t("Company name") . ": " . $form_state['values']['company'] . "<br>";

    $emailText .= t("Contact person") . ": " . $form_state['values']['person'] . "<br>";

    if (!empty ($form_state['values']['phone']))
        $emailText .= t("Phone") . ": " . $form_state['values']['phone'] . "<br>";

    $emailText .= t("E-mail") . ": " . $form_state['values']['email'] . "<br>";

    $emailText .= t("Country") . ": " . $form_state['values']['country'] . "<br>";

    if (!empty ($form_state['values']['contact_additional']))
        $emailText .= t("Additional information") . ": " . $form_state['values']['contact_additional'] . "<br>";

    if (!empty ($form_state['values']['how_did_you_find_us']))
        $emailText .= t("How did you find us") . ": " . $form_state['values']['how_did_you_find_us'] . "<br>";

    $params = array
    (
        'body'      => $emailText,
        'subject'   => t("New order form submitted")
    );

    if (drupal_mail('order_form', 'some_mail_key', $site_email, language_default(), $params, "mailer@containers.lv", TRUE))
        drupal_set_message(t('An email has been sent'));
    else
        drupal_set_message('There was an error sending your email');

}


function order_form_showcontactform()
{}