<?php

include_once './config.php';
include_once '../env.php';
include_once './log.php';

function orderStatus(){

  global $entityManager;

  $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();
    }
  }

  if (empty($ord)) {
    exit;
  }


  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();
    }
  }

  //finaliza os nulos e adiciona o não
  foreach ($dataOrders as $key => $d) {
    if ($d->getStatusStock() == null) {
      $idStatus[] = $d->getId();
    }
  }

  if (!empty($idStatus)) {
    foreach ($idStatus as $key => $s) {
      $s = $dataOrdersRepository->find($s);
      $s->setStatusStock('nao');
      $entityManager->persist($s);
      $entityManager->flush();
    }
  }

  //finaliza os nulos e adiciona o não
  foreach ($order as $key => $i) {
    if ($i->getProductFabric() == null) {
      $idIt[] = $i->getId();
    }
  }

  if (!empty($idIt)) {
    foreach ($idIt as $key => $t) {
      $t = $ordersRepository->find($t);
      $t->setProductFabric('nao');
      $entityManager->persist($t);
      $entityManager->flush();
    }
  }
}
