<?php

class ModuleStock extends Module
{
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Stock';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPLv3';
    $this->Description = 'Stock and products';
    $this->Dependencies = array(ModuleUser::GetName(), ModuleCustomer::GetName(), ModuleNetwork::GetName(),
      ModuleDocument::GetName());
    $this->Models = array(Product::GetClassName(), StockSerialNumber::GetClassName(), Stock::GetClassName(),
      StockMoveGroup::GetClassName(), StockMove::GetClassName(), StockMoveItem::GetClassName(),
      StockItemHistory::GetClassName(), StockMoveItemSerialRel::GetClassName());
  }

  function DoStart(): void
  {
    $this->System->FormManager->RegisterClass('Product', array(
      'Title' => 'Produkty',
      'Table' => 'Product',
      'DefaultSortColumn' => 'Name',
      'Items' => array(
        'Manufacturer' => array('Type' => 'TSubject', 'Caption' => 'Výrobce', 'Default' => '', 'Null' => true),
        'Code' => array('Type' => 'String', 'Caption' => 'Kód', 'Default' => ''),
        'Name' => array('Type' => 'String', 'Caption' => 'Jméno', 'Default' => ''),
        'SellPrice' => array('Type' => 'Integer', 'Caption' => 'Prodejní cena', 'Default' => '0', 'Suffix' => 'Kč'),
        'BuyPrice' => array('Type' => 'Integer', 'Caption' => 'Kupní cena', 'Default' => '0', 'Suffix' => 'Kč'),
        'VAT' => array('Type' => 'Integer', 'Caption' => 'DPH', 'Default' => '0', 'Suffix' => '%'),
        'Consumption' => array('Type' => 'Integer', 'Caption' => 'Spotřeba', 'Default' => '', 'Suffix' => 'Watt'),
        'Supplier' => array('Type' => 'TSubject', 'Caption' => 'Dodavatel', 'Default' => '', 'Null' => true),
        'UnitOfMeasure' => array('Type' => 'TUnitOfMeasure', 'Caption' => 'Měrná jednotka', 'Default' => '', 'Null' => true),
        'StockSerialNumbers' => array('Type' => 'TStockSerialNumberListProduct', 'Caption' => 'Položky na skladě', 'Default' => ''),
        'StockState' => array('Type' => 'Integer', 'Caption' => 'Počet na skladě', 'Default' => '', 'ReadOnly' => true,
          'SQL' => 'SELECT IFNULL(SUM(`Amount`), 0) FROM `StockMoveItem` WHERE `StockMoveItem`.`Product`=#Id'),
        'StockMinCount' => array('Type' => 'Integer', 'Caption' => 'Skladové minimum', 'Default' => '0'),
        'StockMoves' => array('Type' => 'TStockMoveItemListProduct', 'Caption' => 'Pohyby na skladě', 'Default' => ''),
        'NetworkDevices' => array('Type' => 'TNetworkDeviceListProduct', 'Caption' => 'Síťová zařízení', 'Default' => ''),
        'StockShortage' => array('Type' => 'TStockState', 'Caption' => 'Stav skladu', 'Default' => '', 'ReadOnly' => true,
          'SQL' => 'SELECT (IFNULL(SUM(`Amount`), 0) >= `StockMinCount`) FROM `StockMoveItem` WHERE `StockMoveItem`.`Product`=#Id'),
      ),
    ));

    $this->System->FormManager->RegisterClass('StockSerialNumber', array(
      'Title' => 'Skladové položky',
      'Table' => 'StockSerialNumber',
      'DefaultSortColumn' => 'Id',
      'Items' => array(
        'Stock' => array('Type' => 'TStock', 'Caption' => 'Sklad', 'Default' => ''),
        'Product' => array('Type' => 'TProduct', 'Caption' => 'Produkt', 'Default' => ''),
        'TimeEnlistment' => array('Type' => 'Date', 'Caption' => 'Datum zařazení', 'Default' => ''),
        'TimeElimination' => array('Type' => 'Date', 'Caption' => 'Datum vyřazení', 'Default' => '', 'Null' => true),
        'SellPrice' => array('Type' => 'Integer', 'Caption' => 'Prodejní cena', 'Default' => '0', 'Suffix' => 'Kč'),
        'BuyPrice' => array('Type' => 'Integer', 'Caption' => 'Kupní cena', 'Default' => '0', 'Suffix' => 'Kč'),
        'Amount' => array('Type' => 'Integer', 'Caption' => 'Množství', 'Default' => '1'),
        'SerialNumber' => array('Type' => 'String', 'Caption' => 'Sériové číslo', 'Default' => '', 'Null' => true),
        'RegNumber' => array('Type' => 'String', 'Caption' => 'Evidenční číslo', 'Default' => '', 'Null' => true),
        'Location' => array('Type' => 'TMember', 'Caption' => 'Umístění', 'Default' => '', 'Null' => true),
        'Esemble' => array('Type' => 'TStockSerialNumber', 'Caption' => 'Celek', 'Default' => ''),
        'Parts' => array('Type' => 'TStockSerialNumberListStockSerialNumber', 'Caption' => 'Části', 'Default' => ''),
        'History' => array('Type' => 'TStockItemHistoryListStockSerialNumber', 'Caption' => 'Historie', 'Default' => ''),
        'Sériové čísla' => array('Type' => 'TStockMoveItemSerialListSerial', 'Caption' => 'Skladové pohyby', 'Default' => ''),
      ),
    ));
    $this->System->FormManager->RegisterClass('Stock', array(
      'Title' => 'Sklady',
      'Table' => 'Stock',
      'DefaultSortColumn' => 'Name',
      'Items' => array(
        'Name' => array('Type' => 'String', 'Caption' => 'Jméno', 'Default' => ''),
        'Location' => array('Type' => 'TMember', 'Caption' => 'Umístění', 'Default' => '', 'Null' => true),
        'Items' => array('Type' => 'TStockSerialNumberListStock', 'Caption' => 'Položky', 'Default' => ''),
        'ItemsCount' => array('Type' => 'Integer', 'Caption' => 'Položek', 'Default' => '',
          'ReadOnly' => true, 'SQL' => '(SELECT COUNT(*) FROM `StockSerialNumber` WHERE '.
          '(`StockSerialNumber`.`Stock`=#Id) AND (`StockSerialNumber`.`TimeElimination` IS NULL))'),
        'TotalPrice' => array('Type' => 'Integer', 'Caption' => 'Celková cena', 'Default' => '',
          'ReadOnly' => true, 'SQL' => '(SELECT SUM(`SellPrice`) FROM `StockSerialNumber` WHERE '.
          '(`StockSerialNumber`.`Stock`=#Id) AND (`StockSerialNumber`.`TimeElimination` IS NULL))', 'Suffix' => 'Kč'),
        'Moves' => array('Type' => 'TStockMoveStock', 'Caption' => 'Pohyby', 'Default' => ''),
      ),
    ));
    $this->System->FormManager->RegisterClass('StockMove', array(
      'Title' => 'Skladový pohyb',
      'Table' => 'StockMove',
      'DefaultSortColumn' => 'Time',
      'Items' => array(
        'Group' => array('Type' => 'TStockMoveGroup', 'Caption' => 'Skupina', 'Default' => ''),
        'BillCode' => array('Type' => 'TDocumentLineCode', 'Caption' => 'Označení', 'Default' => '', 'ReadOnly' => true),
        'Time' => array('Type' => 'DateTime', 'Caption' => 'Čas', 'Default' => ''),
        'Stock' => array('Type' => 'TStock', 'Caption' => 'Sklad', 'Default' => '', 'Null' => true),
        'File' => array('Type' => 'TFile', 'Caption' => 'Doklad', 'Default' => '', 'Null' => true),
        'Price' => array('Type' => 'Float', 'Caption' => 'Cena', 'Default' => '',
          'ReadOnly' => true, 'Suffix' => 'Kč', 'SQL' => '(SELECT SUM(`StockMoveItem`.`UnitPrice` * `StockMoveItem`.`Amount`) FROM `StockMoveItem` '.
          'WHERE `StockMoveItem`.`StockMove`=#Id)'),
        'Items' => array('Type' => 'TStockMoveItemListStockMove', 'Caption' => 'Položky', 'Default' => ''),
      ),
      'BeforeInsert' => array($this, 'BeforeInsertStockMove'),
      //'AfterInsert' => array($this, 'AfterInsertStockMove'),
      //'BeforeModify' => array($this, 'BeforeModifyStockMove'),
    ));
    $this->System->FormManager->RegisterClass('StockMoveItem', array(
      'Title' => 'Položka skladového pohybu',
      'Table' => 'StockMoveItem',
      'DefaultSortColumn' => 'Product',
      'Items' => array(
        'StockMove' => array('Type' => 'TStockMove', 'Caption' => 'Skladový pohyb', 'Default' => ''),
        'Product' => array('Type' => 'TProduct', 'Caption' => 'Produkt', 'Default' => ''),
        'UnitPrice' => array('Type' => 'Integer', 'Caption' => 'Jednotková cena', 'Default' => '0', 'Suffix' => 'Kč'),
        'Amount' => array('Type' => 'Integer', 'Caption' => 'Množství', 'Default' => '1'),
        'Total' => array('Type' => 'Integer', 'Caption' => 'Celkem', 'Default' => '', 'Suffix' => 'Kč',
          'ReadOnly' => true, 'SQL' => 'ROUND(`UnitPrice` * `Amount`, '.$this->System->Config['Finance']['Rounding'].')'),
        'Položky pohybů' => array('Type' => 'TStockMoveItemSerialListItem', 'Caption' => 'Vztahy sériových čísel', 'Default' => ''),
        'Sériové čísla' => array('Type' => 'String', 'Caption' => 'Sériové čísla', 'ReadOnly' => true,
          'SQL' => 'SELECT GROUP_CONCAT(`StockSerialNumber`.`RegNumber` SEPARATOR ", ") FROM `StockMoveItemSerialRel` '.
          'LEFT JOIN `StockSerialNumber` ON `StockSerialNumber`.`Id`=`StockMoveItemSerialRel`.`StockSerialNumber` '.
          'WHERE `StockMoveItemSerialRel`.`StockMoveItem`=#Id'),
      ),
    ));
    $this->System->FormManager->RegisterClass('StockMoveGroup', array(
      'Title' => 'Skupina skladových pohybů',
      'Table' => 'StockMoveGroup',
      'Items' => array(
        'Name' => array('Type' => 'String', 'Caption' => 'Název', 'Default' => '0'),
        'DocumentLine' => array('Type' => 'TDocumentLine', 'Caption' => 'Dokladová řada', 'Default' => '0'),
        'ValueSign' => array('Type' => 'TFinanceValueSign', 'Caption' => 'Znaménko hodnoty', 'Default' => '0'),
        'Direction' => array('Type' => 'TFinanceDirection', 'Caption' => 'Směr', 'Default' => '0'),
        'Items' => array('Type' => 'TStockMoveListGroup', 'Caption' => 'Operace', 'Default' => ''),
      ),
    ));
    $this->System->FormManager->RegisterClass('StockItemHistory', array(
      'Title' => 'Historie skladové položky',
      'Table' => 'StockItemHistory',
      'DefaultSortColumn' => 'Time',
      'Items' => array(
        'Time' => array('Type' => 'DateTime', 'Caption' => 'Čas', 'Default' => ''),
        'StockSerialNumber' => array('Type' => 'TStockSerialNumber', 'Caption' => 'Sériové číslo', 'Default' => ''),
        'Text' => array('Type' => 'Text', 'Caption' => 'Text', 'Default' => ''),
      ),
    ));
    $this->System->FormManager->RegisterClass('StockMoveItemSerialRel', array(
      'Title' => 'Vztah položky skladových pohybů a sériových čísel',
      'Table' => 'StockMoveItemSerialRel',
      'Items' => array(
        'StockMoveItem' => array('Type' => 'TStockMoveItem', 'Caption' => 'Položky pohybu', 'Default' => ''),
        'StockSerialNumber' => array('Type' => 'TStockSerialNumber', 'Caption' => 'Sériové číslo', 'Default' => ''),
      ),
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveItemListStockMove', array(
      'Type' => 'ManyToOne',
      'Table' => 'StockMoveItem',
      'Id' => 'Id',
      'Ref' => 'StockMove',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveItemListProduct', array(
      'Type' => 'ManyToOne',
      'Table' => 'StockMoveItem',
      'Id' => 'Id',
      'Ref' => 'Product',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveListGroup', array(
      'Type' => 'ManyToOne',
      'Table' => 'StockMove',
      'Id' => 'Id',
      'Ref' => 'Group',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveStock', array(
      'Type' => 'ManyToOne',
      'Table' => 'StockMove',
      'Id' => 'Id',
      'Ref' => 'Stock',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveItemSerialListItem', array(
      'Type' => 'ManyToOne',
      'Table' => 'StockMoveItemSerialRel',
      'Id' => 'Id',
      'Ref' => 'StockMoveItem',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveItemSerialListSerial', array(
      'Type' => 'ManyToOne',
      'Table' => 'StockMoveItemSerialRel',
      'Id' => 'Id',
      'Ref' => 'StockSerialNumber',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMove', array(
      'Type' => 'Reference',
      'Table' => 'StockMove',
      'Id' => 'Id',
      'Name' => '(SELECT `DocumentLineCode`.`Name` FROM `DocumentLineCode` WHERE `Id`=`StockMove`.`BillCode`)',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveItem', array(
      'Type' => 'Reference',
      'Table' => 'StockMoveItem',
      'Id' => 'Id',
      'Name' => '(SELECT `Name` FROM `Product` WHERE `Product`.`Id`=`StockMoveItem`.`Product`)',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TProduct', array(
      'Type' => 'Reference',
      'Table' => 'Product',
      'Id' => 'Id',
      'Name' => 'Name',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStock', array(
      'Type' => 'Reference',
      'Table' => 'Stock',
      'Id' => 'Id',
      'Name' => 'Name',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockMoveGroup', array(
      'Type' => 'Reference',
      'Table' => 'StockMoveGroup',
      'Id' => 'Id',
      'Name' => 'Name',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockSerialNumber', array(
      'Type' => 'Reference',
      'Table' => 'StockSerialNumber',
      'Id' => 'Id',
      'Name' => 'RegNumber',
      'Filter' => '1',
    ));
    $this->System->FormManager->RegisterFormType('TStockItemHistoryListStockSerialNumber', array(
      'Type' => 'ManyToOne',
      'Table' => 'StockItemHistory',
      'Id' => 'Id',
      'Ref' => 'StockSerialNumber',
      'Filter' => '1',
    ));

    $this->System->FormManager->RegisterFormType('TStockState', array(
      'Type' => 'Enumeration',
      'States' => array('<span style="color:red;">Nedostatek</span>',
        '<span style="color:green;">Dostatek</span>'),
    ));
  }

  function BeforeInsertStockMove(Form $Form): array
  {
    $Finance = &ModuleFinance::Cast($this->System->GetModule('Finance'))->Finance;
    if (array_key_exists('Time', $Form->Values)) $Year = date("Y", $Form->Values['Time']);
      else $Year = date("Y", $Form->Values['ValidFrom']);
    $Group = $Finance->GetFinanceGroupById($Form->Values['Group'], 'StockMoveGroup');
    $Form->Values['BillCode'] = ModuleDocument::Cast($this->System->GetModule('Document'))->GetNextDocumentLineNumberId($Group['DocumentLine'], $Year);
    return $Form->Values;
  }
}

class Product extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddReference('Manufacturer', Subject::GetClassName());
    $Desc->AddString('Code');
    $Desc->AddString('Name');
    $Desc->AddInteger('SellPrice');
    $Desc->AddInteger('BuyPrice');
    $Desc->AddInteger('VAT');
    $Desc->AddInteger('Consumption');
    $Desc->AddReference('Supplier', Subject::GetClassName());
    $Desc->AddReference('UnitOfMeasure', UnitOfMeasure::GetClassName());
    $Desc->AddInteger('StockMinCount');
    return $Desc;
  }
}

class StockSerialNumber extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddReference('Stock', Stock::GetClassName());
    $Desc->AddReference('Product', Product::GetClassName());
    $Desc->AddDate('TimeEnlistment');
    $Desc->AddDate('TimeElimination');
    $Desc->AddInteger('SellPrice');
    $Desc->AddInteger('BuyPrice');
    $Desc->AddInteger('Amount');
    $Desc->AddString('SerialNumber');
    $Desc->AddString('RegNumber');
    $Desc->AddReference('Location', Member::GetClassName());
    $Desc->AddReference('Esemble', StockSerialNumber::GetClassName());
    return $Desc;
  }
}

class Stock extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddString('Name');
    $Desc->AddReference('Location', Member::GetClassName());
    return $Desc;
  }
}

class StockMove extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddReference('Group', StockMoveGroup::GetClassName());
    $Desc->AddDateTime('Time');
    $Desc->AddReference('Stock', Stock::GetClassName());
    $Desc->AddReference('File', File::GetClassName());
    return $Desc;
  }
}

class StockMoveItem extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddReference('StockMove', StockMove::GetClassName());
    $Desc->AddReference('Product', Product::GetClassName());
    $Desc->AddInteger('UnitPrice');
    $Desc->AddInteger('Amount');
    return $Desc;
  }
}

class StockMoveGroup extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddString('Name');
    $Desc->AddReference('DocumentLine', DocumentLine::GetClassName());
    $Desc->AddInteger('ValueSign');
    $Desc->AddInteger('Direction');
    return $Desc;
  }
}

class StockItemHistory extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddReference('StockSerialNumber', StockSerialNumber::GetClassName());
    $Desc->AddDateTime('Time');
    $Desc->AddText('Text');
    return $Desc;
  }
}

class StockMoveItemSerialRel extends Model
{
  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddReference('StockMoveItem', StockMoveItem::GetClassName());
    $Desc->AddReference('StockSerialNumber', StockSerialNumber::GetClassName());
    return $Desc;
  }
}
