<?php
namespace Controllers;

class CrmController
{
  public static $source = [ 0 => 'ceidg', 1 => 'kontakt własny', 2 => 'BNI' ];
  public static $status = [ 0 => 'kontakt pozyskany', 1 => 'oferta wysłana', 2 => 'follow up', 3 => 'klient niezainteresowany' ];

  public static function mainView()
  {
    global $user;

    if ( !$user or !\controls\Users::permissions( $user['id'], 'wiki' ) )
      return false;

    return \Tpl::view( 'crm/main-view' );
  }

  public static function clientEdit()
  {
    global $user;

    if ( !$user or !\controls\Users::permissions( $user['id'], 'wiki' ) )
      return false;

    $repository = new \Domain\Crm\ClientRepository();

    return \Tpl::view( 'crm/client-edit', [
      'client' => $repository -> getById( (int)\S::get( 'id' ) )
    ] );
  }

  public static function clientSave()
  {
    global $user;

    if ( !$user or !\controls\Users::permissions( $user['id'], 'wiki' ) )
      return false;

    $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania klienta wystąpił błąd. Proszę spróbować ponownie.' ];
    $values = \S::json_to_array( \S::get( 'values' ) );

    $repository = new \Domain\Crm\ClientRepository();

    if ( $id = $repository -> save(
      (int)$values['id'], $values['firm'], $values['firm_name'], $values['emails'], $values['phones'], $values['notes']
    ) )
      $response = [ 'status' => 'ok', 'msg' => 'Projekt został zapisany.', 'id' => $id ];

    echo json_encode( $response );
    exit;
  }

  public static function clientDelete()
  {
    global $user;

    if ( !$user )
      return \controls\Users::login_form();

    $repository = new \Domain\Crm\ClientRepository();

    if ( $repository -> delete( (int)\S::get( 'client_id' ) ) )
    {
      \S::alert( 'Klient został usunięty' );
      header( 'Location: /crm/main_view/' );
      exit;
    }
  }
}
