<?php
namespace Domain\Users;

class PermissionRepository
{
  const MODULES = [ 'tasks', 'projects_view', 'projects_add', 'projects_edit', 'projects_delete', 'finances', 'wiki', 'crm', 'work_time' ];

  const DEFAULTS = [
    'tasks'    => 1,
    'projects_view' => 1,
    'projects_add' => 1,
    'projects_edit' => 1,
    'projects_delete' => 1,
    'finances' => 0,
    'wiki'     => 1,
    'crm'      => 0,
    'work_time' => 1
  ];

  private $mdb;

  public function __construct( $mdb = null )
  {
    if ( $mdb )
      $this -> mdb = $mdb;
    else if ( isset( $GLOBALS['mdb'] ) )
      $this -> mdb = $GLOBALS['mdb'];
    else
      $this -> mdb = null;
  }

  public static function defaults()
  {
    return self::DEFAULTS;
  }

  public function byUserId( $user_id )
  {
    if ( !$this -> mdb )
      return self::defaults();

    $row = $this -> mdb -> get( 'users_permissions', '*', [ 'user_id' => (int)$user_id ] );

    if ( !$row )
      return self::defaults();

    $result = [];
    $legacy_projects_value = isset( $row['projects'] ) ? (int)$row['projects'] : 1;
    foreach ( self::MODULES as $module )
    {
      if ( isset( $row[ $module ] ) )
        $result[ $module ] = (int)$row[ $module ];
      else if ( strpos( $module, 'projects_' ) === 0 )
        $result[ $module ] = $legacy_projects_value;
      else
        $result[ $module ] = isset( self::DEFAULTS[ $module ] ) ? (int)self::DEFAULTS[ $module ] : 0;
    }

    return $result;
  }

  public function save( $user_id, array $modules )
  {
    if ( !$this -> mdb )
      return;

    $data = [];
    foreach ( self::MODULES as $module )
      $data[ $module ] = isset( $modules[ $module ] ) ? (int)(bool)$modules[ $module ] : 0;

    $existing = $this -> mdb -> get( 'users_permissions', 'user_id', [ 'user_id' => (int)$user_id ] );

    if ( $existing )
      $this -> mdb -> update( 'users_permissions', $data, [ 'user_id' => (int)$user_id ] );
    else
      $this -> mdb -> insert( 'users_permissions', array_merge( [ 'user_id' => (int)$user_id ], $data ) );
  }
}
