<?php

class IvtCustomerController extends mfBaseController {
  
  protected function createAction() {
    $order_id = $this->request->order_id;
    $order = new Order($order_id);
    if(!$order->id) {
      $this->layout()->setFlash("Bestellung nicht gefunden.", "error");
      $this->redirect("Order");
    }
    
    $contact = $order->$billingaddress;
    if(!$contact) {
      $contact = $order->owner;
    } else {
      $contact->customer_number = $order->owner->customer_number;
    }
    
    if(!$contact->customer_number) {
      $return = ['status' => 'error', 'reason' => "no-cust-num"];
      $this->returnJson($return);
    }
    
    $ivtc = new IvtCustomer($contact->customer_number);
    //var_dump($ivtc);
    
    if($ivtc->id) {
      $return = ['status' => 'error', 'reason' => "ivt-exist"];
      $this->returnJson($return);
    }
    

    $ivtc->title = "";
    $ivtc->nick = "";
    $ivtc->pwd = "";
    $ivtc->bankcode = "";
    $ivtc->accountnumber = "";
    $ivtc->bill_row1 = "";
    $ivtc->bill_row2 = "";
    $ivtc->bill_row3 = "";
    $ivtc->bill_row4 = "";
    
    $ivtc->id = $contact->customer_number;
    $ivtc->firstname = $contact->firstname;
    $ivtc->surname = $contact->lastname;
    $ivtc->company = str_replace("\r\n", " ", str_replace("\n", " ", $contact->company));

    if($contact->company) {
      $ivtc->firstname = "";
      $ivtc->surname = str_replace("\r\n", " ", str_replace("\n", " ", $contact->company));
    }
    $ivtc->UID = ""; // XXX
    $ivtc->zip = $contact->zip;
    $ivtc->location = $contact->city;
    
    // get housenumber
    $m = [];
    if(preg_match('/^(.+)\s+([^ ]+$)/', $contact->street, $m)) {
      if($m[1]) {
        $ivtc->street = $m[1];
        if($m[2]) {
          $ivtc->housenumber = $m[2];
        } else {
          $ivtc->housenumber = "";
        }
      }
    } else {
      $ivtc->street = $contact->street;
      $ivtc->housenumber = "";
    }
    
    $ivtc->phone = $contact->phone;
    $ivtc->email = $contact->email;
    
    if($order->billing_type == "sepa") {
      $ivtc->payment = 0; // 0 = sepa / 1 = rechnung
      $ivtc->BIC = $order->bank_account_bic;
      $ivtc->IBAN = $order->bank_account_iban;
    } else {
      $ivtc->payment = 1; // 0 = sepa / 1 = rechnung
      $ivtc->BIC = "";
      $ivtc->IBAN = "";
    }
    
    $ivtc->paper_invoice = 0;
    if(!$contact->email) {
      $ivtc->paper_invoice = 1;
    }
    
    $ivtc->MandatID = ($contact->spin) ? $contact->spin : 1;
    
    $ivtc->egn = 0; // 0=keine;1=pdf;2=cdr
    $ivtc->accept_adver = ($order->allow_contact) ? 2 : 1;
    $ivtc->accept_info = ($order->allow_spin) ? 2 : 1;
    $ivtc->telephony_pricelist = 2;
    $ivtc->extrainfo = $order->note;

    //var_dump($ivtc);

    if($ivtc->save()) {
      $return = ['status' => 'OK', 'reason' => ""];
    } else {
      $return = ['status' => 'error', 'reason' => "save"];
    }
    $this->returnJson($return);
  }
}