<?php

function fernweh_invoice_preview_modal_callback($js = FALSE, $nodeId) {
    if ($js) {

        ctools_include('modal');
        ctools_include('ajax');
        ctools_add_js('ajax-responder');

        $form_state = array(
            'title' => t('Send Invoice'),
            'ajax' => TRUE,
        );


        $output = ctools_modal_form_wrapper('fernweh_invoice_preview_form', $form_state);

        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }

        print ajax_render($output);
        drupal_exit();

    }
    else {
        return drupal_get_form('fernweh_invoice_preview_form');
    }
}

function fernweh_invoice_preview_form($form, $form_state) {

    $order_id = (arg(2) == "invoice" && is_numeric(arg(3)))?arg(3):0;
    $invoice_pdf_path = array();
    $files = array();//"invoice_".$order_id.".pdf";
    if(function_exists('fernweh_generate_invoice_pdf')){
        $invoices = fernweh_generate_invoice_pdf($order_id);
        $invoice_pdf_path = $invoices;
        foreach($invoices as $invoice){
            $file_link = file_create_url(file_build_uri($invoice));
            $files[] = array( 'filename' => basename($file_link),
                            'link' => $file_link
                    );
        }
    }
    $to = "";
    $product_id = fernweh_get_account_id($order_id, TRUE);
    $product = commerce_product_load($product_id);

    if(is_object($product)){
        $to = isset($product->field_lead_passenger_email[LANGUAGE_NONE][0]['value']) ? $product->field_lead_passenger_email[LANGUAGE_NONE][0]['value'] : '';

    }
    $form = array();
    $form['order_id'] = array(
        '#type' => 'hidden',
        '#default_value' => $order_id,
    );
    $form['invoice_pdf_path'] = array(
        '#type' => 'hidden',
        '#default_value' => implode(',', $invoice_pdf_path),
    );
    $form['to'] = array(
        '#title' => t('To'),
        '#type' => 'textfield',
        '#default_value' => $to,
        '#description' => t("Enter the recipient(s) separated by lines or commas. "),
        '#required' => TRUE
    );
    $subject = "Order Invoice";
    $form['subject'] = array(
        '#title' => t('Subject'),
        '#type' => 'textfield',
        '#default_value' => $subject,
        '#required' => TRUE
    );
    
    $defaultMessage = "Dear Sir / Madam, 
 
Please find your invoice attached for " . $product->field_global_id[LANGUAGE_NONE][0]['value'] . ". 

Clients are requested to check invoice immediately upon receipt. Errors should be highlighted within 24 - 48 hours. Changes or discrepancies beyond the aforementioned timelines will not be accepted and we will not be held liable for any damages or loss incurred. 
Kindly also inform the Accounts team of payment schedule after receipt of invoice. 
 
Contact: Accounts@fernweh.in | 044 42042425 | 044 45042425

Thanks,
The Fernweh Team";
    $form['message'] = array(
        '#title' => t('Body'),
        '#type' => 'textarea',
        '#default_value' => $defaultMessage,
        '#description' => t('Review and edit message before send. ')
    );

    $links = '<ul class="invoice-send-list">';
    foreach($files as $file){
        $links .= '<li><input style="box-shadow:none;float:left;width:25px;margin-top:9px;" type="checkbox" checked="checked" value="1"><a href="'.$file['link'].'" target="_blank">'.$file['filename'].'</a></li>';
    }
    $links .= "</ul>";
    $form['view_attachment'] = array(
        '#markup' =>'<div class="form-item form-type-textfield form-item-to">
                  <label for="edit-to">Attachment</label>
                 '.$links.'
                </div>',
    );

    $form['actions']['cancel'] = array(
        '#prefix' => '<div class="popup-footer-wrapper">',
        '#markup' => l(t('Cancel'), '#', array(
                'attributes' => array(
                    'class' => 'ctools-close-modal modal-cancel-btn'
                ),
                'external' => TRUE
            )
        )
    );
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Send'),
        '#suffix' => '</div>',
    );
    $form['actions']['submit']['#submit'][] = 'fernweh_invoice_send_form_submit';
    return $form;
}

function fernweh_invoice_send_form_submit($form, &$form_state){

    $order_id = $form_state['values']['order_id'];
    $file_paths = $form_state['values']['invoice_pdf_path'];
    $recipients = $form_state['values']['to'];
    $subject = $form_state['values']['subject'];
    $message = str_replace(PHP_EOL, "<br/>", $form_state['values']['message']);

    if($recipients){
        $recipients = explode(',', $recipients);
    }
    $body = fernweh_prepare_mail_markup(array('body'=>$message));
    $from = "no-reply@fernweh.in";

    $dir_uri = file_stream_wrapper_get_instance_by_uri('public://');
    $path = $dir_uri->realpath();
    $attachments = array();
    $file_paths = explode(',', $file_paths);
    foreach($file_paths as $file){
        $absolute_path = $path.$file;
        $attachments[] = fernweh_prepare_attachment($absolute_path, false, basename($file));
    }
    $mailSent = FALSE;
    if(function_exists('fernweh_sendmail')){
        if(is_array($recipients)){
            foreach($recipients as $to){
                $to = trim($to);
                if( filter_var($to, FILTER_VALIDATE_EMAIL) ){
                    $mailSent = fernweh_sendmail($to, $from, $subject, $body, $attachments)?TRUE:FALSE;
                }
            }
        }
    }

    if ($mailSent) {
        $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
        drupal_set_message('Invoice sent successfully.');
    }
    else {
        drupal_set_message('Some error occurred while sending mail.', 'error');
    }

    $form_state['ajax_commands'][] =  ctools_ajax_command_reload();


}