<style>
    .table thead tr >th{
        background-color:#4c0870;
        color:#fff;
    }
</style>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"> <?php print $title; ?></div>
            <?php
            if ($permissions->hasPermission('add_project_period')) {
                echo Forms::FloatingAddButton('4c0870', '#project_period_modal', CommonLanguage::getMessage('add_project_period'), 'add_project_period_btn');
            }
            ?>
        </div>
        <div class="panel-body">
            <div class=" row   ">
                <div class="col-md-12 table-responsive">
                    <table class="table table-bordered  ACC" id="tableWithSearch" >
                        <thead>
                            <tr>
                                <th class="text-center" style="width:15%" >#</th> 
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('title'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('project'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('nb_period'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('start_date'); ?></th>
                                <th class="text-center" style="width:15%" ><?php print CommonLanguage::getMessage('currency'); ?></th>
                                <th class="text-center no-print" style="width:15%"><?php print CommonLanguage::getMessage('Action'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="project_period_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog ">
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label bold hidden h-labels"><?php echo CommonLanguage::getMessage('add_project_period'); ?></h5>
                <h5 class="edit-label bold hidden h-labels"><?php echo CommonLanguage::getMessage('edit_project_period'); ?></h5>
            </div>
            <div class="modal-body">
                <form id="project_period_form" method="POST" onsubmit="return false">
                    <input type='hidden' name='period_id' id='period_id'/>
                    <div class="row">
                        <?php echo Forms::AlertDiv('project_period_alert'); ?>
                    </div>
                    <div class="row form-group">
                        <div class="col-md-2 ">
                            <label><?php echo CommonLanguage::getMessage('title') ?>
                                <span class="red-star">*</span>
                            </label>
                            <input type="text" class="form-control" id="period_title" name="period_title" required/>
                        </div>
                        <div class="col-md-2">
                            <label><?php echo CommonLanguage::getMessage('project') ?>
                                <span class="red-star">*</span>
                            </label>
                            <input type="hidden" class="full-width" value="" id="project_id" name="project_id" required/>
                        </div>
                        <div class="col-md-2">
                            <label><?php echo CommonLanguage::getMessage('nb_period') ?>
                                <span class="red-star">*</span>
                                <i class="fa fa-info-circle" title="<?php echo CommonLanguage::getMessage('number_months'); ?>"></i>
                            </label>
                            <input type="number" class="form-control" id="nb_period" name="nb_period" value="" required/>
                        </div>
                        <div class="col-md-2">
                            <label><?php echo CommonLanguage::getMessage('period_unit') ?>
                                <span class="red-star">*</span>
                                <i class="fa fa-info-circle" title="<?php echo CommonLanguage::getMessage('nb_month_rep_schd'); ?>"></i>
                            </label>
                            <input type="number" class="form-control" id="period_unit" name="period_unit" value="" required/>
                        </div>
                        <div class="col-md-2">
                            <label><?php echo CommonLanguage::getMessage('currency') ?>
                                <span class="red-star">*</span>
                            </label>
                            <input type="hidden" class="full-width" id="currency_id" name="currency_id" value="" required/>
                        </div>
                        <div class="col-md-2 ">
                            <label><?php echo CommonLanguage::getMessage('start_date') ?>
                                <span class="red-star">*</span>
                            </label>
                            <input type="text" class="form-control detail_date_picker " id="start_date" name="start_date" required />
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-md-2">
                            <label><?php echo CommonLanguage::getMessage('account'); ?></label> 
                            <span class="red-star">*</span>
                            <input type="hidden"  id="account_id" name="account_id" class="full-width" required>
                        </div>
                        <div class="col-md-4 ">
                            <label><?php echo CommonLanguage::getMessage('main_activities') ?>
                                <span class="red-star">*</span>
                            </label>
                            <input type="hidden" class="full-width" id="activity_ids" name="activity_ids" required/>
                        </div>
                        <div class="col-md-1 m-t-20 col-xs-6 pull-right ">
                            <button  class="btn btn-complete full-width pull-right " id="generate" ><?php echo CommonLanguage::getMessage('generate') ?></button>
                        </div>
                    </div>
                    <div class=" div_details hidden" id="project_period_div">
                        <div class=" form-group row">
                            <div class="col-md-3 "><label><?php echo CommonLanguage::getMessage('detail_period_title') ?><span class="red-star">*</span></label></div>
                            <div class=" col-md-2"><label><?php echo CommonLanguage::getMessage('start_date') ?><span class="red-star">*</span></label></div>
                            <div class=" col-md-2"><label><?php echo CommonLanguage::getMessage('end_date') ?><span class="red-star">*</span></label></div>
                        </div>
                        <div class="form-group row AddRow">
                            <div class="col-md-3 ">
                                <input type="text" class="form-control detail_period_title " value=""  >
                            </div> 
                            <div class="col-md-2 ">
                                <input type="text" class="form-control start_date " value=""  >
                            </div> 
                            <div class="col-md-2 ">
                                <input type="text" class="form-control end_date " value=""   >
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close'); ?></button>
                <button class="btn btn-complete" id="submit_project_period"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
            <?php echo Forms::ModalLoader('project_period_loader'); ?>
        </div>
    </div>
</div>

<div class="form-group row hidden row-temp">
    <div class="col-md-3 ">
        <input type="text" class="form-control detail_period_title  "  >
    </div>
    <div class="col-md-2 ">
        <input type="text" class="form-control start_date  "  >
    </div> 
    <div class="col-md-2 ">
        <input type="text" class="form-control end_date  "  >
    </div>
</div>
<script>
    $(function () {
        build_select2($("#account_id"), "xhr/accIDSearch");
        $("#currency_id").val(<?php echo smc_session()['local_currency']; ?>).attr("data-select-name", ('<?php echo smc_session()['local_currency_name']; ?>' + ' - ' + '<?php echo smc_session()['local_currency_code']; ?>'))

        build_select2($("#currency_id"), ("xhr/CurrencySearch"));
        build_select2($("#activity_ids"), ("ACCAjax/searchMainActivity"), 1);
        build_select2($("#project_id"), ("xhr/commonSearch?table=tbl_projects&col_id=project_id&col_name=project_name"));
        $('#start_date').datepicker({autoclose: true});

        RebuildDataTable($('.panel-heading .panel-title').html(), [0, 1], "ACCAjax/project_period_list");
        $('#tableWithSearch').on('click', '.delete_project_period', function () {
            var category_id = $(this).parents('div.Action').attr('data-id');
             IncludeDeleteModal(common_delete_modal, {entry_value: category_id}, function () {
                RebuildDataTable($('.panel-heading .panel-title').html(), [0, 1], 'ACCAjax/project_period_list');
            }, "ACCAjax/delete_project_period");
        });

        $(".add_project_period_btn").on("click", function () {
            $("#period_id").val('');
            $('#project_period_modal .add-label').removeClass('hidden');
            $("#project_period_div").addClass('hidden');
            $("#project_period_div .AddRow:gt(0)").remove();
            $("#project_period_div .AddRow:eq(0)").attr("data-detail-id", 0);
            $('#currency_id,#nb_period,#period_unit,#start_date,#project_id,#account_id,#activity_ids').prop('readonly', false)
            $("#generate").prop("disabled", false)
        });
        $('#generate').on('click', function () {
            if (!$('#start_date').val()) {
                toastr.error('<?php echo CommonLanguage::getMessage('Required_Fields'); ?>');
                return;
            }
            var nb_period = parseFloat($("#nb_period").val() || 0),
                    period_unit = $("#period_unit").val(),
                    start_date = $("#start_date").val(),
                    temp = $(".row-temp").clone();
            $('#project_period_div .AddRow').remove();
            $('#project_period_div').removeClass('hidden');
            var j = 1;
            for (var i = 0; i < nb_period; i++) {
                var temp = $(".row-temp").clone();
                temp.removeClass("row-temp hidden").addClass('AddRow')
                temp.attr('data-id', i);
                temp.attr('data-detail-id', 0);
                temp.appendTo($("#project_period_div"))
                $("input.detail_period_title", temp).val(j);
                $("input.start_date", temp).val(start_date).datepicker({autoclose: true});
                if (i == 0)
                    $("input.start_date", temp).attr('disabled', true);
                start_date = moment(start_date).add(period_unit, 'month').format('YYYY-MM-DD');
                $("input.end_date", temp).val(moment(start_date).subtract(1, 'day').format('YYYY-MM-DD')).datepicker({autoclose: true});
                $("input.end_date", temp).prop('readonly', true).prop('disabled', true);
                j++;
            }
        });
        $('#project_period_div').on('changeDate', 'input.start_date', function () {
            var current_row_index = parseInt($(this).parents('.AddRow').attr('data-id')),
                    before_row_index = current_row_index - 1;
            $(".AddRow[data-id=" + before_row_index + "] input.end_date").val(moment($(this).val()).subtract(1, 'day').format('YYYY-MM-DD'));
        });

        $("#tableWithSearch").on("click", ".edit_project_period", function () {
            var period_id = $(this).parents('div.Action').attr('data-id');
            $('#project_period_modal .edit-label').removeClass('hidden');
            $("#period_id").val(period_id);

            CommonViewById('ACCAjax/get_project_period', {period_id: period_id},
                    '#project_period_loader', function (response) {
                        var main = response['main'],
                                details = response['details'],
                                activities = response['activities'],
                                current_details = $('#project_period_div .AddRow:eq(0)').clone();
                        if (response['is_used'] == 1) {
                            $('#currency_id,#nb_period,#period_unit,#start_date,#project_id,#account_id,#activity_ids').prop('readonly', true)
                            $("#generate").prop("disabled", true)
                        } else {
                            $('#currency_id,#nb_period,#period_unit,#start_date,#project_id,#account_id,#activity_ids').prop('readonly', false)
                            $("#generate").prop("disabled", false)

                        }
                        $('#period_title').val(main.period_title);
                        $('#nb_period').val(main.nb_period);
                        $('#period_unit').val(main.period_unit);
                        $('#start_date').val(main.start_date);

                        $('#currency_id').val(main.currency_id).attr('data-select-name', main.Currency_Name).trigger('change');
                        $('#project_id').val(main.project_id).attr('data-select-name', main.project_name).trigger('change');
                        $('#account_id').val(main.account_id).attr('data-select-name', main.Account_Name).trigger('change');

                        if (activities.length > 0) {
                            $('#activity_ids').select2('val', [])
                            $('#activity_ids').data().select2.updateSelection(activities);
                        }
                        if (details.length > 0) {
                            $("#project_period_div").removeClass('hidden');
                            $("#project_period_div .AddRow").remove();
                            $.each(details, function (index, value) {
                                current_details = current_details == null ? $("#project_period_div .AddRow:eq(0)").clone() : current_details;
                                $('input.detail_period_title', current_details).val(details[index].detail_period_title);
                                $('input.start_date', current_details).val(details[index].start_date).datepicker({autoclose: true});
                                $('input.end_date', current_details).val(details[index].end_date).datepicker({autoclose: true});
                                $("input.end_date", current_details).prop('readonly', true).prop('disabled', true);
                                current_details.attr('data-id', index);
                                current_details.attr('data-detail-id', details[index].detail_id);
                                if (index == 0) {
                                    $('input.start_date', current_details).attr('disabled', true);
                                } else {
                                    $('input.start_date', current_details).attr('disabled', false);
                                }
                                $("#project_period_div").append(current_details);
                                current_details = null
                            });
                        }
                    });
        });
        $("#submit_project_period").on("click", function () {
            var details = [], is_start_false = false
            if (!$("#project_period_form").valid())
                return;
            var Data = new FormData(document.getElementById("project_period_form"));
            $(".AddRow").each(function (e) {
                var parent = $(this);
                if ($('input.detail_period_title', parent).val() &&
                        $('input.start_date', parent).val() &&
                        $('input.end_date', parent).val()) {
                    var current_row_index = parseInt(parent.attr('data-id')),
                            before_row_index = current_row_index - 1;
                    details.push({detail_period_title: $('input.detail_period_title', parent).val(),
                        start_date: $('input.start_date', parent).val(),
                        end_date: $('input.end_date', parent).val(),
                        detail_id: parent.attr("data-detail-id")
                    });
                    if ($('.AddRow[data-id=' + before_row_index + ']').length > 0 &&
                            $('input.start_date', parent).val() <= $('.AddRow[data-id=' + before_row_index + '] input.start_date').val())
                        is_start_false = true;
                }
            });
            if (details.length == 0) {
                AddAlert("#project_period_alert", '<?php echo CommonLanguage::getMessage('Required_Fields'); ?>', 'danger');
                return;
            }
            if (details.length != parseInt($("#nb_period").val())) {
                AddAlert("#project_period_alert", '<?php echo CommonLanguage::getMessage('nb_period_alert'); ?>', 'danger');
                return;
            }
            if (is_start_false) {
                AddAlert("#project_period_alert", '<?php echo CommonLanguage::getMessage('check_start_date'); ?>', 'danger');
                return;
            }
            Data.append('details', JSON.stringify(details));
            Data.append('end_date', $('.AddRow:last input.end_date').val());
            $("#project_period_loader").removeClass('hidden');
            $.ajax({
                url: "ACCAjax/submit_project_period",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            RebuildDataTable($('.panel-heading .panel-title').html(), [0, 1], 'ACCAjax/project_period_list');
                            hideModalAlert('project_period_modal', 'project_period_alert');
                        }
                        AddAlert("#project_period_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#project_period_loader").addClass('hidden');
                }
            });
        });
    });
</script>