<?php
namespace App\Controllers\DB;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

use \App\Controllers\Container;

class OrdersStatusStockDBController extends Container
{
  public function status(Request $request, Response $response, $args){
    $entityManager = $this->container->get('em');

    $ordersRepository = $entityManager->getRepository('App\Models\Entity\OrdersDb');
    $order = $ordersRepository->findAll();

    $itemsRepository = $entityManager->getRepository('App\Models\Entity\ItemsOrderDb');
    $items = $itemsRepository->findAll();

    $dataOrdersRepository = $entityManager->getRepository('App\Models\Entity\DataOrderSellerDb');
    $dataOrders = $dataOrdersRepository->findAll();

    foreach ($order as $o) {
      if ($o->getProductFabric() == null) {
        $ord[] = $o->getOrderId();
      }
    }

    foreach ($items as $i) {
      if (in_array($i->getOrderId() , $ord) && ($i->getStatusStock() == null || $i->getStatusStock() <= 0)) {
        $idItems[] = $i->getOrderId();
      }
    }

    if (!empty($idItems)) {
      foreach ($order as $o) {
        if (in_array($o->getOrderId(), $idItems)) {
          $idOrder[] = $o->getId();
        }
      }

      foreach ($dataOrders as $d) {
        if (in_array($d->getOrderId(), $idItems)) {
          $idDataOrder[] = $d->getId();
        }
      }
    }

    if (!empty($idOrder)) {
      foreach ($idOrder as $key => $id) {
        $id = $ordersRepository->find($id);
        $id->setProductFabric('sim');
        $entityManager->persist($id);
        $entityManager->flush();
      }
    }

    if (!empty($idDataOrder)) {
      foreach ($idDataOrder as $key => $id) {
        $id = $dataOrdersRepository->find($id);
        $id->setStatusStock('sim');
        $entityManager->persist($id);
        $entityManager->flush();
      }
    }
    
  }
}
