<?php

/**
Copyright distrib (2018)

contact@opendistrib.net

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\GlobalParam ;
use common\models\Producer ;
use common\models\Distribution ;

\producer\assets\VuejsOrderOrderAsset::register($this);

$this->setTitle('Commander') ;

$producer = GlobalParam::getCurrentProducer() ;

?>

<script>
    var appInitValues = {
    };
</script>

<div id="app-order-order" :class="{'loaded': !loadingInit}">

    <?php if(isset($order)): ?>
        <span id="order-distribution-date"><?= $order->distribution->date; ?></span>
    <?php endif; ?>
    <?php if(isset($date)): ?>
        <span id="distribution-date"><?= $date; ?></span>
    <?php endif; ?>
    <div v-if="loadingInit && distributions.length == 0" class="alert alert-warning">
        Aucune distribution n'est prévue chez ce producteur.
    </div>
    <div v-else>
        <div>
            <div id="steps">
                <ul>
                    <?php if($producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_DATE): ?>
                        <step-date
                                first="true"
                                :step="step"
                                :point-sale-active="pointSaleActive"
                                :date-format="dateFormat"
                                :change-step="changeStep"
                                :producer="producer"
                        ></step-date>
                        <step-point-sale
                                :step="step"
                                :point-sale-active="pointSaleActive"
                                :change-step="changeStep"
                                :producer="producer"
                        ></step-point-sale>
                    <?php else: ?>
                        <step-point-sale
                                first="true"
                                :step="step"
                                :point-sale-active="pointSaleActive"
                                :change-step="changeStep"
                                :producer="producer"
                        ></step-point-sale>
                        <step-date
                                :step="step"
                                :point-sale-active="pointSaleActive"
                                :date-format="dateFormat"
                                :change-step="changeStep"
                                :producer="producer"
                        ></step-date>
                    <?php endif; ?>

                    <li id="step-products" :class="'col-md-3 '+((step == 'products') ? 'active ' : '')">
                        <button @click="changeStep('products')" :class="'btn '+ (step == 'products' ? 'btn-primary' : 'btn-default')" :disabled="step == 'date' || step == 'point-sale'">
                            <span class="button-content"><span class="glyphicon glyphicon-th-list"></span> Produits</span>
                        </button>
                        <div class="info-step" v-if="oneProductOrdered()">
                            {{ countProductOrdered() }} produit{{ (countProductOrdered() > 1) ? 's' : '' }}
                        </div>
                    </li>
                    <li id="step-payment" :class="'col-md-3 '+((step == 'payment') ? 'active' : '')">
                        <button @click="changeStep('payment')" :class="'btn '+ (step == 'payment' ? 'btn-primary' : 'btn-default')" :disabled="step == 'date' || step == 'point-sale' || step == 'products'">
                            <span class="button-content"><span class="glyphicon glyphicon-ok"></span> Confirmation</span>
                        </button>
                    </li>
                </ul>
                <div class="clr"></div>
            </div>
            <div class="content">
                <div v-if="errors && errors.length" class="alert alert-danger">
                    <ul>
                        <li v-for="error in errors">
                            <div v-html="error"></div>
                        </li>
                    </ul>
                </div>
                <div v-if="loading && !step">
                    Chargement ...
                </div>
                <transition name="slide">
                    <div id="content-step-date" v-if="step == 'date'">
                        <div v-if="loading">
                            Chargement ...
                        </div>
                        <div v-else>
                            <?php if($producer->behavior_order_select_distribution == Producer::BEHAVIOR_ORDER_SELECT_DISTRIBUTION_LIST ): ?>
                                <div style="display:none ;">
                            <?php endif; ?>
                            <div id="legend">
                                <div><span id="distribution-date-color"></span> Prochains jours de distribution</div>
                                <div><span id="order-date-color"></span> Vos commandes déjà enregistrées</div>
                            </div>
                            <div id="calendar">
                                <v-calendar
                                        is-inline
                                        is-double-paned
                                        is-expanded
                                        v-model="date"
                                        mode="single"
                                        locale="fr-FR"
                                        :locale="{ id: 'fr_FR', firstDayOfWeek: 1, masks: { weekdays: 'WW' } }"
                                        :formats="calendar.formats"
                                        :theme-styles="calendar.themeStyles"
                                        :attributes="calendar.attrs"
                                        :available-dates="calendar.availableDates"
                                        @dayclick='dayClick'
                                ></v-calendar>
                            </div>
                            <?php if($producer->behavior_order_select_distribution == Producer::BEHAVIOR_ORDER_SELECT_DISTRIBUTION_LIST ): ?>
                                </div>
                            <?php endif; ?>

                            <?php if($producer->behavior_order_select_distribution == Producer::BEHAVIOR_ORDER_SELECT_DISTRIBUTION_LIST ): ?>
                                    <div id="distributions-list">
                                        <?php $incomingDistributions = Distribution::getIncomingDistributions(); ?>
                                        <?php foreach($incomingDistributions as $distribution): ?>

                                            <?php
                                                $pointSaleDistributions = PointSaleDistribution::searchAll([
                                                        'id_distribution' => $distribution->id,
                                                        'delivery' => 1
                                                ], [], [
                                                    'with' => 'pointSale'
                                                ]);
                                            ?>

                                            <div class="panel panel-default">
                                                    <div class="panel-body">
                                                        <button class="btn btn-primary" @click="dayClickList" data-distribution-date="<?= $distribution->date.' 00:00:00' ?>">Sélectionner cette distribution</button>
                                                        <span class="date"><?= ucfirst(strftime('%A %d %B', strtotime($distribution->date))); ?></span>
                                                        <?php
                                                                if($pointSaleDistributions && count($pointSaleDistributions) > 0) {
                                                                        echo '<div class="point-sales">' ;
                                                                        foreach($pointSaleDistributions as $pointSaleDistribution) {
                                                                                echo $pointSaleDistribution->pointSale->name.'' ;
                                                                                if(strlen($pointSaleDistribution->pointSale->locality)) {
                                                                                        echo ' ('.$pointSaleDistribution->pointSale->locality.')' ;
                                                                                }
                                                                                echo '<br />' ;
                                                                        }
                                                                        echo '</div>' ;
                                                                }
                                                        ?>
                                                    </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </transition>
                <transition name="slide">
                    <div id="content-step-point-sale" v-if="step == 'point-sale'">
                        <div v-if="loading">
                            Chargement ...
                        </div>
                        <div v-else>
                            <h3>Où souhaitez-vous récupérer votre commande ?</h3>
                            <table id="points-sale" class="table table-bordered" v-if="pointsSale.length">
                                <thead>
                                    <tr>
                                        <th>Nom</th>
                                        <th>Localité</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="pointSale in orderedPointsSale" v-if="pointSale && (producer.option_order_entry_point == 'point-sale' || (producer.option_order_entry_point == 'date' && pointSale.pointSaleDistribution.delivery))" :class="(pointSaleActive && pointSale.id == pointSaleActive.id) ? 'selected' : ''">
                                        <td class="name">
                                            <span class="the-name">{{ pointSale.name }}</span>
                                            <div class="comment" v-if="pointSale.userPointSale">
                                                {{ pointSale.userPointSale.comment }}
                                            </div>
                                        </td>
                                        <td class="locality">{{ pointSale.locality }}</td>
                                        <td class="actions">
                                            <div :class="'form-group' + (pointSale.invalid_code ? ' has-error' : '')">
                                                <div class="input-group" v-if="pointSale.code.length > 0">
                                                    <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
                                                    <input v-model="pointsSaleCodes[pointSale.id]" type="password" placeholder="Code" class="form-control input-code" />
                                                </div>
                                            </div>
                                            <button class="btn btn-primary" @click="pointSaleClick" :data-code="pointSale.code.length > 0" :data-id-point-sale="pointSale.id">
                                                <span class="glyphicon glyphicon-map-marker"></span>
                                                Choisir
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <div class="alert alert-warning" v-else>
                                Aucun point de vente disponible pour ce jour de distribution.
                            </div>
                        </div>
                    </div>
                </transition>
                <transition name="slide">
                    <div id="content-step-products" v-if="step == 'products'">
                        <div v-if="loading">
                            Chargement ...
                        </div>
                        <div v-else>
                            <div v-if="products.length">
                                <table id="products" class="table table-bordered" >
                                    <thead>
                                        <tr>
                                            <th>Photo</th>
                                            <th>Nom</th>
                                            <th>Prix unitaire</th>
                                            <th>Quantité</th>
                                            <th>Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <template v-for="category in categories">
                                            <tr v-if="category.id && countProductsByCategory(category)">
                                                <td class="category-name" colspan="5" @click="setCategoryCurrent(category)">
                                                    <span v-if="categoryCurrent && categoryCurrent.id == category.id" class="glyphicon glyphicon-triangle-bottom"></span>
                                                    <span v-else class="glyphicon glyphicon-triangle-right"></span>
                                                    {{ category.name }}
                                                    <span class="label label-default">{{ countProductsByCategory(category) }} produit<template v-if="countProductsByCategory(category) > 1">s</template></span>
                                                    <span v-if="countSelectedProductsByCategory(category) > 0" class="label label-success">{{ countSelectedProductsByCategory(category) }} produit<template v-if="countSelectedProductsByCategory(category) > 1">s</template> sélectionné<template v-if="countSelectedProductsByCategory(category) > 1">s</template></span>
                                                </td>
                                            </tr>
                                            <template v-if="(categoryCurrent && categoryCurrent.id == category.id) || category.id == null">
                                                <tr v-for="product in products" v-if="product.id_product_category == category.id && product.productDistribution && product.productDistribution[0] && product.productDistribution[0].active == 1">
                                                    <td class="photo">
                                                        <img v-if="product.photo.length" class="photo-product" :src="'<?php echo Yii::$app->urlManager->getBaseUrl(); ?>/uploads/'+product.photo" />
                                                    </td>
                                                    <td class="name">
                                                        <span class="name">{{ product.name }}</span>
                                                        <span class="other">
                                                        <span v-if="product.description.length">/</span>
                                                        <span class="description">{{ product.description }}</span>
                                                        <span v-if="product.weight">({{ product.weight }}&nbsp;g)</span>
                                                    </span>
                                                        <span v-if="product.quantity_max > 0 && ((product.quantity_form / product.coefficient_unit == product.quantity_remaining) || ((product.quantity_remaining * product.coefficient_unit) - product.quantity_form) < product.step)" class="label label-danger">
                                                        Épuisé
                                                    </span>
                                                        <div class="recipe" v-if="product.recipe.length">{{ product.recipe }}</div>
                                                    </td>
                                                    <td class="price-unit">
                                                        <template v-if="product.price_with_tax >= 0">{{ formatPrice(product.price_with_tax) }}<br /><span class="unit">{{ product.wording_unit }}</span></template>
                                                    </td>
                                                    <td class="td-quantity">
                                                        <template v-if="product.price_with_tax >= 0">
                                                            <div class="input-group">
                                                                <span class="input-group-btn">
                                                                    <button class="btn btn-default btn-moins" type="button" @click="productQuantityClick(product, product.unit == 'piece' ? -1 : -parseFloat(product.step))" :disabled="product.quantity_form == 0"><span class="glyphicon glyphicon-minus"></span></button>
                                                                </span>
                                                                <input type="text" v-model="product.quantity_form" class="form-control quantity" readonly="readonly" />
                                                                <span class="input-group-addon">{{ product.unit == 'piece' ? 'p.' : product.unit }}</span>
                                                                <span class="input-group-btn">
                                                                    <button class="btn btn-default btn-plus" type="button" @click="productQuantityClick(product, product.unit == 'piece' ? 1 : parseFloat(product.step))" :disabled="product.quantity_form == product.quantity_remaining && product.quantity_max > 0"><span class="glyphicon glyphicon-plus"></span></button>
                                                                </span>
                                                            </div>
                                                        </template>
                                                    </td>
                                                    <td class="price-total">
                                                        <template v-if="product.price_with_tax >= 0 && product.quantity_form > 0">
                                                            {{ formatPrice(product.price_with_tax * (product.quantity_form / product.coefficient_unit )) }}
                                                        </template>
                                                    </td>
                                                </tr>
                                            </template>
                                        </template>
                                        <tr class="total">
                                            <td class="summary" colspan="4">
                                                <template v-if="priceTotal() > 0">
                                                    <h3>&gt; Résumé</h3>
                                                    <ul>
                                                        <li v-for="product in products" v-if="product.quantity_form > 0">
                                                            <span class="quantity">{{ product.quantity_form }} {{ product.unit == 'piece' ? 'p.' : product.unit }} x</span>
                                                            <span class="name">{{ product.name }}</span>
                                                            <span class="other">
                                                            <span v-if="product.description.length">/</span>
                                                            <span class="description">{{ product.description }}</span>
                                                            <span v-if="product.weight">({{ product.weight }}&nbsp;g)</span>
                                                        </li>
                                                    </ul>
                                                </template>
                                            </td>
                                            <td class="price-total">{{ priceTotal(true) }}</td>
                                        </tr>
                                    </tbody>
                                </table>
                                <div class="block-actions">
                                    <button class="btn btn-primary" @click="changeStep('payment')">Valider</button>
                                </div>
                            </div>
                            <div class="alert alert-warning" v-else>
                                Aucun produit disponible
                            </div>
                        </div>
                    </div>
                </transition>
                <transition name="slide">
                    <div id="content-step-payment" v-if="step == 'payment'">

                        <div class="delivery">
                            <div class="delivery-home" v-if="producer.option_delivery">
                                <input type="checkbox" name="delivery" id="delivery" v-model="delivery" />
                                <label for="delivery">Je souhaite être livré à domicile</label>
                            </div>
                            <div class="delivery-address" v-if="delivery">
                                <label for="deliver-address">Adresse de livraison</label>
                                <textarea id="deliver-address" v-model="deliveryAddress" class="form-control" required="required"></textarea>
                            </div>
                        </div>

                        <div class="comment">
                            <label for="order-comment">Commentaire</label>
                            <textarea id="order-comment" v-model="comment" class="form-control"></textarea>
                        </div>

                        <template v-if="!checkCreditLimit(order) && pointSaleActive.credit_functioning == 'mandatory'">
                            <div class="alert alert-danger">Vous devez recharger votre crédit ou supprimer des produits. Votre producteur n'autorise pas un crédit inférieur à <strong>{{ formatPrice(creditLimit) }}</strong>.</div>

                            <div class="block-actions">
                                <a class="btn btn-primary" href="<?= Yii::$app->urlManager->createUrl(['site/index']) ?>">Retour à l'accueil</a>
                            </div>
                        </template>
                        <template v-else>
                            <div class="credit">
                                <div v-if="user && producer.credit == 1 && pointSaleActive.credit == 1 && (pointSaleActive.credit_functioning != 'user' || (pointSaleActive.credit_functioning == 'user' && user.credit_active))">
                                    <input type="checkbox" id="use-credit" v-model="useCredit" disabled="disabled" v-if="pointSaleActive.credit_functioning == 'mandatory' || (pointSaleActive.credit_functioning == 'user' && user.credit_active)" />
                                    <input type="checkbox" id="use-credit" v-model="useCredit" v-else /> <label for="use-credit">Utiliser mon Crédit ({{ formatPrice(user.credit) }})</label>

                                    <div class="info" v-if="useCredit">
                                        <template v-if="order == null || order.amount_paid == 0">
                                            <span v-if="checkCreditLimit(order)">{{ priceTotal(true) }} seront débités</span>
                                            <span v-else>
                                                {{ formatPrice(user.credit) }} seront débités. (Limite de crédit à {{ formatPrice(producer.credit_limit) }})<br />
                                                Restera {{ formatPrice(priceTotal() - credit) }} à régler.
                                            </span>
                                        </template>
                                        <template v-else-if="order != null && order.amount_paid > 0 && order.amount_paid < priceTotal()">
                                            <span v-if="checkCreditLimit(order)">{{ formatPrice(priceTotal() - order.amount_paid) }} seront débités</span>
                                            <span v-else>
                                                {{ formatPrice(user.credit) }} seront débités. (Limite de crédit à {{ formatPrice(producer.credit_limit) }})<br />
                                                Restera {{ formatPrice(priceTotal() - order.amount_paid - user.credit) }} à régler.
                                            </span>
                                        </template>
                                        <template v-else-if="order != null && order.amount_paid > priceTotal()">
                                            <span>{{ formatPrice(order.amount_paid - priceTotal()) }} seront remboursés</span>
                                        </template>
                                    </div>
                                </div>
                                <div v-else>
                                        <span class="glyphicon glyphicon-chevron-right"></span>
                                        <?php if($producer->option_payment_info && strlen($producer->option_payment_info) > 0): ?>
                                                Confirmez votre commande et retrouvez les informations liées au paiement sur la page suivante.
                                        <?php else: ?>
                                                La commande sera à régler sur place.
                                        <?php endif; ?>
                                </div>
                            </div>
                            <div id="signup-guest" v-if="!user && producer.option_allow_order_guest">
                                <h3>Informations personnelles</h3>
                                <form action="#">
                                    <div class="form-group field-signupguest-email required">
                                        <label class="control-label" for="signupguest-email">Email</label>
                                        <input type="email" id="signupguest-email" class="form-control" name="SignupForm[email]">
                                        <p class="help-block help-block-error"></p>
                                    </div>
                                    <!--<div class="form-group field-signupguest-password required">
                                        <label class="control-label" for="signupguest-password">Mot de passe</label>
                                        <input type="password" id="signupguest-password" class="form-control" name="SignupForm[password]">
                                        <p class="help-block help-block-error"></p>
                                    </div>-->
                                    <div class="form-group field-signupguest-firstname required">
                                        <label class="control-label" for="signupguest-firstname">Prénom</label>
                                        <input type="text" id="signupguest-firstname" class="form-control" name="SignupForm[firstname]">
                                        <p class="help-block help-block-error"></p>
                                    </div>
                                    <div class="form-group field-signupguest-lastname required">
                                        <label class="control-label" for="signupguest-lastname">Nom</label>
                                        <input type="text" id="signupguest-lastname" class="form-control" name="SignupForm[lastname]">
                                        <p class="help-block help-block-error"></p>
                                    </div>
                                    <div class="form-group field-signupguest-phone required">
                                        <label class="control-label" for="signupguest-phone">Téléphone</label>
                                        <input type="text" id="signupguest-phone" class="form-control" name="SignupForm[phone]">
                                        <p class="help-block help-block-error"></p>
                                    </div>
                                </form>
                            </div>
                            <div class="block-actions">
                                <button class="btn btn-primary" disabled="disabled" v-if="disableConfirmButton">Je confirme ma commande</button>
                                <button class="btn btn-primary" v-else @click="confirmClick">Je confirme ma commande</button>
                            </div>
                        </template>
                    </div>
                </transition>
            </div>
        </div>

            <div id="infos" v-if="producer != null && producer.order_infos != null && producer.order_infos.length">
                    <div class="panel panel-default">
                            <div class="panel-heading">
                                    Informations
                            </div>
                            <div class="panel-body">
                                    {{ producer.order_infos }}
                            </div>
                    </div>
            </div>

        <?php
        $producer = GlobalParam::getCurrentProducer() ;
        if($producer->hasSpecificDelays()): ?>
            <div id="specific-delays" class="panel panel-default">
                    <div class="panel-heading">
                            Délais de commande spécifiques
                    </div>
                    <div class="panel-body">
                            <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                                <th>Jour</th>
                                                <th>Délai</th>
                                        </tr>
                                    </thead>
                                    <?php foreach($producer->getSpecificDelays() as $day => $delay): ?>
                                        <?php if($delay['order_delay'] && $delay['order_deadline']): ?>
                                                <tr>
                                                        <td>
                                                                <?php
                                                                switch($day) {
                                                                        case 'monday': echo 'Lundi' ; break;
                                                                        case 'tuesday': echo 'Mardi' ; break;
                                                                        case 'wednesday': echo 'Mercredi' ; break;
                                                                        case 'thursday': echo 'Jeudi' ; break;
                                                                        case 'friday': echo 'Vendredi' ; break;
                                                                        case 'saturday': echo 'Samedi' ; break;
                                                                        case 'sunday': echo 'Dimanche' ; break;
                                                                }
                                                                ?>
                                                        </td>
                                                        <td>
                                                                <span><?= $delay['order_delay'] ?> jour<?= ($delay['order_delay'] > 1) ? 's' : '' ?></span> à l'avance,
                                                                avant <span><?= ($delay['order_deadline'] == 24) ? 'minuit' : $delay['order_deadline'].'h' ; ?></span>
                                                        </td>
                                                </tr>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                            </table>
                    </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script type="text/x-template" id="template-step-date">
    <li id="step-date" :class="'col-md-3'+((step == 'date') ? ' active' : '')+(first ? ' first' : '')">
        <button @click="changeStep('date')" :class="'btn '+ (step == 'date' ? 'btn-primary' : 'btn-default')" :disabled="producer && producer.option_order_entry_point == 'point-sale' && !pointSaleActive">
            <span class="button-content"><span class="glyphicon glyphicon-time"></span> Date</span></span>
        </button>
        <div class="info-step" v-if="dateFormat">
            {{ dateFormat }}
        </div>
    </li>
</script>

<script type="text/x-template" id="template-step-point-sale">
    <li id="step-point-sale" :class="'col-md-3'+((step == 'point-sale') ? ' active ' : '')+(first ? ' first' : '')">
        <button @click="changeStep('point-sale')" :class="'btn '+ (step == 'point-sale' ? 'btn-primary' : 'btn-default')" :disabled="producer && (producer.option_order_entry_point == 'date' && step == 'date')">
            <span class="button-content"><span class="glyphicon glyphicon-map-marker"></span> Points de vente</span>
        </button>
        <div class="info-step" v-if="pointSaleActive">
            {{ pointSaleActive.name }}
        </div>
    </li>
</script>