<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle("Оформление заказа");
CModule::IncludeModule('iblock');
\Bitrix\Main\UI\Extension::load("ui.alerts");
$IBLOCK_ID = 4;
define("NOT_CHECK_PERMISSIONS", true);

$arBask = json_decode($_COOKIE['basket']);
                  $arBasket = array();
                    foreach ($arBask as $object) {
                      array_push($arBasket, $object->id);
                    }
                  $arBasketFilter = ["ID" => $arBasket];


                  $arFilter = Array("IBLOCK_ID"=>4, "ID"=>$arBasket);?>
                  

<?$arSelect = Array("ID", "IBLOCK_ID", "NAME", "DATE_ACTIVE_FROM","PROPERTY_*");//IBLOCK_ID и ID обязательно должны быть указаны, см. описание arSelectFields выше
$res = CIBlockElement::GetList(Array(), $arFilter, false, Array("nPageSize"=>50), $arSelect);
$wth_discount = 0;
$sum = 0;
$cart_goods = array();
while($ob = $res->GetNextElement()){ 
	$arFields = $ob->GetFields();
  array_push($cart_goods, $arFields["ID"]);
	$arProps = $ob->GetProperties();
	if ($arProps["DISCOUNT"]["VALUE"]){
		$new_price = $arProps["PRICE"]["VALUE"] - ($arProps["PRICE"]["VALUE"] * $arProps["DISCOUNT"]["VALUE"] / 100);
		$wth_discount+=$new_price;
	}
	else{
		$wth_discount+=$arProps["PRICE"]["VALUE"];
	}
	$sum+=$arProps["PRICE"]["VALUE"];
}








if (isset($_POST["submitorder"])){


  //Погнали
  $el = new CIBlockElement;
  $iblock_id = 6;
  $section_id = false;

  //Свойства
  $PROP = array();

  
  $PROP['ADDRESS'] = $_POST['address'];
  $PROP['POST_INDEX'] = $_POST['zip'];
  $PROP['PHONE_NUMBER'] = $_POST['phone'];
  $PROP['EMAIL'] = $_POST['email'];
  $PROP['DISCOUNT_PRICE'] = $_POST['discount'];
  $PROP['PRICE'] = $_POST['price'];
  $PROP['GOODS'] = $cart_goods;

  //Основные поля элемента
  $fields = array(
      "DATE_CREATE" => date("d.m.Y H:i:s"), //Передаем дата создания 
     "IBLOCK_SECTION" => $section_id,
     "IBLOCK_ID" => $iblock_id,
     "PROPERTY_VALUES" => $PROP,
     "NAME" => $_POST["fio"],
     "ACTIVE" => "Y",
     "PREVIEW_TEXT" => $POST["dop_info"], //Анонс
     "PREVIEW_PICTURE" => "", //изображение для анонса
     "DETAIL_TEXT" => strip_tags($_REQUEST['description_detail']),
      "DETAIL_PICTURE" => "", //изображение для детальной страницы
   );
  
   //Результат в конце отработки
   if ($ID = $el ->Add($fields)) {?>
   <div class="ui-alert ui-alert-success">
	  <span class="ui-alert-message"><strong>Успешно!</strong> Заказ был оформлен. Информация направлена на указанный Email</span>
    </div><?
    if (isset($_COOKIE['basket'])){
    setcookie("basket","",time()-3600,"/");
    }
  } else {?>
    <div class="ui-alert ui-alert-danger">
	    <span class="ui-alert-message"><strong>Неудача!</strong> Проверьте правильность заполнения формы.</span>
    </div> 
  <?}
  header("Location: /order"); exit();
}
?>

<?$APPLICATION->IncludeComponent(
	"bitrix:breadcrumb", 
	"top_navigate", 
	array(
		"COMPONENT_TEMPLATE" => "top_navigate",
		"START_FROM" => "0",
		"PATH" => "",
		"SITE_ID" => "s1"
	),
	false
);?>
<section class="checkout-wrap padding-large">
      <div class="container">
      <form name="add_my_ankete" method="POST" enctype="multipart/form-data" class="form-group" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]) ?>">
          <div class="row d-flex flex-wrap">
            <div class="col-lg-6">
              <h3 class="mb-3">Детали заказа</h3>

              <div class="billing-details">
                <label for="fname">ФИО*</label>
                <input type="text" id="fio" name="fio" placeholder="Иванов Иван Иванович" class="form-control mt-2 mb-4 ps-3">
                
                <label for="address">Адрес*</label>
                <input type="text" id="adr" name="address" placeholder="Введите адрес доставки"
                  class="form-control mt-3 ps-3 mb-3">

                <label for="zip">Почтовый индекс *</label>
                <input type="text" id="zip" name="zip" class="form-control mt-2 mb-4 ps-3" placeholder="603053">
                
                
                <label for="phone">Номер телефона *</label>
                <input type="text" id="phone" name="phone" class="form-control mt-2 mb-4 ps-3" placeholder="79009009090">
                <label for="email">Email адрес *</label>
                <input type="email" id="email" name="email" class="form-control mt-2 mb-4 ps-3" placeholder="email@email.ru">
              </div>
            </div>

            <div class="col-lg-6">
              <div>
                <h3 class="mb-3">Дополнительная информация</h3>
                <div class="billing-details">
                  <label for="fname">Сообщение к заказу (необязательно)</label>
                  <textarea class="form-control pt-3 pb-3 ps-3 mt-2" name="dop_info"
                    placeholder="Примечания к заказу"></textarea>
                </div>
              </div>

              <div class="cart-totals padding-medium pb-0">
                <h3 class="mb-3">Сумма заказа</h3>
                <div class="total-price pb-3">
                  <table cellspacing="0" class="table text-capitalize">
                    <tbody>
                      <tr class="subtotal pt-2 pb-2 border-top border-bottom">
                        <th>Без скидки</th>
                        <td data-title="Subtotal">
                          <span class="price-amount amount text-primary ps-5 fw-light">
                            <bdi>
                              <?=$sum;?> <span class="price-currency-symbol">₽</span>
                            </bdi>
                          </span>
                        </td>
                        <input type="hidden" name="discount" value="<?=$sum;?>">
                      </tr>
                      <tr class="order-total pt-2 pb-2 border-bottom">
                        <th>Итог</th>
                        <td data-title="Total">
                          <span class="price-amount amount text-primary ps-5 fw-light">
                            <bdi>
                              <?=$wth_discount;?> <span class="price-currency-symbol">₽</span></bdi>
                          </span>
                        </td>
                        <input type="hidden" name="price" value="<?=$wth_discount;?>">
                      </tr>
                    </tbody>
                  </table>
                </div>
                
                <div class="button-wrap mt-3">
                  <button type="submit" name="submitorder" class="btn">Оформить заказ</button>
                </div>
              </div>

            </div>

          </div>
        </form>
      </div>
    </section>




























<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>