<?php
/**
 * views/customerdocument/index.php
 *
 * Customer Documents — DataTables list view with context-menu actions.
 *
 * @var CustomerdocumentController $this
 */

$baseUrl    = Yii::app()->baseUrl;
$listUrl    = Yii::app()->createUrl('front/customerdocument/getlist');
$disableUrl = Yii::app()->createUrl('front/customerdocument/disable');
$createUrl  = Yii::app()->createUrl('front/customerdocument/create');

$cs = Yii::app()->getClientScript();

$csrfTokenName  = Yii::app()->request->csrfTokenName;
$csrfTokenValue = Yii::app()->request->csrfToken;

$cs->registerMetaTag($csrfTokenValue, $csrfTokenName);

$cs->registerScript('CustomerDocumentIndex', "
(function (\$) {
    'use strict';

    var TABLE_ID    = '#tbl_customer_documents';
    var LIST_URL    = " . CJSON::encode($listUrl) . ";
    var DISABLE_URL = " . CJSON::encode($disableUrl) . ";
    var CREATE_URL  = " . CJSON::encode($createUrl) . ";
    var BASE_URL    = " . CJSON::encode($baseUrl) . ";
    var CSRF_NAME   = " . CJSON::encode($csrfTokenName) . ";
    var CSRF_VALUE  = " . CJSON::encode($csrfTokenValue) . ";

    // ------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------
    function csrfData(extra) {
        var d = {};
        d[CSRF_NAME] = CSRF_VALUE;
        return \$.extend(d, extra);
    }

    function reloadTable() {
        \$(TABLE_ID).DataTable().ajax.reload(null, false);
    }

    // ------------------------------------------------------------------
    // Toggle active / inactive
    // ------------------------------------------------------------------
    function toggleStatus(id, currentStatus) {
        var msg = (currentStatus === 'Y')
            ? 'Are you sure you want to disable this document?'
            : 'Are you sure you want to enable this document?';

        if (!confirm(msg)) { return; }

        \$.ajax({
            type    : 'POST',
            dataType: 'json',
            url     : DISABLE_URL,
            cache   : false,
            data    : csrfData({ id: id, status: currentStatus }),
            success : function (response) {
                if (response.status === 'success') {
                    reloadTable();
                    t8.success('Status updated successfully.');
                } else {
                    t8.error(response.message || 'Error while updating status.');
                }
            },
            error: function (xhr) {
                t8.error('Request failed (' + xhr.status + '). Please try again.');
            }
        });
    }

    // ------------------------------------------------------------------
    // Context menu
    // ------------------------------------------------------------------
    function buildContextMenu(row, meta) {
        \$(row).contextMenu({
            selector: 'td',
            items: {
                edit: {
                    name    : 'Edit',
                    icon    : 'edit',
                    callback: function () {
                        loadPopupModal(
                            CREATE_URL + '&id=' + meta.id,
                            'Edit: ' + meta.title,
                            'lg'
                        );
                    }
                },
                toggle: {
                    name    : (meta.status === 'Y') ? 'Disable' : 'Enable',
                    icon    : (meta.status === 'Y') ? 'delete'  : 'add',
                    callback: function () {
                        toggleStatus(meta.id, meta.status);
                    }
                }
            }
        });
    }

    // ------------------------------------------------------------------
    // DataTable init
    // ------------------------------------------------------------------
    \$(document).ready(function () {

        var dt = \$(TABLE_ID).DataTable({
            scrollY      : '645px',
            pageLength   : 50,
            processing   : true,
            serverSide   : true,
            fixedColumns : true,
            language     : {
                processing : '<i class=\"fa fa-spinner fa-spin\"></i> Loading\u2026',
                zeroRecords: 'No documents found.',
                emptyTable : 'No documents available.'
            },

            columnDefs: [
                // SI No — fixed width, not searchable or sortable
                { targets: [0], searchable: false, orderable: false, width: '50px' },
                // Document column — render as download link
                {
                    targets: [3],
                    render : function (data) {
                        if (!data) { return '\u2014'; }
                        return '<a href=\"' + BASE_URL + '/uploads/customer_docs/' + data + '\" target=\"_blank\" rel=\"noopener noreferrer\">'
                             + '<i class=\"fa fa-file\"></i> ' + data
                             + '</a>';
                    }
                },
                // Hidden metadata column
                { targets: [4], visible: false, searchable: false }
            ],

            ajax: {
                url  : LIST_URL,
                type : 'POST',
                cache: false,
                data : function (d) {
                    d[CSRF_NAME]  = CSRF_VALUE;
                    d.customer_id = \$('#filter_customer_id').val();
                }
            },

            createdRow: function (row, data) {
                \$(row).addClass('context-menu');

                if (data[4] && data[4].status === 'N') {
                    \$(row).addClass('bg-danger');
                }

                if (data[4]) {
                    buildContextMenu(row, data[4]);
                }
            }
        });

        // Re-query server when customer filter changes
        \$('#filter_customer_id').on('change', function () {
            dt.ajax.reload(null, false);
        });
    });

}(jQuery));
", CClientScript::POS_END);
?>

<section class="panel">

    <header class="panel-heading clearfix panel-theame">
        <i class="fa fa-file"></i> Customer Documents

        {{!-- Customer filter --}}
        <div class="col-sm-2 pull-right" style="margin-right: 10px;">
            <?php
            $allCustomers = Customers::model()->findAll(array('order' => 'customer_name ASC'));
            $customers    = CHtml::listData($allCustomers, 'id', 'customer_name');
            echo CHtml::dropDownList(
                'filter_customer_id',
                '',
                $customers,
                array(
                    'id'     => 'filter_customer_id',
                    'class'  => 'form-control',
                    'prompt' => 'All Customers',
                )
            );
            ?>
        </div>

        {{!-- Add button --}}
        <div class="pull-right">
            <a class="ad-btn"
               title="Add Document"
               onclick="loadPopupModal(<?php echo CJSON::encode($createUrl); ?>,'Add Document','md')"
               style="cursor: pointer;">
                <svg width="30" height="30" viewBox="0 0 24 24"
                     fill="none" xmlns="http://www.w3.org/2000/svg" class="pluss-ad">
                    <circle cx="12" cy="12" r="11"
                            stroke="white" stroke-width="2" fill="none"/>
                    <line x1="12" y1="7"  x2="12" y2="17"
                          stroke="#5db5a4" stroke-width="2" stroke-linecap="round"/>
                    <line x1="7"  y1="12" x2="17" y2="12"
                          stroke="#5db5a4" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </a>
        </div>
    </header>

    <div class="panel-body">
        <div class="custom-data-table">
            <table class="table table-hover table-bordered"
                   id="tbl_customer_documents"
                   style="font-size: 13px; width: 100%;">
                <thead>
                    <tr>
                        <th style="width: 50px;">#</th>
                        <th>Customer Name</th>
                        <th>Document Title</th>
                        <th>Document</th>
                        <th><!-- meta --></th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

</section>