· 5 years ago · Feb 18, 2021, 03:22 PM
1<?php
2
3namespace App\FrontModule;
4
5use App\Model\APIBackend;
6use App\Model\Cart;
7use App\Model\GiftVoucher;
8use App\Model\Log;
9use App\Model\Order;
10use App\Model\Product;
11use App\Model\UserManager;
12use Nette\Application\UI\Form;
13use Nette\Utils\ArrayHash;
14use Nette\Utils\DateTime;
15use Nette\Utils\Strings;
16use Tracy\Debugger;
17
18class CartPresenter extends BasePresenter
19{
20
21
22 /** @var IHomepageListControlFactory @inject */
23 public $homePageListControl;
24
25 /** @var Product @inject */
26 public $product;
27
28 /** @var Order @inject */
29 public $order;
30
31 /** @var UserManager @inject */
32 public $userNamager;
33
34 /** @var GiftVoucher @inject */
35 public $giftVoucher;
36
37 /** @var APIBackend @inject */
38 public $api;
39
40 /** @var Cart @inject */
41 public $cart;
42
43 /** @var Log @inject */
44 public $log;
45
46 private $wishes;
47 private $payCredit;
48
49 public $refProduct = [];
50
51 private $carrier = [];
52
53 private $isElBookInCart, $isPaperBookInCart;
54
55 private $freeDelivery = 799;
56
57 private $completeOrder = true;
58
59 private $priceDelivery = 0;
60
61 public function beforeRender()
62 {
63 $buyNoLogged = true;
64 $_wishes = array();
65 $this->removeNoStock();
66 foreach ($this->product->getUsersWishesIds($this->getUser()->id) as $value) {
67 $_wishes[] = $value['book_id'];
68 }
69 foreach ($this->databaseB->select('*')->from('delivery_methods')->where('active = %i', 1)->fetchAll() as $carrier) {
70 $this->carrier[$carrier['code']] = [
71 'id' => $carrier['id'],
72 'price' => $carrier['price'],
73 'title' => $carrier['name'],
74 'points' => $carrier['points'],
75 'desc' => 'POPIS',
76 'logo' => 'https://www.seekpng.com/png/detail/76-765297_marlboro-gold-100-20-200-placeholder-image-png.png'
77 ];
78 }
79
80 $this->wishes = $_wishes;
81 if ($this->getUser()->isLoggedIn()) {
82 $this->userNamager->updateUserInfoBe($this->getUser()->id);
83 $this->getUser()->identity->credits = $this->userNamager->getCreditsById($this->getUser()->id);
84 unset($this->getSession('cart')->items);
85 unset($this->getSession('cart')->credit);
86 //unset($this->getSession('cart')->sale);
87 if (empty($this->getSession("cart")->sale)) {
88 if ($row = $this->cart->getCartSale($this->getUser()->id)) {
89 if (!empty($row->books_id)) {
90 $this->getSession("cart")->offsetSet("sale_id_book", [$row->books_id]);
91 }
92 $this->getSession("cart")->offsetSet("sale", (int)$row->sale);
93 $this->getSession("cart")->offsetSet("sale_type", $row->sale_type);
94 }
95 }
96 foreach ($this->cart->getUserBasketById($this->getUser()->id) as $item) {
97 if (!empty($item["id_voucher_motiv"])) {
98 if (empty($this->getPresenter()->getSession('cart')->items[$item["id_voucher_motiv"] . "-" . $item["order_type"] . "-" . $item["voucher_price"] . "-" . $item["text"]])) {
99 $url = $this->cart->buildBuyUrl($item);
100 $this->getPresenter()->handleBuyItem($url, true);
101 }
102 } elseif (!empty($item['credit'])) {
103 $this->getSession('cart')->credit = $item['credit'];
104 } else {
105 if (empty($this->getPresenter()->getSession('cart')->items[$item["id_book"] . "-" . $item["order_type"]])) {
106 if (empty($this->product->getBooksById($item["id_book"])['id'])) {
107 unset($this->getSession('cart')->items[$item["id_book"] . "-" . $item["order_type"]]);
108 $this->cart->removeByUser(
109 $this->getUser()->id,
110 array("id_book" => $item["id_book"], "order_type" => $item["order_type"])
111 );
112 } elseif (!$this->product->hasValidLicence($item["id_book"])) {
113 unset($this->getSession('cart')->items[$item["id_book"] . "-" . $item["order_type"]]);
114 $this->cart->removeByUser(
115 $this->getUser()->id,
116 array("id_book" => $item["id_book"], "order_type" => $item["order_type"])
117 );
118 } else {
119 $url = $this->cart->buildBuyUrl($item);
120 if(empty($item['quantity'])){
121 $item['quantity'] = 1;
122 }
123 $this->getPresenter()->handleBuyItem($url, true, false, null, $item['quantity']);
124 }
125 }
126 }
127 }
128 } else {
129 if (!empty($this->getPresenter()->getSession('cart')->items)) {
130 foreach ($this->getPresenter()->getSession('cart')->items as $item => $quantity) {
131 if (explode('-', $item)[1] == "cart" || explode('-', $item)[1] == "pack") {
132 $buyNoLogged = false;
133 }
134 $id_book = explode("-", $item)[0];
135 $voucher = false;
136 if (!empty(explode("-", $item)[1]) && explode("-", $item)[1] == "gVoucher") {
137 $voucher = true;
138 }
139 if (!$voucher) {
140 if (!$this->product->hasValidLicence($id_book)) {
141 unset($this->getSession('cart')->items[$item]);
142 }
143 }
144 }
145 }
146 }
147
148 $this->template->buyNoLogged = $buyNoLogged;
149 }
150
151
152 public function renderDefault()
153 {
154 $inCart = [];
155 $gVouchersInCart = [];
156 $priceWoDph = 0;
157 $priceDph = 0;
158 $priceSum = 0;
159 $priceSumNoSale = 0;
160 $priceSumFullNoSale = 0;
161 $sumCart = 0;
162 $showModal = false;
163 $saleBook = "";
164
165 $isPaperBookInCart = false;
166
167
168 $salesUsed = [];
169 Debugger::barDump($this->getSession('cart')->code);
170 if (!empty($this->getSession('cart')->credit) && !empty($this->getSession('cart')->items)) {
171 $this->template->showModalNoBuy = true;
172 unset($this->getSession('cart')->credit);
173 $this->databaseB->delete('cart')->where('id_user = %i AND credit IS NOT NULL', $this->getUser()->id)->execute();
174 }
175
176 if (!empty($this->getSession('cart')->items)) {
177 foreach ($this->getSession('cart')->items as $id => $pcs) {
178 $sumCart += $pcs;
179 if (explode('-', $id)[1] == "paper") {
180 $isPaperBookInCart = true;
181 }
182 if (explode("-", $id)[1] == "gVoucher") {
183 $book = $this->giftVoucher->getVoucherById(explode("-", $id)[0]);
184 $book["price"] = explode("-", $id)[2];
185 $book["text"] = urldecode(explode("-", $id)[3]);
186 $book["pcs"] = $pcs;
187 $book["urlRemove"] = $id;
188 $gVouchersInCart[] = $book;
189 } else {
190 $idBook = explode('-', $id)[0];
191 $book = $this->product->getBooksById($idBook);
192 $book["pcs"] = $pcs;
193 $book["urlRemove"] = $id;
194 if (explode("-", $id)[1] == "pack") {
195 $bookLibDup = array();
196 $bookInPack = $this->product->getBookInPack(explode("-", $id)[0]);
197 foreach ($bookInPack as $idBook) {
198 if ($this->userNamager->checkLibraryIdBook($this->getUser()->id, $idBook)) {
199 $bookLibDup[] = $this->product->getBookTitleById($idBook);
200 }
201 }
202 $title = "";
203
204 foreach ($bookLibDup as $key => $value) {
205 $title .= $value;
206 if (next($bookLibDup) == true) {
207 $title .= ",";
208 }
209 }
210
211 $book['books_lib_dup'] = $title;
212 }
213 $inCart[] = $book;
214 }
215
216 $tmpPrice = (isset($book["price_sale"]) ? round($book["price_sale"]) : round($book["price"])) * $book['pcs'];
217 $priceSumFullNoSale += $tmpPrice;
218 if (explode("-", $id)[1] != "gVoucher") {
219 $priceSumNoSale += $tmpPrice;
220 }
221 if (explode("-", $id)[1] != "gVoucher") {
222 if (isset($this->getSession("cart")->sale_id_book)) {
223 foreach ($this->getSession("cart")->sale_id_book as $book_id) {
224 if ($book_id == $book['id']) {
225 if (isset($salesUsed[$book_id])) {
226 continue;
227 } else {
228 $salesUsed[$book_id] = true;
229 }
230 $saleBook = $book['title'];
231 if ($this->getSession("cart")->sale_type == "percent") {
232 $sale = $this->getSession("cart")->sale;
233 $tmpPrice = round(round($tmpPrice) * ((100 - $sale) / 100));
234 } else {
235 $sale = $this->getSession("cart")->sale;
236 $tmpPrice = round(round($tmpPrice) - $sale);
237 }
238 $book["price_sale"] = $tmpPrice;
239 }
240 }
241 }
242 }
243 $tmpPrice = round($tmpPrice);
244 $priceSum += $tmpPrice * $book["pcs"];
245 $priceDph += $tmpPrice - ($tmpPrice / 1.1) * $book["pcs"];
246 $priceWoDph += ($tmpPrice / 1.1) * $book["pcs"];
247 }
248 }
249
250 if (((!empty($this->getSession('cart')->sale) && empty($this->getSession('cart')->sale_id_book))
251 && !empty($this->getSession('cart')->credit))
252 || ((!empty($this->getSession('cart')->sale) && empty($this->getSession('cart')->sale_id_book))
253 && !empty($gVouchersInCart))) {
254 $showModal = true;
255 $this->template->canContinue = true;
256 //$this->template->canContinue = false;
257 } else {
258 $this->template->canContinue = true;
259 }
260
261 $priceSum = $this->getBooksPricesForCartNew();
262
263 $bundleInfo = [];
264 foreach ($inCart as $bk) {
265 if ($bk['type'] == "bundle") {
266 $bundle = $this->product->getBooksById($bk['id'])->toArray();
267 $priceBundle = round($bundle['price']);
268 $priceBookInBundle = 0;
269 $priceTotalBookSingle = 0;
270 $bookInLibrary = [];
271 foreach ($this->product->getBundleBooksIds($bk['id']) as $booksInBundle) {
272 $book = $this->product->getBooksById($booksInBundle['book_id']);
273 $priceTotalBookSingle += round($book['price']);
274 if ($this->user->checkLibraryIdBook($this->getUser()->id, $booksInBundle['book_id'])) {
275 $priceBookInBundle += round($book['price']);
276 $bookInLibrary[] = $book['title'];
277 }
278 }
279 if (!empty($bookInLibrary)) {
280 if (count($bookInLibrary) == 1) {
281 $text = "Knihu " . $bookInLibrary[0];
282 } else {
283 $text = "Knihy " . implode(', ', $bookInLibrary[0]);
284 }
285 if (($priceTotalBookSingle - $priceBookInBundle) > $priceBundle) {
286 $diference = ($priceTotalBookSingle - $priceBookInBundle) - $priceBundle;
287 $text .= " již máte v knihovně, přesto koupí tohoto balíčku ušetříte <strong>" . $diference . " Kč</strong>.";
288 } else {
289 $diference = $priceBundle - ($priceTotalBookSingle - $priceBookInBundle);
290 $text .= " již máte v knihovně, koupí tohoto balíčku zaplatíte o <strong>" . $diference . " Kč</strong> víc, než při nákupu jednotlivých knih.";
291 }
292 }
293 if (!empty($text)) {
294 $bundleInfo[$bk['id']] = $text;
295 }
296 }
297 }
298
299
300 if (!empty($this->getUser()->identity->id)) {
301 $buyNoLogged = true;
302 }
303
304 if (!$this->isAjax() || !isset($this->template->showModalCart)) {
305 $this->template->showModalCart = $showModal;
306 }
307
308 $noStock = $this->updateStock();
309 if (!empty($noStock)) {
310 foreach ($noStock as $id => $quantity) {
311 }
312 }
313
314 $this->template->isPaperBookInCart = $isPaperBookInCart;
315 $this->template->sumCart = is_array($this->getPresenter()->getSession('cart')->items) ? array_sum($this->getPresenter()->getSession('cart')->items) + (isset($this->getPresenter()->getSession('cart')->credit) ? 1 : 0) : 0;
316 $this->template->priceSumFullNoSale = $priceSumFullNoSale;
317 $this->template->inBundle = $bundleInfo;
318 $this->template->inCart = $inCart;
319 $this->template->gVouchersInCart = $gVouchersInCart;
320 $this->template->priceWoDph = $priceWoDph;
321 $this->template->priceDph = $priceDph;
322 $this->template->priceSum = $priceSum;
323 $this->template->priceSumNoSale = $priceSumNoSale;
324 $this->template->product = $this->product;
325 $this->template->sale = $this->getSession("cart")->sale;
326 $this->template->sale_type = $this->getSession("cart")->sale_type;
327 $this->template->sale_id_book = $this->getSession("cart")->sale_id_book;
328 $this->template->saleBook = $saleBook;
329
330
331 if ($this->getUser()->isLoggedIn()) {
332 $type = $this->databaseB->select('test_grp')->from('pk_puser')->where('id = %i', $this->getUser()->getId())->fetchSingle();
333 if ($type == 3) {
334 if (empty($inCart)) {
335 $bkApi = $this->api->getGprBooks($this->getUser()->getId(), 0, 6);
336 if (!empty($bkApi)) {
337 $books = $this->product->getBooksByIdsNoOrder(array_slice($bkApi, 0, 6));
338 }
339 } else {
340 $booksIds = [];
341 foreach ($inCart as $in) {
342 $booksIds[] = $in['id'];
343 }
344 $bksApi = $this->api->getGprBooksByBooks($this->getUser()->getId(), implode(',', $booksIds), 0, 6);
345 if (!empty($bkApi)) {
346
347 $books = $this->product->getBooksByIdsNoOrder(array_slice($bksApi, 0, 6));
348 }
349 }
350 } elseif ($type == 2) {
351 $books = [];
352 if (!empty($this->refProduct)) {
353 $books = $this->refProduct;
354 }
355
356 }
357 }
358 if (!isset($books)) {
359 if (!$this->isAjax()) {
360 $this->template->results = $this->getRecommendedBooks($inCart);
361 $this->cache->save('resultRecomended', $this->getRecommendedBooks($inCart));
362 } else {
363 if (!empty($re = $this->cache->load('resultRecomended'))) {
364 $this->template->results = $re;
365 } else {
366 $this->template->results = $this->getRecommendedBooks($inCart);
367 $this->cache->save('resultRecomended', $this->getRecommendedBooks($inCart));
368 }
369 }
370 } else {
371 $this->template->results = $books;
372 }
373// if(!empty($type)){
374// $this->template->type = $type;
375// }else{
376 $this->template->type = 1;
377// }
378 $this->template->creditCart = $this->getSession('cart')->credit ?? 0;
379 $this['breadCrumb']->addLink("Košík", ["Cart:default"]);
380 }
381
382 public function handleGetBookById(array $ids)
383 {
384 $this->refProduct = $this->product->getBooksByIds($ids);
385 $this->redrawControl('prodRef');
386 }
387
388 public function removeNoStock()
389 {
390 if (!empty($removesCart = $this->updateStock())) {
391 $name = [];
392 $this->completeOrder = false;
393 foreach ($removesCart as $removeCart) {
394 if (empty($this->getSession('cart')->items[$removeCart['id'] . '-paper'])) {
395 continue;
396 }
397 $name[$removeCart['id']] = [
398 'stock' => $removeCart['stock'],
399 'name' => $this->databaseB->select('title')->from('books')->where('id = %i', $removeCart['id'])->fetchSingle(),
400 'id' => $removeCart['id']
401
402 ];
403 if ($removeCart['stock'] <= 0) {
404 unset($this->getSession('cart')->items[$removeCart['id'] . '-paper']);
405 if ($this->getUser()->isLoggedIn()) {
406 $this->databaseB->delete('cart')->where('id_book = %i AND id_user = %i', $removeCart['id'], $this->getUser()->getId())->execute();
407 }
408 continue;
409 }
410 $this->getSession('cart')->items[$removeCart['id'] . '-papar'] = $removeCart['stock'];
411 if ($this->getUser()->isLoggedIn()) {
412 $this->databaseB->update('cart', ['quantity' => $removeCart['stock']])->where('id_book = %i AND id_user = %i', $removeCart['id'], $this->getUser()->getId())->execute();
413 }
414 }
415 $this->template->productRemove = $name;
416 $this->redrawControl('productRemove');
417 }
418 }
419
420 public function getRecommendedBooks($inCart)
421 {
422 $ids = [];
423 foreach ($inCart as $book) {
424 $ids[] = $book['id'];
425 }
426 if ($this->getUser()->isLoggedIn()) {
427 foreach ($this->user->getAllBookInLibraryByIdUser($this->getUser()->getId()) as $id => $state) {
428 $ids[] = $id;
429 }
430 }
431 return $this->cache->call([$this->product, 'getRecommendedBooks'], $ids, $limit = 12);
432 }
433
434
435 public function renderPayment()
436 {
437 if (empty($this->getSession('cart')->items) && empty($this->getSession('cart')->credit)) {
438 $this->redirect('Cart:default');
439 }
440
441 $date = new DateTime('2021-01-04 00:00');
442 $this->template->date = $date->getTimestamp();
443
444 $this->template->vip = $this->user->getVipById($this->getUser()->id);
445 $inCart = [];
446 $gVouchersInCart = [];
447 $priceWoDph = 0;
448 $priceDph = 0;
449 $priceSum = 0;
450 $priceSumNoPaper = 0;
451 $priceSumNoSale = 0;
452 $priceSumFullNoSale = 0;
453 $sumCart = 0;
454 $payCredit = 0;
455 $onlyPayCredit = false;
456 $buyNoLogged = true;
457 $address = false;
458 $isPaperBookInCart = false;
459 $isElBookInCart = false;
460
461 if(!$this->isAjax()){
462 unset($this->getSession('order')->data);
463 }
464 if (!empty($this->getSession('cart')->items)) {
465 if (!empty($this->getSession('cart')->items)) {
466 foreach ($this->getSession('cart')->items as $id => $pcs) {
467 if (explode('-', $id)[1] == "cart" || explode('-', $id)[1] == "pack") {
468 $buyNoLogged = false;
469 }
470 if (explode('-', $id)[1] == "paper") {
471 $address = true;
472 $isPaperBookInCart = true;
473 } else {
474 $isElBookInCart = true;
475 }
476 $sumCart += $pcs;
477 if (explode("-", $id)[1] == "gVoucher") {
478 $book = $this->giftVoucher->getVoucherById(explode("-", $id)[0]);
479 $book["price"] = explode("-", $id)[2];
480 $book["text"] = urldecode(explode("-", $id)[3]);
481 $book["pcs"] = $pcs;
482 $book["urlRemove"] = $id;
483 $gVouchersInCart[] = $book;
484 } else {
485 $idBook = explode('-', $id)[0];
486 $book = $this->product->getBooksById($idBook);
487 $book["pcs"] = $pcs;
488 $book["urlRemove"] = $id;
489 if (explode("-", $id)[1] == "pack") {
490 $bookLibDup = array();
491 $bookInPack = $this->product->getBookInPack(explode("-", $id)[0]);
492 foreach ($bookInPack as $idBook) {
493 if ($this->userNamager->checkLibraryIdBook($this->getUser()->id, $idBook)) {
494 $bookLibDup[] = $this->product->getBookTitleById($idBook);
495 }
496 }
497 $title = "";
498
499 foreach ($bookLibDup as $key => $value) {
500 $title .= $value;
501 if (next($bookLibDup) == true) {
502 $title .= ",";
503 }
504 }
505
506 $book['books_lib_dup'] = $title;
507 }
508 $inCart[] = $book;
509 }
510 $tmpPrice = (isset($book["price_sale"]) ? round($book["price_sale"]) : round($book["price"])) * $book['pcs'];
511 $priceSumFullNoSale += $tmpPrice;
512 if (explode("-", $id)[1] != "gVoucher") {
513 $priceSumNoSale += $tmpPrice;
514 }
515 if (explode("-", $id)[1] != "gVoucher") {
516 if (isset($this->getSession("cart")->sale_id_book)) {
517 foreach ($this->getSession("cart")->sale_id_book as $book_id) {
518 if ($book_id == $book['id']) {
519 if ($this->getSession("cart")->sale_type == "percent") {
520 $sale = $this->getSession("cart")->sale;
521 $tmpPrice = round($tmpPrice) * ((100 - $sale) / 100);
522 } else {
523 $sale = $this->getSession("cart")->sale;
524 $tmpPrice = round($tmpPrice) - $sale;
525 }
526 $book["price_sale"] = $tmpPrice;
527 }
528 }
529 }
530 }
531 if (explode("-", $id)[1] != "gVoucher") {
532 $payCredit += round($tmpPrice);
533 }
534 $tmpPrice = round($tmpPrice);
535 if (explode("-", $id)[1] != "paper") {
536 $priceSumNoPaper += $tmpPrice * $book["pcs"];
537 }
538 $priceSum += $tmpPrice * $book["pcs"];
539 $priceDph += $tmpPrice - round(($tmpPrice / 1.1)) * $book["pcs"];
540 $priceWoDph += round($tmpPrice / 1.1) * $book["pcs"];
541 }
542 }
543 }
544
545 if ($this->getSession("cart")->sale_type == "percent") {
546 $sale = $this->getSession("cart")->sale;
547 $priceSum = round($priceSumNoPaper) * ((100 - $sale) / 100);
548 } else {
549 $sale = $this->getSession("cart")->sale;
550 $priceSum = round($priceSumNoPaper) - $sale;
551 }
552 $priceSum = $this->getBooksPricesForCartNew();
553
554 if(!empty($this->getSession('order')->data['typeCarrier'])){
555 $carrier = $this->getSession('order')->data['typeCarrier'];
556 if($priceSum <= $this->freeDelivery){
557 $priceSum += $this->carrier[$carrier]['price'];
558 $this->template->deliveryPrice = $this->carrier[$carrier]['price'];
559 }
560 }
561 if(!empty($this->getSession('order')->data['typePayment'])){
562 $payment = $this->getSession('order')->data['typePayment'];
563 if($priceSum <= $this->freeDelivery){
564 if($payment == 'cod'){
565 $priceSum += 39;
566 $this->template->cod = 39;
567 }
568 }
569 }
570
571 $bundleInfo = [];
572 foreach ($inCart as $bk) {
573 if ($bk['type'] == "bundle") {
574 $bundle = $this->product->getBooksById($bk['id'])->toArray();
575 $priceBundle = round($bundle['price']);
576 $priceBookInBundle = 0;
577 $priceTotalBookSingle = 0;
578 $bookInLibrary = [];
579 foreach ($this->product->getBundleBooksIds($bk['id']) as $booksInBundle) {
580 $book = $this->product->getBooksById($booksInBundle['book_id']);
581 $priceTotalBookSingle += round($book['price']);
582 if ($this->user->checkLibraryIdBook($this->getUser()->id, $booksInBundle['book_id'])) {
583 $priceBookInBundle += round($book['price']);
584 $bookInLibrary[] = $book['title'];
585 }
586 }
587 if (!empty($bookInLibrary)) {
588 if (count($bookInLibrary) == 1) {
589 $text = "Knihu " . $bookInLibrary[0];
590 } else {
591 $text = "Knihy " . implode(', ', $bookInLibrary[0]);
592 }
593 if (($priceTotalBookSingle - $priceBookInBundle) > $priceBundle) {
594 $diference = ($priceTotalBookSingle - $priceBookInBundle) - $priceBundle;
595 $text .= " již máte v knihovně, přesto koupí tohoto balíčku ušetříte <strong>" . $diference . " Kč</strong>.";
596 } else {
597 $diference = $priceBundle - ($priceTotalBookSingle - $priceBookInBundle);
598 $text .= " již máte v knihovně, koupí tohoto balíčku zaplatíte o <strong>" . $diference . " Kč</strong> víc, než při nákupu jednotlivých knih.";
599 }
600 }
601 if (!empty($text)) {
602 $bundleInfo[$bk['id']] = $text;
603 }
604
605 $payCredit += $priceBundle;
606
607 }
608 }
609
610 if (!empty($this->getUser()->identity->id)) {
611 $buyNoLogged = true;
612 }
613
614 if ($this->getUser()->isLoggedIn()) {
615 if ($this->getUser()->getIdentity()->credits >= $priceSum) {
616 $onlyPayCredit = true;
617 $payCredit = $priceSum;
618 } else {
619 $payCredit = $this->getUser()->getIdentity()->credits;
620 }
621 if (empty($crdHelp = $this->getSession('cart')->credit)) {
622 $crdHelp = 0;
623 }
624 if (($sumCreditPay = $priceSum + $crdHelp - $payCredit) < 10) {
625 $payCredit = $payCredit - (10 - $sumCreditPay);
626 $this->template->showMsgPayment = true;
627 }
628 } else {
629 $onlyPayCredit = false;
630 $payCredit = 0;
631 }
632
633 if (isset($this->getSession('cart')->credit) || !empty($gVouchersInCart)) {
634 $payCredit = 0;
635 $onlyPayCredit = false;
636 }
637
638
639 if (!empty($inCart) || !empty($gVouchersInCart) || !empty($creditCart)) {
640 if (!$this->getUser()->isLoggedIn() && !$buyNoLogged) {
641 $this->redirect('Cart:default');
642 }
643 }
644 $this->isElBookInCart = $isElBookInCart;
645 $this->isPaperBookInCart = $isPaperBookInCart;
646
647
648
649
650
651 $this->template->carriers = $this->carrier;
652 $this->template->isElBookInCart = $isElBookInCart;
653 $this->template->isPaperBookInCart = $isPaperBookInCart;
654
655 $this->payCredit = $payCredit;
656 $this->template->address = $address;
657 $this->template->payCredit = $payCredit;
658 $this->template->onlyPayCredit = $onlyPayCredit;
659 $this->template->sumCart = isset($this->getSession('cart')->credit) ? $sumCart + 1 : $sumCart;
660 $this->template->priceSumFullNoSale = $priceSumFullNoSale;
661 $this->template->inBundle = $bundleInfo;
662 $this->template->inCart = $inCart;
663 $this->template->gVouchersInCart = $gVouchersInCart;
664 $this->template->priceWoDph = $priceWoDph;
665 $this->template->priceSumNoSale = $priceSumNoSale;
666 $this->template->priceDph = $priceDph;
667 $this->template->priceSum = $priceSum;
668 $this->template->sale = $this->getSession("cart")->sale;
669 $this->template->sale_type = $this->getSession("cart")->sale_type;
670 $this->template->creditCart = $this->getSession('cart')->credit ?? 0;
671 $this->template->useCredit = $this->getSession('cart')->use_credit ?? false;
672 $this->template->paymentsExternal = $payExternal = $this->databaseB->select("id,id_api,name,description,logo")->from("payments")->where('extra = %i', 0)->fetchAll();
673 $exTernal = [];
674 foreach ($payExternal as $p){
675 if($p['id_api'] != "comgate::CARD_CZ_CSOB_2"){
676 $exTernal[] = $p['id_api'];
677 }
678 }
679 $this->template->paymentsExternalApiName = $exTernal;
680 $this->template->cardPay = $this->databaseB->select('id,id_api,name,description,logo')->from('payments')->where('id_api = %s', 'comgate::CARD_CZ_CSOB_2')->fetch();
681 $this->template->paypal = $this->databaseB->select('id,id_api,name,description,logo')->from('payments')->where('id_api = %s', 'paypal')->fetch();
682 $this->template->credit = $this->databaseB->select('id,id_api,name,description,logo')->from('payments')->where('id_api = %s', 'credit')->fetch();
683 $this->template->vipPay = $this->databaseB->select('id,id_api,name,description,logo')->from('payments')->where('id_api = %s', 'vip')->fetch();
684 $this->template->addressData = $this->getSession('order')->data;
685 $this->template->freeDelivery = $this->freeDelivery;
686 if($this->getUser()->isLoggedIn()){
687 $this->template->country_change_required = strtoupper($this->user->getCountry($this->getUser()->getIdentity()->getId())) != "CZ";
688 }else{
689 $this->template->noLoggedCountyShow = true;
690 }
691 }
692
693 public function handleFindDeliveryPoints($delivery_id, $text)
694 {
695 $data = explode(' ', $text);
696 $query = [];
697 foreach ($data as $d) {
698 if (!empty($d)) {
699 $query[] = $this->databaseB->translate('custom_search LIKE %~like~', $d);
700 }
701 }
702 if (empty($query)) {
703 return $this->sendJson(json_encode([]));
704 }
705 $result = $this->databaseB->select('custom_search AS name,id')->from('delivery_points')
706 ->where('delivery_id = %i AND active = %i', $delivery_id, 1)
707 ->where('(%sql)', implode(' AND ', $query))
708 ->limit(10)->fetchAll();
709 return $this->sendJson(json_encode($result));
710 }
711
712 public function handleSetPoint()
713 {
714
715 }
716
717 public function renderComplete($id)
718 {
719 if (!empty($id) && $this->order->getTypeOrder(str_replace('fe-', '', $id)) > 0) {
720 $this->redirect("Credits:complete", $id);
721 }
722
723 if (empty($id)) {
724 if (empty($this->getSession('cart')->items)) {
725 $this->redirect("Homepage:");
726 }
727 $priceSum = 0;
728 foreach ($this->getSession('cart')->items as $id => $pcs) {
729 $idBook = explode('-', $id)[0];
730 $book = $this->product->getBooksById($idBook);
731 $book["pcs"] = $pcs;
732 $tmpPrice = (isset($book["price_sale"]) ? $book["price_sale"] : $book["price"]);
733 if ($this->getSession("cart")->sale_type == "percent") {
734 $sale = $this->getSession("cart")->sale;
735 $tmpPrice = $tmpPrice * ((100 - $sale) / 100);
736 } else {
737 $sale = $this->getSession("cart")->sale;
738 $tmpPrice = round($tmpPrice) - $sale;
739 }
740 $priceSum += $tmpPrice * $book["pcs"];
741 }
742
743 $priceSum = $this->product->getBooksPricesForCartNew($this->getSession('cart')->items, $this->getSession('cart'));
744
745
746 if ($priceSum != 0) {
747 $this->redirect("Homepage:");
748 }
749
750 if (empty($this->getUser()->getIdentity()->id)) {
751 $this->redirect("Homepage:");
752 }
753
754 $this->getSession('cart')->payment = "comgate";
755 if (!$this->getUser()->isLoggedIn()) {
756 return $this->flashMessage('Chyba', 'error');
757 }
758// if(empty($address = $this->api->getLastAdress($this->getUser()->id))){
759// return $this->flashMessage('Chyba','error');
760// }
761
762 $redir = $this->order->createOrder($this->getSession('cart'), $this->getUser()->id, null, null);
763 $this->cart->removeAllByUser($this->getUser()->id);
764 unset($this->getSession('cart')->credit);
765 //$this->log->addMessage($this->getUser()->id, "Vytvořena objednávka " . $redir['id'], $this->getSession('cart'));
766
767 if (empty($redir["pay_redir"])) {
768 $this->redirect("Cart:complete", "fe-" . $redir["id"]);
769 }
770 $this->redirectUrl($redir["pay_redir"]);
771 }
772
773 $orderedOwn = false;
774 $orderedGift = false;
775
776 $data = $this->api->checkOrder($this->getUser()->id);
777 if ($this->getUser()->isLoggedIn()) {
778 $this->userNamager->updateUserInfoBe($this->getUser()->id);
779 $this->userNamager->updateUserLibraryBeNew($this->getUser()->id);
780 }
781
782 //$this->log->addMessage($this->getUser()->id, "Zkontrolována objednávka " . $id, $data);
783 $credit = false;
784 $voucher = false;
785 $idOrder = null;
786 if (!empty($data)) {
787 Debugger::barDump($data);
788 $is_array = true;
789 foreach ($data as $d) {
790 if (!is_array($d)) {
791 $is_array = false;
792 break;
793 }
794 if (!empty($d["extern_id"])) {
795 if ($d["extern_id"] == $id) {
796 $idOrder = $d["id"];
797 foreach ($d["books"] as $b) {
798 if ($b["type"] == "own") {
799 $orderedOwn = true;
800 } elseif ($b["type"] == "gift") {
801 $orderedGift = true;
802 }
803 if ($b['id_book'] == 174342 && $b['type'] == "own") {
804 $credit = true;
805 }
806 if ($b['type'] == "gift") {
807 $voucher = true;
808 }
809 }
810 if ($d["state"] == "valid") {
811 $this->order->changeState($d["id"], "Vyřízeno");
812 $this->log->addMessage($this->getUser()->id, "Změněn stav objednávky: Vyřízeno", $data);
813 } elseif ($d["state"] == "cancel") {
814 $this->order->changeState($d["id"], "Zrušeno");
815 $this->log->addMessage($this->getUser()->id, "Změněn stav objednávky: Zrušeno", $data);
816 } else {
817 $this->order->changeState($d["id"], "Čeká na platbu");
818 $this->log->addMessage(
819 $this->getUser()->id,
820 "Změněn stav objednávky: Čeká na platbu",
821 $data
822 );
823 $this->getSession("cart")->recentOrder = true;
824 }
825 }
826 }
827 }
828 if (!$is_array) {
829 $d = $data;
830 $tmp = [];
831 $tmp[] = $data;
832 $data = $tmp;
833 if (!empty($d["extern_id"])) {
834 if ($d["extern_id"] == $id) {
835 $idOrder = $d["id"];
836 foreach ($d["books"] as $b) {
837 if ($b["type"] == "own") {
838 $orderedOwn = true;
839 } elseif ($b["type"] == "gift") {
840 $orderedGift = true;
841 }
842 Debugger::barDump($b);
843 }
844 if ($d["state"] == "valid") {
845 $this->order->changeState($d["id"], "Vyřízeno");
846 $this->log->addMessage($this->getUser()->id, "Změněn stav objednávky: Vyřízeno", $data);
847 } elseif ($d["state"] == "cancel") {
848 $this->order->changeState($d["id"], "Zrušeno");
849 $this->log->addMessage($this->getUser()->id, "Změněn stav objednávky: Zrušeno", $data);
850 } else {
851 $this->order->changeState($d["id"], "Čeká na platbu");
852 $this->log->addMessage(
853 $this->getUser()->id,
854 "Změněn stav objednávky: Čeká na platbu",
855 $data
856 );
857 $this->getSession("cart")->recentOrder = true;
858 }
859 }
860 }
861 }
862 }
863
864 $orderSent = false;
865
866 if (empty($this->getSession("sent_orders")->orders)) {
867 $this->getSession("sent_orders")->orders = [];
868 }
869
870 if (in_array($idOrder, $this->getSession("sent_orders")->orders)) {
871 $orderSent = true;
872 }
873
874
875 $orderPay = $this->order->getOrderState($idOrder);
876// if (!$orderSent && $orderPay != "credit" || empty($orderPay)) {
877// $heurekaUrl = "https://www.heureka.cz/direct/dotaznik/objednavka.php?id=ed08e3c121a088221172baf3f4f17d83";
878// $heurekaUrl .= "&email=" . $this->getUser()->getIdentity()->email;
879//
880// foreach ($data as $d) {
881// if ($d['id'] == $idOrder) {
882// foreach ($d["books"] as $book) {
883// $heurekaUrl .= '&itemId[]=' . $book['id_book'];
884// }
885// $heurekaUrl .= "&orderid=" . $idOrder;
886//
887// Debugger::barDump($heurekaUrl);
888//
889// $text = $heurekaUrl . "\r\n";
890// file_put_contents('heureka-calls.txt', $text, FILE_APPEND);
891//
892// file_get_contents($heurekaUrl);
893// }
894// }
895// }
896 if($this->getParameter('Cancel') !== null || $this->getParameter('CancelR') !== null || $this->getParameter('Storno') !== null || $this->getParameter('Refund') !== null){
897 $this->template->noComplte = true;
898 }
899 if (!empty($this->getSession('customUser')->email)) {
900 $this->template->orderEmail = $this->getSession('customUser')->email;
901 }
902 $this->template->books = $books = $this->user->getAllMyBookByOrder($this->getUser()->id, $idOrder);
903Debugger::barDump($books);
904 $type = [];
905 foreach ($books as $book) {
906 $type[$book['book_type']] = true;
907 }
908 Debugger::barDump($type);
909 $this->template->voucher = $voucher;
910 $this->template->credit = $credit;
911 $this->template->type = $type;
912 $this->template->carriers = $this->carrier;
913 $this->template->orderSent = $orderSent;
914 $this->template->orderPay = $orderPay;
915 $this->template->payment = $this->getSession('payment')->pay;
916 $this->template->data = $data;
917 $this->template->reader = $this->userNamager->getUsersReader($this->getUser()->id);
918 $this->template->orderedOwn = $orderedOwn;
919 $this->template->orderedGift = $orderedGift;
920 $this->template->state = $this->order->getOrderStatus($idOrder);
921 $this->template->id = $idOrder ?? str_replace('fe-', '', $id);
922 $this->template->product = $this->product;
923 $this->template->category = $this->category;
924 }
925
926
927 public function handleRemoveCredit()
928 {
929 unset($this->getSession('cart')->credit);
930 $this->cart->removeCredit($this->getUser()->id);
931
932 $this->redrawControl('cartSnippet');
933 $this->redrawControl('content');
934 $this->redrawControl('cartItems');
935 $this->redrawControl('cartPrice');
936 $this->redrawControl('cartPriceMobile');
937 $this->redrawControl('fMessages');
938 }
939
940 public function createComponentAddCreditForm($num)
941 {
942 $form = new Form();
943 $form->addText('credit', 'Kredit')->setRequired('Zadejte počet kreditů!')->addRule(Form::PATTERN, 'Zadejte počet kreditů!', '\d+');
944 $form->addSubmit('send', 'Přidat do košíku');
945 $form->onSuccess[] = function (Form $form, $values) {
946 try {
947// if (!$this->getUser()->isLoggedIn()) {
948// $this->template->showModalCart = true;
949// $this->redrawControl('warningModal');
950// return false;
951// }
952 if (!empty($this->getSession('cart')->items)) {
953 $this->template->showModalNoBuy = true;
954 $this->redrawControl('showModalNoBuy');
955 return false;
956 }
957 $this->template->showModalCart = false;
958 if (!empty($this->getSession('cart')->sale) && empty($this->getSession('cart')->sale_id_book)) {
959 $this->template->showModalCart = true;
960 $this->redrawControl('warningModal');
961 }
962
963 if (empty($this->getSession('cart')->credit)) {
964 if ($values['credit'] < 10) {
965 $this->flashMessage('Minimální množství je 10', 'error');
966 } else {
967 $this->getSession('cart')->credit = $values['credit'];
968 }
969 } else {
970 $this->getSession('cart')->credit = $this->getSession('cart')->credit + $values['credit'];
971 }
972 if ($this->getUser()->isLoggedIn()) {
973 $this->cart->removeCredit($this->getUser()->id);
974 $this->cart->addCredit($this->getUser()->id, $this->getSession('cart')->credit);
975 }
976
977 $this->redrawControl('cartSnippet');
978 $this->redrawControl('content');
979 $this->redrawControl('cartItems');
980 $this->redrawControl('cartPrice');
981 $this->redrawControl('cartPriceMobile');
982 $this->redrawControl('fMessages');
983 } catch (\Exception $e) {
984 if (!empty($e->getMessage())) {
985 $this->flashMessage($e->getMessage(), "error");
986 $this->redirect("this");
987 } else {
988 $this->redirect("Cart:default");
989 }
990 }
991 };
992 return $form;
993
994 }
995
996 public function createComponentSaleForm()
997 {
998 $form = new Form();
999 $form->addText("code");
1000 $form->addSubmit("submit", "Použít kupón");
1001 $form->onSuccess[] = function ($form, $values) {
1002 try {
1003 if (!empty($values->code)) {
1004 if (!$this->getUser()->isLoggedIn()) {
1005 throw new \Exception("Pro použití kupónu je nejdříve nutné se přihlásit");
1006 }
1007 if (!empty($this->getSession("cart")->sale)) {
1008 throw new \Exception("Nemůžete uplatnit více než jeden kupón na objednávku");
1009 }
1010 $coupon = $this->api->checkSaleCodeCart($this->getUser()->id, $values->code);
1011
1012 if (!empty($coupon["status"])) {
1013 if (!empty($coupon["data"])) {
1014 if (!empty($coupon["data"]["voucher_type"])) {
1015 $this->parseVoucherType($coupon["data"]["voucher_type"][0]);
1016 }
1017 }
1018 throw new \Exception("Neplatný kupón");
1019 }
1020
1021 if (empty($coupon['sale']['book']) && !empty($this->getSession('cart')->credit)) {
1022 $this->template->showModalCart = true;
1023 $this->redrawControl('warningModal');
1024 }
1025
1026 if (empty($coupon['sale']['book']) && !empty($this->getSession('cart')->items)) {
1027 foreach ($this->getSession('cart')->items as $id => $pcs) {
1028 if (explode("-", $id)[1] == "gVoucher") {
1029 $this->template->showModalCart = true;
1030 $this->redrawControl('warningModal');
1031 }
1032 }
1033 }
1034 if(empty($coupon['credit'])){
1035 $this->getSession("cart")->offsetSet("code", $values->code);
1036 }
1037 if (!empty($coupon['sale'])) {
1038 if (empty($coupon['sale']['book'])) {
1039 $this->getSession("cart")->offsetSet("sale", (int)$coupon["sale"]["amount"]);
1040 $this->getSession("cart")->offsetSet("sale_type", $coupon["sale"]["type"]);
1041 if (!$this->cart->getCartSale($this->getUser()->id)) {
1042 $this->cart->addCartSale($this->getUser()->id, [
1043 "sale" => (int)$coupon["sale"]["amount"],
1044 "sale_type" => $coupon["sale"]["type"]
1045 ]);
1046 }
1047 } else {
1048 $arrayBook = array();
1049 if (!empty(iterator_to_array($this->getSession('cart'))['items'])) {
1050 foreach (iterator_to_array($this->getSession('cart'))['items'] as $key => $val) {
1051 $arrayBook[] = explode('-', $key)[0];
1052 }
1053 foreach ($coupon['sale']['book'] as $book) {
1054 if (!in_array($book['id_book'], $arrayBook)) {
1055 $this->handleBuyItem($book['id_book'] . '-cart');
1056 }
1057 }
1058 } else {
1059 foreach ($coupon['sale']['book'] as $book) {
1060 $this->handleBuyItem($book['id_book'] . '-cart');
1061 }
1062 }
1063
1064 $arrayBook = array();
1065 if (!empty(iterator_to_array($this->getSession('cart'))['items'])) {
1066 foreach (iterator_to_array($this->getSession('cart'))['items'] as $key => $val) {
1067 $arrayBook[] = explode('-', $key)[0];
1068 }
1069 $cart_empty = true;
1070 $book_ids = [];
1071 foreach ($coupon['sale']['book'] as $book) {
1072 if (in_array($book['id_book'], $arrayBook)) {
1073 $cart_empty = false;
1074 $book_ids[] = $book['id_book'];
1075 }
1076 }
1077 if ($cart_empty) {
1078 throw new \Exception("Nelze uplatnit kupón");
1079 } else {
1080 $this->getSession("cart")->offsetSet("sale_id_book", $book_ids);
1081 $this->getSession("cart")->offsetSet("sale", (int)$coupon["sale"]["amount"]);
1082 $this->getSession("cart")->offsetSet("sale_type", $coupon["sale"]["type"]);
1083 if (!$this->cart->getCartSale($this->getUser()->id)) {
1084 $this->cart->addCartSale($this->getUser()->id, [
1085 "books_id" => $book_ids,
1086 "sale" => (int)$coupon["sale"]["amount"],
1087 "sale_type" => $coupon["sale"]["type"]
1088 ]);
1089 }
1090 }
1091 } else {
1092 throw new \Exception("Nelze uplatnit kupón");
1093 }
1094 }
1095
1096 $this->flashMessage("Slevový kupón byl uplatněn. Vztahuje se pouze na e-knihy a mp3 audioknihy.", "info");
1097 } else {
1098 $this->flashMessage('Nelze uplatnit kupón', 'error');
1099 }
1100 $this->redrawControl('cartSnippet');
1101 $this->redrawControl('content');
1102 $this->redrawControl('cartItems');
1103 $this->redrawControl('cartPrice');
1104 $this->redrawControl('cartPriceMobile');
1105 $this->redrawControl('fMessages');
1106 $this->redrawControl('warningModal');
1107 } else {
1108 $this->redirect("Cart:default");
1109 }
1110 } catch (\Exception $e) {
1111 if (!empty($e->getMessage())) {
1112 $this->flashMessage($e->getMessage(), "error");
1113 if ($this->isAjax()) {
1114 $this->redrawControl('fMessages');
1115 } else {
1116 $this->redirect("this");
1117 }
1118 } else {
1119 $this->redirect("Cart:payment");
1120 }
1121 }
1122 };
1123 return $form;
1124 }
1125
1126 public function handleUseCreditChange($useCredit)
1127 {
1128 $this->getSession('cart')->offsetSet('use_credit', ($useCredit));
1129 $this->redrawControl('cart');
1130 $this->redrawControl('cartPrice');
1131 $this->redrawControl('cartPriceMobile');
1132 }
1133 public function handleSetCarrier($idCarrier){
1134 if(!empty($this->getSession('order')->data)){
1135 $data = $this->getSession('order')->data;
1136 }
1137 if(empty($idCarrier)){
1138 $data['typeCarrier'] = null;
1139 }else{
1140 $data['typeCarrier'] = $idCarrier;
1141 }
1142 $this->getSession('order')->data = $data;
1143 unset($this->getSession('cart')['use_credit']);
1144 $this->redrawControl('cart');
1145 $this->redrawControl('halfCredit');
1146 $this->redrawControl('cartPrice');
1147 $this->redrawControl('cartPriceMobile');
1148 }
1149 public function handleSetPayment($idPayment){
1150 if(!empty($this->getSession('order')->data)){
1151 $data = $this->getSession('order')->data;
1152 }
1153 if(empty($idPayment)){
1154 $data['typePayment'] = null;
1155 }else{
1156 $data['typePayment'] = $idPayment;
1157 }
1158 $this->getSession('order')->data = $data;
1159
1160 $this->redrawControl('cart');
1161 $this->redrawControl('halfCredit');
1162 $this->redrawControl('cartPrice');
1163 $this->redrawControl('cartPriceMobile');
1164 }
1165
1166 public function createComponentPaymentForm()
1167 {
1168 $form = new Form();
1169 $credit = $this->databaseB->select('name,id_api')->from('payments')->fetchPairs('id_api', 'name');
1170
1171
1172 if ($this->user->getVipById($this->getUser()->id) == 1) {
1173 $credit['vip'] = "Testovací platba";
1174 }
1175 foreach ($this->databaseB->select('*')->from('delivery_methods')->where('active = %i', 1)->fetchAll() as $carrier) {
1176 $this->carrier[$carrier['code']] = [
1177 'price' => $carrier['price'],
1178 'title' => $carrier['name'],
1179 'points' => $carrier['points'],
1180 'desc' => 'POPIS',
1181 'logo' => 'https://www.seekpng.com/png/detail/76-765297_marlboro-gold-100-20-200-placeholder-image-png.png'
1182 ];
1183 }
1184 $delivery = [];
1185 foreach ($this->carrier as $name => $value) {
1186 $delivery[$name] = $value['title'];
1187 }
1188
1189
1190// if (empty($this->getUser()->identity->id)) {
1191// $form->addEmail('email', 'Na tento e-mail Vám přijde objednaný voucher. Prosíme, zkontrolujte si správnost uvedeného e-mailu.')->setRequired('Na tento e-mail Vám přijde objednaný voucher. Prosíme, zkontrolujte si správnost uvedeného e-mailu.');
1192// $form->addCheckbox('condition', '')->setRequired('Musíte souhlasit s obchodními podmínkami.');
1193// }
1194
1195 $useCredit = $form->addCheckbox('useCredit');
1196 $form->addHidden('payCredit')->setDefaultValue($this->payCredit);
1197// $form->addCheckbox('condition');
1198 $rl = $form->addRadioList('typePayment', ':', $credit);
1199 $rl->getSeparatorPrototype()->setName(null);
1200
1201 if (!$this->getUser()->isLoggedIn()) {
1202 $form->addCheckbox('conditions')->setRequired('Bez odsouhlasení nelze dokončit nákup.');
1203 }
1204 $form->addRadioList('typeCarrier', ':', $delivery);
1205 $form->addHidden('point', '');
1206 $form->addText('firstname', 'Jméno')
1207 ->addRule($form::MAX_LENGTH, 'Jméno je příliš dlouhé', 50)
1208 ->setRequired("Tento údaj je povinný, prosíme doplňte.");
1209
1210 $form->addText('surname', 'Příjmení')
1211 ->addRule($form::MAX_LENGTH, 'Příjmení je příliš dlouhé', 50)
1212 ->setRequired("Tento údaj je povinný, prosíme doplňte.");
1213
1214 $form->addText('city', 'Město')
1215 ->addRule($form::MAX_LENGTH, 'Město je příliš dlouhé', 255)
1216 ->setRequired("Tento údaj je povinný, prosíme doplňte.");
1217
1218 if(!$this->getUser()->isLoggedIn()) {
1219 $form->addText('email', 'E-mail')
1220 ->addRule($form::MAX_LENGTH, 'E-mail je příliš dlouhý', 255)
1221 ->setRequired("Tento údaj je povinný, prosíme doplňte.")
1222 ->addRule(Form::EMAIL, 'Údaj není správný');
1223 }
1224 else
1225 {
1226 $form->addHidden('email');
1227 }
1228
1229
1230 $form->addText('street', 'Ulice a číslo popisné')
1231 ->setRequired("Tento údaj je povinný, prosíme doplňte.")
1232 ->addRule($form::MAX_LENGTH, 'Ulice a číslo popisné je příliš dlouhé', 255)
1233 ->addRule(Form::MIN_LENGTH, "Údaj není správný", '2');
1234
1235 $form->addText('postal_code', 'PSČ')
1236 ->setRequired("Tento údaj je povinný, prosíme doplňte.")
1237 ->addRule($form::MAX_LENGTH, 'PSČ je příliš dlouhé', 15)
1238 ->addRule(Form::PATTERN, 'Údaj není správný', '([0-9]\s*){5}');
1239
1240 $form->addText('place', 'Místo dodání');
1241
1242
1243 $form->addText('phone', 'Telefon')
1244 ->setRequired("Tento údaj je povinný, prosíme doplňte.");
1245
1246
1247 $form->addCheckbox('alternative', 'Fakturační adresa je jiná než doručovací');
1248
1249 $form->addText('alternative_firstname', 'Jméno')
1250 ->addConditionOn($form['alternative'], Form::EQUAL, true)
1251 ->setRequired('Tento údaj je povinný, prosíme doplňte.')
1252 ->addRule($form::MAX_LENGTH, 'Jméno je příliš dlouhé', 30);
1253
1254 $form->addText('alternative_surname', 'Příjmení')
1255 ->addConditionOn($form['alternative'], Form::EQUAL, true)
1256 ->setRequired('Tento údaj je povinný, prosíme doplňte.')
1257 ->addRule($form::MAX_LENGTH, 'Příjmení je příliš dlouhé', 30);
1258
1259 $form->addText('alternative_city', 'Město')
1260 ->addConditionOn($form['alternative'], Form::EQUAL, true)
1261 ->setRequired('Tento údaj je povinný, prosíme doplňte.')
1262 ->addRule($form::MAX_LENGTH, 'Město je příliš dlouhé', 255);
1263
1264 $form->addText('alternative_phone', 'Telefon')
1265 ->addConditionOn($form['alternative'], Form::EQUAL, true)
1266 ->setRequired("Tento údaj je povinný, prosíme doplňte.")
1267 ->addRule($form::MAX_LENGTH, 'Telefon je příliš dlouhý', 40)
1268 ->addRule(Form::PATTERN, 'Údaj není správný', '^(\+420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$');
1269
1270 $form->addText('alternative_street', 'Ulice a číslo popisné')
1271 ->addConditionOn($form['alternative'], Form::EQUAL, true)
1272 ->addRule($form::MAX_LENGTH, 'Ulice a číslo popisné je příliš dlouhé', 255)
1273 ->addRule(Form::MIN_LENGTH, "Údaj není správný", '2')
1274 ->setRequired('Tento údaj je povinný, prosíme doplňte.');
1275
1276 $form->addText('alternative_email', 'E-mail')
1277 ->addConditionOn($form['alternative'], Form::EQUAL, true)
1278 ->addRule($form::MAX_LENGTH, 'E-mail je příliš dlouhý', 255)
1279 ->setRequired("Tento údaj je povinný, prosíme doplňte.")
1280 ->addRule(Form::EMAIL, 'Údaj není správný');
1281
1282 $form->addText('alternative_postal_code', 'Psč')
1283 ->addConditionOn($form['alternative'], Form::EQUAL, true)
1284 ->addRule(Form::PATTERN, 'Údaj není správný', '([0-9]\s*){5}')
1285 ->addRule($form::MAX_LENGTH, 'PSČ je příliš dlouhé', 15)
1286 ->setRequired('Tento údaj je povinný, prosíme doplňte.');
1287
1288 $form->addText('alternative_place', 'Místo dodání');
1289
1290
1291 $form->addCheckbox('on_company', ' Nakupují na firmu');
1292 $form->addText('company_name', 'Název firmy')
1293 ->addConditionOn($form['on_company'], Form::EQUAL, true)
1294 ->addRule($form::MAX_LENGTH, 'Název firmy je příliš dlouhý', 40)
1295 ->setRequired('Tento údaj je povinný, prosíme doplňte.');
1296
1297 $form->addText('company_ic', 'IČO')
1298 ->addConditionOn($form['on_company'], Form::EQUAL, true)
1299 ->addRule($form::MAX_LENGTH, 'IČO je příliš dlouhé', 15)
1300 ->setRequired('Tento údaj je povinný, prosíme doplňte.');
1301
1302 $form->addText('company_dic', 'DIČ')
1303 ->addConditionOn($form['on_company'], Form::EQUAL, true)
1304 ->addRule($form::MAX_LENGTH, 'DIČ je příliš dlouhé', 15)
1305 ->setRequired('Tento údaj je povinný, prosíme doplňte.');
1306
1307 if (!empty($defaultData = $this->getSession('order')->data)) {
1308 if (!empty($defaultData['typeCarrier'])) {
1309 if (empty($this->carrier[$defaultData['typeCarrier']])) {
1310 unset($defaultData['typeCarrier']);
1311 }
1312 }
1313 if (empty($defaultData['phone'])) {
1314 $defaultData['phone'] = "+420";
1315 }
1316
1317 $form->setDefaults($defaultData);
1318 } else {
1319 if ($this->getUser()->isLoggedIn()) {
1320 $idUser = $this->getUser()->getId();
1321 $values = [];
1322 if (!empty($values = $this->user->getAddress($idUser))) {
1323 $values = $values[0];
1324 $values['postal_code'] = $values['zip'];
1325 unset($values['zip']);
1326 $values['company_name'] = $values['com_name'];
1327 $values['company_ic'] = $values['IC'];
1328 $values['company_dic'] = $values['DIC'];
1329 if (empty($values['phone'])) {
1330 $values['phone'] = "+420";
1331 }
1332 }
1333 $values['email'] = $this->getUser()->getIdentity()->email;
1334 $form->setDefaults($values);
1335 } else {
1336 $form->setDefaults(['phone' => '+420']);
1337 }
1338 }
1339
1340 if(!empty($this->isPaperBookInCart))
1341 {
1342 $country = "";
1343 if($this->getUser()->isLoggedIn()) {
1344 $country = strtoupper($this->user->getCountry($this->getUser()->getIdentity()->getId()));
1345 }
1346 if($country != "CZ")
1347 {
1348 $form->addText('country', 'Země')->setDisabled();
1349
1350 $resetDefaults = [
1351 'city' => '',
1352 'street' => '',
1353 'postal_code' => '',
1354 'country' => "Česká republika"
1355 ];
1356
1357 $form->setDefaults($resetDefaults);
1358
1359 }
1360 }
1361
1362 if (empty($this->isPaperBookInCart)) {
1363 $form['phone']->setRequired(false);
1364 $form['firstname']->setRequired(false);
1365 $form['surname']->setRequired(false);
1366 $form['city']->setRequired(false);
1367 $form['street']->setRequired(false);
1368 $form['postal_code']->setRequired(false);
1369 $form['place']->setRequired(false);
1370
1371
1372 $form['alternative_phone']->setRequired(false);
1373 $form['alternative_firstname']->setRequired(false);
1374 $form['alternative_surname']->setRequired(false);
1375 $form['alternative_city']->setRequired(false);
1376 $form['alternative_street']->setRequired(false);
1377 $form['alternative_postal_code']->setRequired(false);
1378 }else{
1379 $form['phone']->addRule($form::MAX_LENGTH, 'Telefon je příliš dlouhý', 40)
1380 ->addRule(Form::PATTERN, 'Údaj není správný', '^(\+420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$');
1381 }
1382
1383
1384 $form->addSubmit('submit', 'Pokračovat');
1385 $form->onSuccess[] = function (Form $form, ArrayHash $values) {
1386 try {
1387// if($values['typePayment'] == "cod" && $values['useCredit']){
1388// $this->presenter->flashMessage("Nelze uplatnit kombinaci dobírky a platby kreditem", 'error');
1389// $this->redirect('this');
1390// return false;
1391// }
1392 $values['phone'] = str_replace(' ', '', $values['phone']);
1393 $values['alternative_phone'] = str_replace(' ', '', $values['alternative_phone']);
1394 $buyNoLogged = true;
1395 $is_anonymous = false;
1396 if (!empty($this->getSession('cart')->items) || !empty($this->getSession('cart')->credit)) {
1397 if (!empty($this->getSession('cart')->items)) {
1398 foreach ($this->getSession('cart')->items as $id => $pcs) {
1399 if (explode('-', $id)[1] == "cart" || explode('-', $id)[1] == "pack") {
1400 $buyNoLogged = false;
1401 }
1402 }
1403 }
1404
1405 if (!$buyNoLogged && empty($this->getUser()->identity->id)) {
1406 $this->presenter->flashMessage("Pro uskutečnění objednávky, je třeba se přihlásit", 'error');
1407 $this->redirect('this');
1408 }
1409 $this->getSession('payment')->pay = $values['typePayment'];
1410 if ($values->typePayment == "credit") {
1411 $priceSum = $this->product->getBooksPricesForCartNew($this->getSession('cart')->items, $this->getSession('cart'));
1412
1413 $priceSum = round($priceSum);
1414 if (!empty($values['typeCarrier']) && !empty($carrierData = $this->carrier[$values['typeCarrier']])) {
1415 $priceSum += $carrierData['price'];
1416 }
1417 if ($priceSum <= $this->userNamager->getCreditsById($this->getUser()->id)) {
1418 // TODO COMPLETE
1419// $this->userNamager->removeCredits($this->getUser()->id, $priceSum);
1420 $this->getUser()->identity->credits = $this->user->getCreditsById($this->getUser()->id);
1421 } else {
1422 $this->presenter->flashMessage("Je nám líto, nemáte dostatečný kredit", 'error');
1423 $this->redirect('this');
1424 }
1425 }
1426
1427 if ($this->getSession('cart')->use_credit) {
1428 if ($values['payCredit'] > $this->userNamager->getCreditsById($this->getUser()->id)) {
1429 $this->presenter->flashMessage("Je nám líto, nemáte dostatečný kredit", 'error');
1430 $this->redirect('this');
1431 } else {
1432 // TODO COMPLETE
1433// $this->userNamager->removeCredits($this->getUser()->id, $values['payCredit']);
1434 $this->getUser()->identity->credits = $this->user->getCreditsById($this->getUser()->id);
1435 }
1436 }
1437 $this->getSession('cart')->payment = $values["typePayment"];
1438
1439 if ($buyNoLogged && empty($this->getUser()->identity->id)) {
1440 if (!empty($values['email'])) {
1441// if (!empty($values['condition'])) {
1442// if ($values['condition']) {
1443 if (!empty($user = $this->api->getUserByEmail($values['email']))) {
1444 $idUser = $user['id'];
1445 } else {
1446 $userData = array(
1447 'email' => $values['email'],
1448 'firstname' => "",
1449 'surname' => "",
1450 'phone' => "",
1451 'password' => "",
1452 'fake_reg' => 1
1453 );
1454 $this->api->register($userData);
1455 $userAddres = array(
1456 'street' => "",
1457 'city' => "",
1458 'zip' => "",
1459 'country' => "cz"
1460 );
1461 $idUser = $this->api->getUserByEmail($values['email'])['id'];
1462 $this->api->addAddress($idUser, $userAddres);
1463 }
1464 $is_anonymous = true;
1465// } else {
1466// $this->presenter->flashMessage("Musíte souhlasit s obchodními podmínkami", 'error');
1467// $this->redirect('this');
1468// }
1469// } else {
1470// $this->presenter->flashMessage("Musíte souhlasit s obchodními podmínkami", 'error');
1471// $this->redirect('this');
1472// }
1473 } else {
1474 $this->presenter->flashMessage("Zadejte email", 'error');
1475 $this->redirect('this');
1476 }
1477 }
1478 if (empty($idUser) && !empty($this->getUser()->identity->id)) {
1479 $idUser = $this->getUser()->identity->id;
1480 }
1481 $invoiceAddress = $this->getAddresByApi($idUser, $values, 'invoice', $is_anonymous);
1482 if (!empty($values['alternative'])) {
1483 $data = [
1484 'on_company' => $values['on_company'] ?? "",
1485 'firstname' => $values['alternative_firstname'] ?? "",
1486 'surname' => $values['alternative_surname'] ?? "",
1487 'com_name' => $values['company_name'] ?? "",
1488 'IC' => $values['company_ic'] ?? "",
1489 'DIC' => $values['company_dic'] ?? "",
1490 'street' => $values['alternative_street'] ?? "",
1491 'postal_code' => $values['alternative_postal_code'] ?? "",
1492 'city' => $values['alternative_city'] ?? "",
1493 'email' => $values['alternative_email'] ?? "",
1494 'phone' => $values['alternative_phone'] ?? "",
1495 'place' => $values['alternative_place'] ?? "",
1496 'country' => "cz"
1497 ];
1498
1499 $deliveryAddress = $this->getAddresByApi($idUser, $data, 'delivery', $is_anonymous);
1500 }
1501
1502
1503// $redir = $this->order->createOrder($this->getSession('cart'), $idUser,$values['payCredit']);
1504// $this->cart->removeAllByUser($this->getUser()->id);
1505 //$this->user->setLogConsents('create_order', $idUser, 1);
1506
1507// if (empty($redir["pay_redir"])) {
1508// $this->redirect("Cart:complete", "fe-" . $redir["id"]);
1509// }
1510// $this->redirectUrl($redir["pay_redir"]);
1511
1512 $this->getSession('order')->data = $values;
1513 $this->getSession('order')->delivery_address = $deliveryAddress ?? $invoiceAddress;
1514 $this->getSession('order')->invoice_address = $invoiceAddress;
1515 $this->handleCompleteOrder($is_anonymous);
1516// $this->redirect('Cart:summary');
1517 die();
1518 } else {
1519 $this->flashMessage("V košíku nemáte žádné položky", 'error');
1520 $this->redirect('Cart:default');
1521 }
1522 } catch (\Dibi\Exception $e) {
1523 if (!empty($e->getMessage())) {
1524 $this->presenter->flashMessage($e->getMessage(), 'error');
1525 }
1526 $this->redirect('this');
1527 }
1528 };
1529
1530 return $form;
1531 }
1532
1533 public function getAddresByApi($idUser, $values, $type, $is_anonymous = false)
1534 {
1535 $idAddres = null;
1536 $valueAddress = [
1537 'type' => $type,
1538 'firstname' => $values['firstname'] ?? "",
1539 'surname' => $values['surname'] ?? "",
1540 'com_name' => $values['company_name'] ?? "",
1541 'IC' => $values['company_ic'] ?? "",
1542 'DIC' => $values['company_dic'] ?? "",
1543 'street' => $values['street'] ?? "",
1544 'zip' => $values['postal_code'] ?? "",
1545 'city' => $values['city'] ?? "",
1546 'email' => $values['email'] ?? "",
1547 'phone' => $values['phone'] ?? "",
1548 'place' => $values['place'] ?? "",
1549 'country' => "cz"
1550 ];
1551 if (empty($values['on_company'])) {
1552 $valueAddress['com_name'] = "";
1553 $valueAddress['IC'] = "";
1554 $valueAddress['DIC'] = "";
1555 }
1556 foreach ($this->api->getAdress($idUser) as $address) {
1557 $id_address = $address['id'];
1558 unset($address['id']);
1559 if ($address == $valueAddress) {
1560 $idAddres = $id_address;
1561 }
1562 }
1563 if (empty($idAddres)) {
1564 if ($is_anonymous) {
1565 $valueAddress['is_anonymous'] = 1;
1566 }
1567 $addressDataApi = $this->api->addAddress($idUser, $valueAddress);
1568
1569// dump('data address '. $valueAddress);
1570// dump('address id: ', $addressDataApi);
1571 if (empty($addressDataApi['id'])) {
1572 return null;
1573 }
1574 $idAddres = $addressDataApi['id'];
1575 $valueAddress['default_address'] = false;
1576 if ($type == "invoice" && !$is_anonymous) {
1577 unset($valueAddress['type']);
1578 unset($valueAddress['email']);
1579 $valueAddress['id_puser'] = $idUser;
1580 $this->databaseB->insert('pk_puser_address', [
1581 'id_puser' => $idUser,
1582// 'id_address' => $idAddres,
1583 'state' => 'New',
1584 'firstname' => $values['firstname'] ?? "",
1585 'surname' => $values['surname'] ?? "",
1586 'com_name' => $values['company_name'] ?? "",
1587 'IC' => $values['company_ic'] ?? "",
1588 'DIC' => $values['company_dic'] ?? "",
1589 'street' => $values['street'] ?? "",
1590 'city' => $values['city'] ?? "",
1591 'zip' => $values['postal_code'] ?? "",
1592 'country' => "cz",
1593 'phone' => $values['phone'] ?? "",
1594 'place' => $values['place'] ?? "",
1595 'id_adress_api' => $idAddres,
1596 ])->execute();
1597 $idAdd = $this->databaseB->getInsertId();
1598 $this->databaseB->update('pk_puser', ['default_address_id' => $idAdd])->where('id = %i', $idUser)->execute();
1599 }
1600
1601 }
1602 return $idAddres;
1603 }
1604
1605 public function renderSummary()
1606 {
1607 if (empty($this->getSession('order')->data)) {
1608 $this->redirect('Cart:payment');
1609 }
1610 if (empty($this->getSession('cart')->items) && empty($this->getSession('cart')->credit)) {
1611 $this->redirect('Cart:default');
1612 }
1613 $this->template->vip = $this->user->getVipById($this->getUser()->id);
1614 $inCart = [];
1615 $gVouchersInCart = [];
1616 $priceWoDph = 0;
1617 $priceDph = 0;
1618 $priceSum = 0;
1619 $priceSumNoSale = 0;
1620 $priceSumFullNoSale = 0;
1621 $sumCart = 0;
1622 $payCredit = 0;
1623 $onlyPayCredit = false;
1624 $buyNoLogged = true;
1625 $address = false;
1626 $isPaperBookInCart = false;
1627 if (!empty($this->getSession('cart')->items)) {
1628 if (!empty($this->getSession('cart')->items)) {
1629 foreach ($this->getSession('cart')->items as $id => $pcs) {
1630 if (explode('-', $id)[1] == "cart" || explode('-', $id)[1] == "pack") {
1631 $buyNoLogged = false;
1632 }
1633 if (explode('-', $id)[1] == "paper") {
1634 $address = true;
1635 $isPaperBookInCart = true;
1636 }
1637 $sumCart += $pcs;
1638 if (explode("-", $id)[1] == "gVoucher") {
1639 $book = $this->giftVoucher->getVoucherById(explode("-", $id)[0]);
1640 $book["price"] = explode("-", $id)[2];
1641 $book["text"] = urldecode(explode("-", $id)[3]);
1642 $book["pcs"] = $pcs;
1643 $book["urlRemove"] = $id;
1644 $gVouchersInCart[] = $book;
1645 } else {
1646 $idBook = explode('-', $id)[0];
1647 $book = $this->product->getBooksById($idBook);
1648 $book["pcs"] = $pcs;
1649 $book["urlRemove"] = $id;
1650 if (explode("-", $id)[1] == "pack") {
1651 $bookLibDup = array();
1652 $bookInPack = $this->product->getBookInPack(explode("-", $id)[0]);
1653 foreach ($bookInPack as $idBook) {
1654 if ($this->userNamager->checkLibraryIdBook($this->getUser()->id, $idBook)) {
1655 $bookLibDup[] = $this->product->getBookTitleById($idBook);
1656 }
1657 }
1658 $title = "";
1659
1660 foreach ($bookLibDup as $key => $value) {
1661 $title .= $value;
1662 if (next($bookLibDup) == true) {
1663 $title .= ",";
1664 }
1665 }
1666
1667 $book['books_lib_dup'] = $title;
1668 }
1669 $inCart[] = $book;
1670 }
1671 $tmpPrice = (isset($book["price_sale"]) ? $book["price_sale"] : $book["price"]) * $book['pcs'];
1672 $priceSumFullNoSale += round($tmpPrice);
1673 if (explode("-", $id)[1] != "gVoucher") {
1674 $priceSumNoSale += round($tmpPrice);
1675 }
1676 if (explode("-", $id)[1] != "gVoucher") {
1677 if (isset($this->getSession("cart")->sale_id_book)) {
1678 foreach ($this->getSession("cart")->sale_id_book as $book_id) {
1679 if ($book_id == $book['id']) {
1680 if ($this->getSession("cart")->sale_type == "percent") {
1681 $sale = $this->getSession("cart")->sale;
1682 $tmpPrice = round($tmpPrice) * ((100 - $sale) / 100);
1683 } else {
1684 $sale = $this->getSession("cart")->sale;
1685 $tmpPrice = round($tmpPrice) - $sale;
1686 }
1687 $book["price_sale"] = $tmpPrice;
1688 }
1689 }
1690 }
1691 }
1692 if (explode("-", $id)[1] != "gVoucher") {
1693 $payCredit += round($tmpPrice);
1694 }
1695 $tmpPrice = round($tmpPrice);
1696 $priceSum += $tmpPrice * $book["pcs"];
1697 $priceDph += $tmpPrice - ($tmpPrice / 1.1) * $book["pcs"];
1698 $priceWoDph += ($tmpPrice / 1.1) * $book["pcs"];
1699 }
1700 }
1701 }
1702
1703 if ($this->getSession("cart")->sale_type == "percent") {
1704 $sale = $this->getSession("cart")->sale;
1705 $priceSum = round($priceSum) * ((100 - $sale) / 100);
1706 } else {
1707 $sale = $this->getSession("cart")->sale;
1708 $priceSum = round($priceSum) - $sale;
1709 }
1710
1711 $priceSum = $this->getBooksPricesForCartNew();
1712
1713 $bundleInfo = [];
1714 foreach ($inCart as $bk) {
1715 if ($bk['type'] == "bundle") {
1716 $bundle = $this->product->getBooksById($bk['id'])->toArray();
1717 $priceBundle = round($bundle['price']);
1718 $priceBookInBundle = 0;
1719 $priceTotalBookSingle = 0;
1720 $bookInLibrary = [];
1721 foreach ($this->product->getBundleBooksIds($bk['id']) as $booksInBundle) {
1722 $book = $this->product->getBooksById($booksInBundle['book_id']);
1723 $priceTotalBookSingle += round($book['price']);
1724 if ($this->user->checkLibraryIdBook($this->getUser()->id, $booksInBundle['book_id'])) {
1725 $priceBookInBundle += round($book['price']);
1726 $bookInLibrary[] = $book['title'];
1727 }
1728 }
1729 if (!empty($bookInLibrary)) {
1730 if (count($bookInLibrary) == 1) {
1731 $text = "Knihu " . $bookInLibrary[0];
1732 } else {
1733 $text = "Knihy " . implode(', ', $bookInLibrary[0]);
1734 }
1735 if (($priceTotalBookSingle - $priceBookInBundle) > $priceBundle) {
1736 $diference = ($priceTotalBookSingle - $priceBookInBundle) - $priceBundle;
1737 $text .= " již máte v knihovně, přesto koupí tohoto balíčku ušetříte <strong>" . $diference . " Kč</strong>.";
1738 } else {
1739 $diference = $priceBundle - ($priceTotalBookSingle - $priceBookInBundle);
1740 $text .= " již máte v knihovně, koupí tohoto balíčku zaplatíte o <strong>" . $diference . " Kč</strong> víc, než při nákupu jednotlivých knih.";
1741 }
1742 }
1743 if (!empty($text)) {
1744 $bundleInfo[$bk['id']] = $text;
1745 }
1746
1747 $payCredit += $priceBundle;
1748
1749 }
1750 }
1751
1752 if (!empty($this->getUser()->identity->id)) {
1753 $buyNoLogged = true;
1754 }
1755
1756 if ($this->getUser()->isLoggedIn()) {
1757 if ($this->getUser()->getIdentity()->credits >= $priceSum) {
1758 $onlyPayCredit = true;
1759 $payCredit = $priceSum;
1760 } else {
1761 $payCredit = $this->getUser()->getIdentity()->credits;
1762 }
1763 if (empty($crdHelp = $this->getSession('cart')->credit)) {
1764 $crdHelp = 0;
1765 }
1766
1767 if (($sumCreditPay = $priceSum + $crdHelp - $payCredit) < 10) {
1768 $payCredit = $payCredit - (10 - $sumCreditPay);
1769 $this->template->showMsgPayment = true;
1770 }
1771 } else {
1772 $onlyPayCredit = false;
1773 $payCredit = 0;
1774 }
1775
1776 if (isset($this->getSession('cart')->credit) || !empty($gVouchersInCart)) {
1777 $payCredit = 0;
1778 $onlyPayCredit = false;
1779 }
1780 if (!empty($inCart) || !empty($gVouchersInCart) || !empty($creditCart)) {
1781 if (!$this->getUser()->isLoggedIn() && !$buyNoLogged) {
1782 $this->redirect('Cart:default');
1783 }
1784 }
1785
1786 $this->template->isPaperBookInCart = $isPaperBookInCart;
1787 $this->payCredit = $payCredit;
1788 $this->template->address = $address;
1789 $this->template->payCredit = $payCredit;
1790 $this->template->onlyPayCredit = $onlyPayCredit;
1791 $this->template->sumCart = isset($this->getSession('cart')->credit) ? $sumCart + 1 : $sumCart;
1792 $this->template->priceSumFullNoSale = $priceSumFullNoSale;
1793 $this->template->inBundle = $bundleInfo;
1794 $this->template->inCart = $inCart;
1795 $this->template->product = $this->product;
1796 $this->template->gVouchersInCart = $gVouchersInCart;
1797 $this->template->priceWoDph = $priceWoDph;
1798 $this->template->priceSumNoSale = $priceSumNoSale;
1799 $this->template->priceDph = $priceDph;
1800 $this->template->priceSum = $priceSum;
1801 $this->template->sale = $this->getSession("cart")->sale;
1802 $this->template->sale_type = $this->getSession("cart")->sale_type;
1803 $this->template->creditCart = $this->getSession('cart')->credit ?? 0;
1804 $this->template->useCredit = $this->getSession('cart')->use_credit ?? false;
1805 $this->template->payment = $this->databaseB->select("id,price,id_api,name,description,logo")->from("payments")->where('id_api = %s', $this->getSession('order')->data['typePayment'])->fetch();
1806 $this->template->carrier = $carrier = !empty($this->carrier[$this->getSession('order')->data['typeCarrier']]) ? $this->carrier[$this->getSession('order')->data['typeCarrier']] : "";
1807 if (!empty($carrier['points'])) {
1808 if (empty($point = $this->getSession('order')->data['point'])) {
1809 $this->flashMessage('Vyberte odběrné místo', 'error');
1810 $this->redirect('Cart:payment');
1811 } else {
1812 if (!empty($pointName = $this->databaseB->select('name')->from('delivery_points')->where('id = %i AND delivery_id = %i', $point, $carrier['id'])->fetchSingle())) {
1813 $this->template->pointName = $pointName;
1814 } else {
1815 $this->flashMessage('Vyberte odběrné místo', 'error');
1816 $this->redirect('Cart:payment');
1817 }
1818 }
1819 }
1820 $this->template->address = $this->getSession('order')->data;
1821 $this->template->freeDelivery = $this->freeDelivery;
1822
1823 }
1824
1825 public function handleCompleteOrder($is_anonymous)
1826 {
1827
1828 try {
1829 if (!$this->completeOrder) {
1830 return false;
1831 }
1832 $values = $this->getSession('order')->data;
1833 $buyNoLogged = true;
1834 if (!empty($this->getSession('cart')->items) || !empty($this->getSession('cart')->credit)) {
1835 if (!empty($this->getSession('cart')->items)) {
1836 foreach ($this->getSession('cart')->items as $id => $pcs) {
1837 if (explode('-', $id)[1] == "cart" || explode('-', $id)[1] == "pack") {
1838 $buyNoLogged = false;
1839 }
1840 }
1841 }
1842
1843 if (!$buyNoLogged && empty($this->getUser()->identity->id)) {
1844 $this->presenter->flashMessage("Pro uskutečnění objednávky, je třeba se přihlásit", 'error');
1845 $this->redirect('this');
1846 }
1847 $this->getSession('payment')->pay = $values['typePayment'];
1848 if ($values->typePayment == "credit") {
1849 $priceSum = $this->product->getBooksPricesForCartNew($this->getSession('cart')->items, $this->getSession('cart'));
1850
1851 $priceSum = round($priceSum);
1852 if ($priceSum <= $this->userNamager->getCreditsById($this->getUser()->id)) {
1853 $this->userNamager->removeCredits($this->getUser()->id, $priceSum);
1854 $this->getUser()->identity->credits = $this->user->getCreditsById($this->getUser()->id);
1855 } else {
1856 $this->presenter->flashMessage("Je nám líto, nemáte dostatečný kredit", 'error');
1857 $this->redirect('this');
1858 }
1859 }
1860 if ($this->getSession('cart')->use_credit) {
1861 if ($values['payCredit'] > $this->userNamager->getCreditsById($this->getUser()->id)) {
1862 $this->presenter->flashMessage("Je nám líto, nemáte dostatečný kredit", 'error');
1863 $this->redirect('this');
1864 } else {
1865 $this->userNamager->removeCredits($this->getUser()->id, $values['payCredit']);
1866 $this->getUser()->identity->credits = $this->user->getCreditsById($this->getUser()->id);
1867 }
1868 }
1869 $this->getSession('cart')->payment = $values["typePayment"];
1870
1871 if ($buyNoLogged && empty($this->getUser()->identity->id)) {
1872 if (!empty($values['email'])) {
1873// if (!empty($values['condition'])) {
1874// if ($values['condition']) {
1875 if (!empty($user = $this->api->getUserByEmail($values['email']))) {
1876 $idUser = $user['id'];
1877 } else {
1878 $userData = array(
1879 'email' => $values['email'],
1880 'firstname' => "",
1881 'surname' => "",
1882 'phone' => "",
1883 'password' => "",
1884 'fake_reg' => 1
1885 );
1886 $this->api->register($userData);
1887 $userAddres = array(
1888 'street' => "",
1889 'city' => "",
1890 'zip' => "",
1891 'country' => "cz"
1892 );
1893 $idUser = $this->api->getUserByEmail($values['email'])['id'];
1894 $this->api->addAddress($idUser, $userAddres);
1895 }
1896// } else {
1897// $this->presenter->flashMessage("Musíte souhlasit s obchodními podmínkami", 'error');
1898// $this->redirect('this');
1899// }
1900// } else {
1901// $this->presenter->flashMessage("Musíte souhlasit s obchodními podmínkami", 'error');
1902// $this->redirect('this');
1903// }
1904 } else {
1905 $this->presenter->flashMessage("Zadejte email", 'error');
1906 $this->redirect('this');
1907 }
1908 }
1909 if (empty($idUser) && !empty($this->getUser()->identity->id)) {
1910 $idUser = $this->getUser()->identity->id;
1911 }
1912 $typeCarrier = null;
1913 if (!empty($codeCarrier = $this->getSession('order')->data['typeCarrier'])) {
1914 $typeCarrier = $this->databaseB->select('*')->from('delivery_methods')->where('code = %s', $codeCarrier)->fetch();
1915 }
1916 $pointId = null;
1917 if ($typeCarrier['points']) {
1918 if (empty($point = $this->getSession('order')->data['point'])) {
1919 $this->flashMessage('Vyberte odběrné místo', 'error');
1920 $this->redirect('Cart:payment');
1921 } else {
1922 if (!empty($pointName = $this->databaseB->select('id')->from('delivery_points')->where('id = %i AND delivery_id = %i', $point, $typeCarrier['id'])->fetchSingle())) {
1923 $pointId = $pointName;
1924 } else {
1925 $this->flashMessage('Vyberte odběrné místo', 'error');
1926 $this->redirect('Cart:payment');
1927 }
1928 }
1929 }
1930 $typeCarrier = $typeCarrier['id'];
1931 if (!$this->getUser()->isLoggedIn()) {
1932 $this->getSession('customUser')->email = $values['email'];
1933 }
1934 $redir = $this->order->createOrder($this->getSession('cart'), $idUser, $values['payCredit'], $this->getSession('order')->invoice_address, $this->getSession('order')->delivery_address, $typeCarrier, $pointId, $is_anonymous);
1935 if (!empty($redir) && !empty($redir['status']) && $redir['status'] == 416) {
1936 $nameBooks = "";
1937 $i = 0;
1938 foreach ($redir['data'] as $bk) {
1939 $i++;
1940 $nameBooks .= $this->databaseB->select('title')->from('books')->where('id = %i', $bk['id'])->fetchSingle();
1941 if ($i < count($redir['data'])) {
1942 $nameBooks .= " ,";
1943 }
1944 }
1945 $this->flashMessage("Nebylo možné provést rezervaci některých knih ( {$nameBooks} ), zkuste to prosím později", 'error');
1946 $this->redirect('Cart:Payment');
1947 }
1948 $this->cart->removeAllByUser($this->getUser()->id);
1949 $this->user->setLogConsents('create_order', $idUser, 1);
1950 unset($this->getSession('order')->data);
1951 if (empty($redir["pay_redir"])) {
1952 $this->redirect("Cart:complete", "fe-" . $redir["id"]);
1953 }
1954 $this->redirectUrl($redir["pay_redir"]);
1955 } else {
1956 $this->flashMessage("V košíku nemáte žádné položky", 'error');
1957 $this->redirect('Cart:default');
1958 }
1959 } catch (\Dibi\Exception $e) {
1960 if (!empty($e->getMessage())) {
1961 $this->presenter->flashMessage($e->getMessage(), 'error');
1962 }
1963 $this->redirect('this');
1964 }
1965 }
1966
1967
1968 public function createComponentMightLikeListControl()
1969 {
1970 $list = $this->homePageListControl->create();
1971 $list->setHeadline('Mohlo by se vám líbit');
1972 $list->setData($this->product->getBooksByCategoryId(4)[0], $this->wishes);
1973 return $list;
1974 }
1975
1976 public function handleRemoveItemFromCart(
1977 $id, $quantity = 1
1978 )
1979 {
1980 /*if (!empty($this->getSession("cart")->sale_id_book)) {
1981 $to_delete = [];
1982 foreach ($this->getSession("cart")->sale_id_book as $key => $sale) {
1983 if ($sale == explode('-', $id)[0]) {
1984 $to_delete[] = $sale;
1985 unset($this->getSession("cart")->sale_id_book);
1986 unset($this->getSession('cart')->sale);
1987 unset($this->getSession('cart')->sale_type);
1988 $this->cart->removeCartSale($this->getUser()->id);
1989 }
1990 }
1991
1992 foreach($to_delete as $id) {
1993 unset($this->getSession("cart")->sale_id_book[$id]);
1994 }
1995
1996 if (empty($this->getSession("cart")->sale_id_book)) {
1997 unset($this->getSession('cart')->sale);
1998 unset($this->getSession('cart')->sale_type);
1999 $this->cart->removeCartSale($this->getUser()->id);
2000 }
2001 }
2002
2003
2004 if (isset($this->getSession("cart")->sale_id_book)) {
2005 if ($this->getSession("cart")->sale_id_book == $id) {
2006 unset($this->getSession("cart")->sale);
2007 unset($this->getSession("cart")->sale_type);
2008 unset($this->getSession("cart")->sale_id_book);
2009 }
2010 }*/
2011
2012 if ($this->getUser()->isLoggedIn()) {
2013 $data = explode("-", $id);
2014 if (count($data) > 3) {
2015 $this->cart->removeByUser($this->getUser()->id, [
2016 "id_voucher_motiv" => $data[0],
2017 "text" => $data[3]
2018 ]);
2019 } else {
2020 $this->cart->removeByUser($this->getUser()->id, [
2021 "id_book" => $data[0],
2022 "order_type" => $data[1],
2023 "quantity" => $quantity
2024 ]);
2025 }
2026 }
2027
2028 if (!empty($this->getSession('cart')->items[$id]) && $this->getSession('cart')->items[$id] > 1) {
2029 $this->getSession('cart')->items[$id] -= $quantity;
2030 if(!$this->getSession('cart')->items[$id]) {
2031 unset($this->getSession('cart')->items[$id]);
2032 }
2033 } else {
2034 unset($this->getSession('cart')->items[$id]);
2035 }
2036 if (empty($this->getSession('cart')->items)) {
2037 unset($this->getSession("cart")->code);
2038 unset($this->getSession("cart")->sale);
2039 unset($this->getSession("cart")->sale_type);
2040 unset($this->getSession("cart")->sale_id_book);
2041 unset($this->getSession('cart')->credit);
2042 }
2043
2044 if (explode("-", $id)[1] == "gVoucher") {
2045 $this->flashMessage('Dárkový poukaz byl odebrán z košíku', 'info');
2046 } else {
2047 $this->flashMessage(
2048 'Položka "' . $this->product->getBookTitleById(explode('-', $id)[0]) . '" byla odebrána z košíku',
2049 'info'
2050 );
2051 }
2052
2053 $this->redrawControl('cartSnippet');
2054 $this->redrawControl('content');
2055 $this->redrawControl('cartItems');
2056 $this->redrawControl('cartPrice');
2057 $this->redrawControl('cartPriceMobile');
2058 $this->redrawControl('fMessages');
2059 }
2060
2061 public function handleRemoveAllFromCart()
2062 {
2063 unset($this->getSession("cart")->code);
2064 unset($this->getSession('cart')->items);
2065 unset($this->getSession("cart")->sale);
2066 unset($this->getSession("cart")->sale_type);
2067 unset($this->getSession("cart")->sale_id_book);
2068 unset($this->getSession('cart')->credit);
2069
2070 if ($this->getUser()->isLoggedIn()) {
2071 $this->cart->removeAllByUser($this->getUser()->id);
2072 }
2073 $this->flashMessage('Všechny položky z košíku byly odstraněny', 'info');
2074 $this->redrawControl('cartSnippet');
2075 $this->redrawControl('content');
2076 $this->redrawControl('cartItems');
2077 $this->redrawControl('cartPrice');
2078 $this->redrawControl('cartPriceMobile');
2079 $this->redrawControl('fMessages');
2080 }
2081
2082 public function createComponentAddressForm()
2083 {
2084
2085 $form = new Form();
2086 $form->addText('firstname', 'Jméno')->setRequired("Zadejte jméno");
2087 $form->addText('surname', 'Příjmení')->setRequired("Zadejte příjmení");
2088 $form->addText('city', 'Město')->setRequired("Zadejte město");
2089 $form->addText('email', 'E-mail')
2090 ->setRequired("Zadejte email")
2091 ->addRule(Form::EMAIL, 'E-mail není ve správnem tvaru');
2092 $form->addText('street', 'Ulice a číslo popisné')
2093 ->setRequired("Ulice a číslo popisné")
2094 ->addRule(Form::MIN_LENGTH, "Neplatná ulice", '2');
2095 $form->addText('postal_code', 'PSČ')
2096 ->setRequired("Zadejte psč")
2097 ->addRule(Form::PATTERN, 'PSČ musí mít 5 číslic', '([0-9]\s*){5}');
2098 $form->addText('phone', 'Telefon')
2099 ->setRequired("Zadejte telefon")
2100 ->addRule(Form::PATTERN, 'Telefon nemá správny formát', '^(\+420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$');
2101
2102
2103 $form->addCheckbox('alternative', 'Fakturační adresa je jiná než doručovací');
2104 $form->addText('alternative_name', 'Jméno a příjmení (název firmy)')
2105 ->addConditionOn($form['alternative'], Form::EQUAL, true)
2106 ->setRequired('Toto pole je povinné');
2107
2108 $form->addText('alternative_city', 'Město')
2109 ->addConditionOn($form['alternative'], Form::EQUAL, true)
2110 ->setRequired('Toto pole je povinné');
2111
2112 $form->addText('alternative_street', 'Ulice a číslo popisné')
2113 ->addConditionOn($form['alternative'], Form::EQUAL, true)
2114 ->addRule(Form::MIN_LENGTH, "Neplatná ulice", '2')
2115 ->setRequired('Toto pole je povinné');
2116
2117 $form->addText('alternative_postal_code', 'Psč')
2118 ->addConditionOn($form['alternative'], Form::EQUAL, true)
2119 ->addRule(Form::PATTERN, 'PSČ musí mít 5 číslic', '([0-9]\s*){5}')
2120 ->setRequired('Toto pole je povinné');
2121
2122
2123 $form->addCheckbox('on_company', ' Nakupují na firmu');
2124 $form->addText('company_name', 'Název firmy')
2125 ->addConditionOn($form['on_company'], Form::EQUAL, true)
2126 ->setRequired('Toto pole je povinné');
2127 $form->addText('company_ic', 'IČO')
2128 ->addConditionOn($form['on_company'], Form::EQUAL, true)
2129 ->setRequired('Toto pole je povinné');
2130 $form->addText('company_dic', 'DIČ')
2131 ->addConditionOn($form['on_company'], Form::EQUAL, true)
2132 ->setRequired('Toto pole je povinné');
2133
2134 if ($this->getUser()->isLoggedIn()) {
2135 $idUser = $this->getUser()->getId();
2136 $values = $this->user->getAddress($idUser)[0];
2137 $values['postal_code'] = $values['zip'];
2138 unset($values['zip']);
2139 $values['email'] = $this->getUser()->getIdentity()->email;
2140 $values['company_name'] = $values['com_name'];
2141 $values['company_ic'] = $values['IC'];
2142 $values['company_dic'] = $values['DIC'];
2143 $form->setDefaults($values);
2144 }
2145 }
2146}
2147