<?php
namespace Domain\Crm;

class ClientRepository
{
  private $mdb;

  public function __construct( $mdb = null )
  {
    if ( $mdb )
      $this -> mdb = $mdb;
    else
    {
      global $mdb;
      $this -> mdb = $mdb;
    }
  }

  public function all()
  {
    return $this -> mdb -> select( 'crm_client', '*', [ 'ORDER' => [ 'firm' => 'ASC' ] ] );
  }

  public function getById( int $client_id )
  {
    return \R::load( 'crm_client', $client_id );
  }

  public function getName( int $client_id )
  {
    return $this -> mdb -> get( 'crm_client', 'firm', [ 'id' => $client_id ] );
  }

  public function save( int $client_id, string $firm, string $firm_name, string $emails, string $phones, string $notes )
  {
    $client = \R::load( 'crm_client', $client_id );
    if ( !$client )
    {
      $client = \R::xdispense( 'crm_client' );
      $client -> date_add = date( 'Y-m-d H:i:s' );
    }
    $client -> firm = $firm;
    $client -> firm_name = $firm_name;
    $client -> emails = $emails;
    $client -> phones = $phones;
    $client -> notes = $notes;
    $client -> date_update = date( 'Y-m-d H:i:s' );
    return \R::store( $client );
  }

  public function delete( int $client_id )
  {
    return $this -> mdb -> delete( 'crm_client', [ 'id' => $client_id ] );
  }

  public function settings()
  {
    $settings = [];
    $results = $this -> mdb -> select( 'settings', '*' );
    foreach ( $results as $result )
    {
      $settings[ $result['name'] ] = $result['value'];
    }
    return $settings;
  }
}
