<?php

/**
 * Copyright La boîte à pain (2018)
 *
 * contact@souke.fr
 *
 * Ce logiciel est un programme informatique servant à aider les producteurs
 * à distribuer leur production en circuits courts.
 *
 * Ce logiciel est régi par la licence CeCILL soumise au droit français et
 * respectant les principes de diffusion des logiciels libres. Vous pouvez
 * utiliser, modifier et/ou redistribuer ce programme sous les conditions
 * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
 * sur le site "http://www.cecill.info".
 *
 * En contrepartie de l'accessibilité au code source et des droits de copie,
 * de modification et de redistribution accordés par cette licence, il n'est
 * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,
 * seule une responsabilité restreinte pèse sur l'auteur du programme,  le
 * titulaire des droits patrimoniaux et les concédants successifs.
 *
 * A cet égard  l'attention de l'utilisateur est attirée sur les risques
 * associés au chargement,  à l'utilisation,  à la modification et/ou au
 * développement et à la reproduction du logiciel par l'utilisateur étant
 * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
 * manipuler et qui le réserve donc à des développeurs et des professionnels
 * avertis possédant  des  connaissances  informatiques approfondies.  Les
 * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du
 * logiciel à leurs besoins dans des conditions permettant d'assurer la
 * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
 * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
 *
 * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
 * pris connaissance de la licence CeCILL, et que vous en avez accepté les
 * termes.
 */

use common\helpers\Environment;
use common\helpers\GlobalParam;
use common\helpers\Image;
use domain\Feature\Feature\Feature;
use domain\Feature\Feature\FeatureModule;
use domain\Order\Order\Order;
use domain\Order\Order\OrderRepositoryQuery;
use domain\PointSale\PointSale\PointSaleModule;
use domain\Producer\Producer\ProducerModule;
use domain\Product\Product\ProductModule;
use domain\User\User\UserModule;
use domain\User\UserProducer\UserProducer;
use yii\bootstrap5\Nav;
use yii\helpers\Html;

\common\assets\CommonAsset::register($this);
\producer\assets\AppAsset::register($this);

$userModule = UserModule::getInstance();
$userCurrent = GlobalParam::getCurrentUser();
$producerModule = ProducerModule::getInstance();
$featureModule = FeatureModule::getInstance();
$productModule = ProductModule::getInstance();
$pointSaleModule = PointSaleModule::getInstance();
$userMessageModule = $this->getUserMessageModule();
$producerUser = null;
if ($userModule->getAuthorizationChecker()->isGrantedAsProducer($userCurrent)) {
    $producerUser = $producerModule->findOneProducerById($userCurrent->id_producer);
}
$producer = $this->context->getProducerCurrent();
if (!Yii::$app->user->isGuest) {
    $userProducer = UserProducer::findOne(['id_user' => GlobalParam::getCurrentUserId(), 'id_producer' => $producer->id]);
}

$mainColor = $producer->option_main_color ?: '#ee6f42' ;

?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="fr-FR">
<head>
    <title>
        <?php if($this->getControllerAction() == 'site/index'): ?>
            <?= Html::encode($producer->name); ?> | <?= $this->getPageTitle(); ?>
        <?php else: ?>
            <?= $this->getPageTitle(); ?> | <?= Html::encode($producer->name); ?>
        <?php endif; ?>
    </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="base-url" content="<?= \Yii::$app->urlManager->baseUrl; ?>">
    <meta name="slug-producer" content="<?= $producer->slug; ?>">
    <?= Environment::metaRobotsNoIndexBeta(); ?>
    <?= Html::csrfMetaTags() ?>
    <link rel="icon" type="image/png"
          href="<?php echo \Yii::$app->urlManager->getBaseUrl(); ?>/img/favicon-souke-1.png"/>
    <?php $this->head() ?>
    <?= $this->render('@common/views/matomo.php') ?>
    <style>
        #header #title h1 a.producer-name,
        #header #title h2 .location .bi,
        #content a,
        .credit-history #credit-user,
        .credit-history #content .table span.payment-positive,
        .order-order #main #app-order-order #steps ul li .info-step,
        .block-date .month,
        #footer-producer a {
            color: <?= $mainColor ?>
        }
        #header nav#main-nav ul a.active,
        #header nav#main-nav ul li a:hover,
        #header nav#main-nav ul li a span.label-success,
        #main .btn-primary,
        .order-order #main #app-order-order #steps ul li .btn.btn-primary,
        ul.pagination li.active a, ul.pagination li a:hover, ul.pagination li a:focus, ul.pagination li a:active,
        .order-order #main #app-order-order table#products tr.total .price-total span,
        .subscription-create .subscription-form .products tr.total .price-total span,
        .subscription-update .subscription-form .products tr.total .price-total span {
            background-color: <?= $mainColor ?>;
        }
        #main .badge.bg-primary {
            background-color: <?= $mainColor ?> !important;
        }
        #header nav#main-nav {
            border-top: solid 5px <?= $mainColor ?>;
        }
        #main form .form-control:focus {
            box-shadow: 0px 0px 0px 1px <?= $mainColor ?>;
            border: solid 1px <?= $mainColor ?>;
        }
        .order-order #main #app-order-order #steps ul li .btn.btn-primary::after {
            border-left: 17px solid <?= $mainColor ?>;
        }
        #header nav#main-nav ul li a span.label.label-success {
            border: solid 1px <?= $mainColor ?>;
        }
        .order-order #main #app-order-order table#products tr.category-open td.category-name,
        .order-order #main #app-order-order table#products tr.category-closed td.category-name:hover{
            border-left-color: <?= $mainColor ?>;
        }
    </style>
</head>
<body class="<?= \Yii::$app->controller->id . '-' . \Yii::$app->controller->action->id ?>">
<?php $this->beginBody() ?>

<?= $this->render('@common/views/nav_user_top', [
    'context' => 'producer'
]); ?>

<div id="main" class="container">
    <?php $hasLogo = strlen($producer->logo) && Image::isPhotoExist($producer->logo); ?>
    <div id="header" class="<?= $hasLogo ? 'with-logo' : 'without-logo'; ?>">
        <?php if (strlen($producer->photo) || strlen($producer->logo)): ?>
            <div id="banner" style="background-color: <?= $mainColor ?>;<?php if(strlen($producer->photo)): ?>background-image:url(<?= \Yii::$app->urlManager->baseUrl; ?>/uploads/<?= urlencode($producer->photo); ?>);<?php endif; ?>">
            </div>
        <?php endif; ?>
        <?php if ($hasLogo): ?>
            <div id="logo"<?php if (!is_null($producer->background_color_logo) && strlen($producer->background_color_logo)): ?> style="background-color:<?= Html::encode($producer->background_color_logo); ?>"<?php endif; ?>>
                <a href="<?= \Yii::$app->urlManager->createUrl(['site/index']) ?>">
                    <img class="img-logo"
                         src="<?= \Yii::$app->urlManager->baseUrl; ?>/uploads/<?= $producer->logo; ?>"
                         alt="Logo <?= Html::encode($producer->name) ?>"/>
                </a>
            </div>
        <?php endif; ?>
        <div id="title">
            <h1>
                <a class="producer-name" href="<?= Yii::$app->urlManager->createUrl(['site/index']); ?>">
                    <?= Html::encode($producer->name); ?>
                </a>
                <?php if (!Yii::$app->user->isGuest): ?>
                    <?php if ($userProducer && $userProducer->bookmark): ?>
                        <a class="bookmark"
                           href="<?= \Yii::$app->urlManagerProducer->createUrl(['site/bookmarks', 'action' => 'delete']); ?>"
                           data-bs-toggle="tooltip" data-bs-placement="top" title="Supprimer de ma liste de producteurs">
                            <i class="bi bi-bookmark-heart-fill"></i>
                        </a>
                    <?php else: ?>
                        <a class="bookmark"
                           href="<?= \Yii::$app->urlManagerProducer->createUrl(['site/bookmarks', 'action' => 'add']); ?>"
                           data-bs-toggle="tooltip" data-bs-placement="top"
                           title="Ajouter à ma liste de producteurs">
                            <i class="bi bi-bookmark-heart"></i>
                        </a>
                    <?php endif; ?>
                <?php endif; ?>
            </h1>
            <h2>
                <?= Html::encode($producer->type) ?>
                <span class="location">
                    <i class="bi bi-geo-alt-fill"></i>
                    <?= Html::encode($producer->postcode); ?> <?= Html::encode($producer->city); ?>
                </span>
            </h2>
        </div>
        <nav id="main-nav">
            <?php
            $credit = '';
            if (isset($userProducer) && $userProducer) {
                $labelType = $userProducer->credit > 0 ? 'success' : 'danger';
                $credit = ' <span class="label label-' . $labelType . '">' . number_format($userProducer->credit, 2, ',', ' ') . ' €</span>';
            }

            $countSubcriptions = 0;
            if ($userCurrent) {
                $countSubcriptions = $this->getSubscriptionModule()->countSubscriptionsByUser(
                    $userCurrent
                );
            }

            $labelSubscription = $countSubcriptions > 0 ? 'success' : 'default';

            $countOrders = Order::find()
                ->joinWith(['distribution'])
                ->where([
                    'id_user' => GlobalParam::getCurrentUserId(),
                    'distribution.id_producer' => GlobalParam::getCurrentProducerId()
                ])
                ->params([':date_today' => date('Y-m-d')])
                ->andWhere('distribution.date >= :date_today')
                ->andWhere(OrderRepositoryQuery::getSqlFilterIsValid())
                ->count();
            $labelOrders = $countOrders > 0 ? 'success' : 'default';

            $isUserSubscribedNewsletter = $userModule->isUserSubscribedNewsletter($userCurrent);
            $isHome = in_array($this->getControllerAction(), ['site/index', 'site/products', 'site/points-sale']);

            echo Nav::widget([
                'encodeLabels' => false,
                'options' => ['class' => ''],
                'items' => [
                    [
                        'url' => $this->getUrlManagerProducer()->createUrl(['site/index']),
                        'label' => '<i class="bi bi-house-door"></i> <span class="hide-desktop"> Accueil</span>',
                        'active' => $isHome,
                    ],
                    [
                        'label' => '<i class="bi bi-pencil-square"></i> Commander',
                        'url' => $this->getUrlManagerProducer()->createUrl(['order/order']),
                        'visible' => $producer->option_allow_order_guest || !Yii::$app->user->isGuest,
                        'active' => in_array($this->getControllerAction(),  ['order/order', 'order/confirm']),
                    ],
                    [
                        'label' => '<i class="bi bi-pencil-square"></i> Commander',
                        'url' => $this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $this->context->getProducerCurrent()->id, 'return_url' => \Yii::$app->urlManagerProducer->createAbsoluteUrl(['order/order', 'slug_producer' => $this->context->getProducerCurrent()->slug])]),
                        'visible' => !$producer->option_allow_order_guest && \Yii::$app->user->isGuest,
                        'active' => in_array($this->getControllerAction(),  ['order/order', 'order/confirm']),
                    ],
                    [
                        'label' => '<i class="bi bi-folder2-open"></i> Mes commandes <span class="label label-' . $labelOrders . '">' . $countOrders . '</span>',
                        'url' => $this->getUrlManagerProducer()->createUrl(['order/history']),
                        'visible' => !Yii::$app->user->isGuest,
                        'active' => $this->getControllerAction() == 'order/history',
                    ],
                    [
                        'label' => '<i class="bi bi-arrow-repeat"></i> Abonnements <span class="label label-' . $labelSubscription . '">' . $countSubcriptions . '</span>',
                        'url' => $this->getUrlManagerProducer()->createUrl(['subscription/index']),
                        'visible' => !Yii::$app->user->isGuest && $producer->user_manage_subscription,
                        'active' => in_array($this->getControllerAction(), ['subscription/index', 'subscription/form']),
                    ],
                    [
                        'label' => '<i class="bi bi-piggy-bank"></i> Cagnotte' . $credit,
                        'url' => $this->getUrlManagerProducer()->createUrl(['credit/history']),
                        'visible' => !Yii::$app->user->isGuest && $producer->credit,
                        'active' => $this->getControllerAction() == 'credit/history',
                    ],
                    [
                        'label' => '<i class="bi bi-megaphone"></i> Infolettre <span class="label label-' . ($isUserSubscribedNewsletter ? 'success' : 'danger') . '">' . ($isUserSubscribedNewsletter ? 'Oui' : 'Non') . '</span>',
                        'url' => $this->getUrlManagerProducer()->createUrl(['newsletter/index']),
                        'visible' => !Yii::$app->user->isGuest,
                        'active' => $this->getControllerAction() == 'newsletter/index',
                    ],
                    [
                        'label' => '<i class="bi bi-envelope"></i> Contact',
                        'url' => $this->getUrlManagerProducer()->createUrl(['site/contact']),
                        'active' => $this->getControllerAction() == 'site/contact',
                        'visible' => $featureModule->getChecker()->isEnabled(Feature::ALIAS_CONTACT)
                    ],
                ],
            ]);

            $submenuItems = null;
            if($isHome) {
                $submenuItems = [
                    [
                        'url' => $this->getUrlManagerProducer()->createUrl(['site/index']),
                        'label' => 'Présentation',
                        'active' => $this->getControllerAction() == 'site/index',
                    ],
                    [
                        'url' => $this->getUrlManagerProducer()->createUrl(['site/products']),
                        'label' => 'Produits <span class="label label-default">'.$productModule->getRepository()->countProducts(true).'</span>',
                        'active' => $this->getControllerAction() == 'site/products',
                    ],
                    [
                        'url' => $this->getUrlManagerProducer()->createUrl(['site/points-sale']),
                        'label' => $producerModule->getSolver()->getPointSaleWording($producer).' <span class="label label-default">'.$pointSaleModule->getRepository()->countPointSalesPublic().'</span>',
                        'active' => $this->getControllerAction() == 'site/points-sale',
                    ],
                ];
            }

            if($submenuItems) {
                echo Nav::widget([
                    'encodeLabels' => false,
                    'options' => ['class' => 'submenu'],
                    'items' => $submenuItems
                ]);
            }

            ?>
        </nav>

        <div id="infos-producer">
            <?php if (!$this->getProducerModule()->hasSpecificDelays($producer) && $producer->order_deadline && $producer->order_delay): ?>
                <span data-toggle="tooltip" data-placement="bottom" title="Heure limite de commande">
                            <span class="glyphicon glyphicon-time"></span> Commande avant
                            <strong><?php echo Html::encode($producer->order_deadline) ?> h</strong></span>,
                <span data-toggle="tooltip" data-placement="bottom"
                      title="Exemple : commande le lundi pour le
                                  <?php if ($producer->order_delay == 1): ?>mardi<?php elseif ($producer->order_delay == 2): ?>mercredi
                                  <?php elseif ($producer->order_delay == 3): ?>jeudi<?php elseif ($producer->order_delay == 4): ?>vendredi
                                  <?php elseif ($producer->order_delay == 5): ?>samedi<?php elseif ($producer->order_delay == 6): ?>dimanche
                                  <?php elseif ($producer->order_delay == 7): ?>lundi d'après<?php endif; ?>"><strong><?= Html::encode($producer->order_delay) ?> jour<?php if ($producer->order_delay > 1): ?>s<?php endif; ?></strong> à l'avance</span>
            <?php endif; ?>
            <div class="clr"></div>
        </div>
    </div>

    <section id="content">

        <?php
        // Message utilisateur
        if($userCurrent):
            $userMessagesArray = $userMessageModule->getRepository()->findUserMessagesUnreadByUser($userCurrent);
            if($userMessagesArray && count($userMessagesArray)):
                foreach($userMessagesArray as $userMessage): ?>
                    <div class="alert alert-info">
                        <h4 class="alert-heading">
                            <i class="bi bi-envelope"></i>
                            Nouveau message
                        </h4>
                        <p><?= nl2br(Html::encode($userMessage->getMessage())) ?></p>
                        <p>
                            <a class="alert-link" href="<?= Yii::$app->urlManager->createUrl(['site/'.($userModule->getAuthorizationChecker()->isGrantedAsAdministrator($userMessage->getCreatedBy()) ? 'support' : 'contact')]); ?>">
                                Répondre</a>
                            &bull;
                            <a class="alert-link" href="<?= Yii::$app->urlManager->createUrl(['site/user-message-read', 'idUserMessage' => $userMessage->getId()]); ?>">
                                Fermer
                            </a>
                        </p>
                    </div>
                <?php endforeach;
            endif;
        endif; ?>

        <?php
        // Message congés
        $leavePeriodMessageDisplay = $producerModule->getSolver()->getConfig('option_leave_period_message_display', $producer);
        $leavePeriodMessageTitle = $producerModule->getSolver()->getConfig('option_leave_period_message_title', $producer);
        $leavePeriodMessage = $producerModule->getSolver()->getConfig('option_leave_period_message', $producer);
        if($leavePeriodMessageDisplay && ($leavePeriodMessageTitle || $leavePeriodMessage)): ?>
            <div class="alert alert-warning alert-leave-period">
                <?php if($leavePeriodMessageTitle): ?>
                    <h4 class="alert-heading<?php if(!$leavePeriodMessage): ?> without-message<?php endif; ?>">
                        <i class="bi bi-calendar-range"></i>
                        <?= $leavePeriodMessageTitle ?>
                    </h4>
                <?php endif; ?>
                <?php if($leavePeriodMessage): ?>
                    <p>
                        <?php if(!$leavePeriodMessageTitle): ?><i class="bi bi-calendar-range"></i><?php endif; ?>
                        <?= nl2br(Html::encode($leavePeriodMessage)) ?>
                    </p>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if (strlen($this->getTitle())): ?>
            <h2 id="page-title">
                <?= $this->getTitle(); ?>
                <?php
                if ($this->buttons && count($this->buttons)): ?>
                    <span id="buttons">
                            <?php foreach ($this->buttons as $button) {
                                echo '<a href="' . \Yii::$app->urlManagerProducer->createUrl($button['url']) . '" class="' . $button['class'] . '">' . $button['label'] . '</a>';
                            }
                            ?>
                            </span>
                <?php endif; ?>
            </h2>
        <?php endif; ?>

        <?php if (Yii::$app->session->hasFlash('error')): ?>
            <div class="alert alert-danger" role="alert">
                <?= \Yii::$app->session->getFlash('error') ?>
            </div>
        <?php endif; ?>
        <?php if (Yii::$app->session->hasFlash('success')): ?>
            <div class="alert alert-success" role="alert">
                <?= \Yii::$app->session->getFlash('success') ?>
            </div>
        <?php endif; ?>

        <?= $content ?>
    </section>
</div>

<?php if (strlen($producer->mentions) || strlen($producer->gcs)): ?>
    <div id="footer-producer">
        <?php if (strlen($producer->mentions)): ?>
            <a href="<?php echo \Yii::$app->urlManager->createUrl(['site/mentions']); ?>">Mentions légales</a>
        <?php endif; ?>
        <?php if (strlen($producer->mentions) && strlen($producer->gcs)): ?> | <?php endif; ?>
        <?php if (strlen($producer->gcs)): ?>
            <a href="<?php echo \Yii::$app->urlManager->createUrl(['site/gcs']); ?>">Conditions générales de vente</a>
        <?php endif; ?>
    </div>
<?php endif; ?>

<footer id="footer" class="container">
    <div class="content">
        <!--<a href="<?php echo \Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/index']); ?>">Souke</a> &bull;
        <a href="<?php echo \Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/mentions']); ?>">Mentions légales</a> &bull;
        <a href="<?php echo \Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/cgv']); ?>">CGS</a>-->

        <?php if($featureModule->getChecker()->isEnabled(Feature::ALIAS_SHOP_SUPPORT)): ?>
            <div id="button-shop-support">
                <a href="<?= Yii::$app->urlManager->createUrl(['site/support']) ?>" class="btn btn-sm btn-secondary">
                    <i class="bi bi-life-preserver"></i>
                    Besoin d'aide ?
                </a>
            </div>
        <?php endif; ?>

    </div>
</footer>
<script type="text/javascript" src="https://cdn.polyfill.io/v3/polyfill.min.js?features=Intl.~locale.fr"></script>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
