<?php
/**
 * views/front/customerdocument/_tab_documents.php
 *
 * Documents tab — embedded inside the Customer create/update view.
 * Include it like this inside the customer view's tab content:
 *
 *   <div class="tab-pane" id="tab-documents">
 *       <?php $this->renderPartial(
 *           'customerdocument/_tab_documents',
 *           array('customerId' => $model->id)
 *       ); ?>
 *   </div>
 *
 * @var integer $customerId   The parent customer's primary key.
 *                            Pass 0 (or omit) for a brand-new customer
 *                            that has not been saved yet.
 */

$customerId = isset($customerId) ? (int) $customerId : 0;
$baseUrl    = Yii::app()->baseUrl;
$saveUrl    = Yii::app()->createUrl('front/customerdocument/savedocument');
$disableUrl = Yii::app()->createUrl('front/customerdocument/disable');
$csrfName   = Yii::app()->request->csrfTokenName;
$csrfVal    = Yii::app()->request->csrfToken;

// Load existing active documents for this customer
$documents = ($customerId > 0)
    ? CustomerDocuments::model()->findAll(
        array(
            'condition' => 'customer_id = :cid AND isActive = :active',
            'params'    => array(':cid' => $customerId, ':active' => 'Y'),
            'order'     => 'id ASC',
        )
    )
    : array();
?>

<div id="documents-tab-wrapper">

    {{!-- Toolbar --}}
    <div style="margin-bottom: 10px; text-align: right;">
        <?php if ($customerId > 0): ?>
            <button type="button" class="btn btn-sm btn-theme" id="btn-add-document">
                <i class="fa fa-plus"></i> Add Document
            </button>
        <?php else: ?>
            <p class="text-muted" style="margin: 0; padding: 8px 0;">
                <i class="fa fa-info-circle"></i>
                Please save the customer record first before adding documents.
            </p>
        <?php endif; ?>
    </div>

    {{!-- Inline add / edit form (hidden by default) --}}
    <?php if ($customerId > 0): ?>
    <div id="doc-inline-form"
         style="display: none; border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; border-radius: 4px; background: #fafafa;">

        <input type="hidden" id="doc-edit-id" value="">

        <div class="row">
            <div class="col-sm-5">
                <div class="form-group" style="margin-bottom: 0;">
                    <label>
                        Document Title
                        <span class="text-danger">*</span>
                    </label>
                    <input type="text"
                           id="doc-title-input"
                           class="form-control"
                           placeholder="Enter document title"
                           maxlength="255">
                </div>
            </div>

            <div class="col-sm-5">
                <div class="form-group" style="margin-bottom: 0;">
                    <label>
                        File
                        <span class="text-danger" id="doc-file-required">*</span>
                        <small class="text-muted">(pdf, doc, docx, png, jpg &mdash; max 5 MB)</small>
                    </label>
                    <input type="file"
                           id="doc-file-input"
                           class="form-control"
                           accept=".pdf,.doc,.docx,.png,.jpg,.jpeg">
                    <small id="doc-current-file" class="text-muted" style="display: none;"></small>
                </div>
            </div>

            <div class="col-sm-2" style="padding-top: 24px;">
                <button type="button" class="btn btn-success btn-sm" id="btn-doc-confirm">
                    <span class="btn-doc-label">Save</span>
                </button>
                <button type="button" class="btn btn-default btn-sm" id="btn-doc-cancel">
                    Cancel
                </button>
            </div>
        </div>

        <div id="doc-inline-error"
             class="text-danger"
             style="margin-top: 8px; display: none; font-size: 13px;">
        </div>
    </div>
    <?php endif; ?>

    {{!-- Documents table --}}
    <table class="table table-bordered table-hover"
           id="tbl-documents-inline"
           style="font-size: 13px; width: 100%; margin-bottom: 0;">
        <thead style="background: #5559a7; color: #fff;">
            <tr>
                <th style="width: 50px;">#</th>
                <th>Document Title</th>
                <th>File</th>
                <?php if ($customerId > 0): ?>
                <th style="width: 120px;">Action</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="doc-table-body">
            <?php if (empty($documents)): ?>
                <tr id="no-docs-row">
                    <td colspan="<?php echo $customerId > 0 ? 4 : 3; ?>"
                        class="text-center text-muted">
                        No documents uploaded yet.
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($documents as $i => $doc): ?>
                <tr id="doc-row-<?php echo $doc->id; ?>">
                    <td><?php echo $i + 1; ?></td>
                    <td><?php echo CHtml::encode($doc->document_title); ?></td>
                    <td>
                        <a href="<?php echo $baseUrl . '/uploads/customer_docs/' . CHtml::encode($doc->customer_document); ?>"
                           target="_blank"
                           rel="noopener noreferrer">
                            <i class="fa fa-file"></i>
                            <?php echo CHtml::encode($doc->customer_document); ?>
                        </a>
                    </td>
                    <?php if ($customerId > 0): ?>
                    <td>
                        <button type="button"
                                class="btn btn-xs btn-info btn-edit-doc"
                                data-id="<?php echo $doc->id; ?>"
                                data-title="<?php echo CHtml::encode($doc->document_title); ?>"
                                data-file="<?php echo CHtml::encode($doc->customer_document); ?>">
                            <i class="fa fa-pencil"></i> Edit
                        </button>
                        <button type="button"
                                class="btn btn-xs btn-danger btn-delete-doc"
                                data-id="<?php echo $doc->id; ?>">
                            <i class="fa fa-trash"></i> Remove
                        </button>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

</div>

<?php if ($customerId > 0): ?>
<script>
(function ($) {
    'use strict';

    // ------------------------------------------------------------------
    // Config (injected server-side — no raw PHP in logic below)
    // ------------------------------------------------------------------
    var CUSTOMER_ID  = <?php echo $customerId; ?>;
    var SAVE_URL     = <?php echo CJSON::encode($saveUrl); ?>;
    var DISABLE_URL  = <?php echo CJSON::encode($disableUrl); ?>;
    var BASE_URL     = <?php echo CJSON::encode($baseUrl); ?>;
    var CSRF_NAME    = <?php echo CJSON::encode($csrfName); ?>;
    var CSRF_VALUE   = <?php echo CJSON::encode($csrfVal); ?>;
    var ALLOWED_EXT  = ['pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg'];
    var MAX_BYTES    = 5 * 1024 * 1024;

    var $form        = $('#doc-inline-form');
    var $tbody       = $('#doc-table-body');
    var $errorBox    = $('#doc-inline-error');
    var rowCount     = $tbody.find('tr[id^="doc-row-"]').length;

    // ------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------
    function showError(msg) {
        $errorBox.text(msg).show();
    }

    function clearError() {
        $errorBox.hide().text('');
    }

    function resetForm() {
        $('#doc-edit-id').val('');
        $('#doc-title-input').val('');
        $('#doc-file-input').val('');
        $('#doc-file-required').show();
        $('#doc-current-file').hide().text('');
        clearError();
    }

    function openForm() {
        $form.slideDown(200);
        $('#doc-title-input').focus();
    }

    function closeForm() {
        $form.slideUp(200, function () { resetForm(); });
    }

    // Remove the "no documents" placeholder row if present
    function removeEmptyRow() {
        $('#no-docs-row').remove();
    }

    // ------------------------------------------------------------------
    // Open blank add form
    // ------------------------------------------------------------------
    $('#btn-add-document').on('click', function () {
        resetForm();
        openForm();
    });

    $('#btn-doc-cancel').on('click', function () {
        closeForm();
    });

    // ------------------------------------------------------------------
    // Open populated edit form
    // ------------------------------------------------------------------
    $(document).on('click', '.btn-edit-doc', function () {
        var $btn = $(this);
        resetForm();
        $('#doc-edit-id').val($btn.data('id'));
        $('#doc-title-input').val($btn.data('title'));
        $('#doc-file-required').hide();
        $('#doc-current-file')
            .text('Current file: ' + $btn.data('file'))
            .show();
        openForm();
    });

    // ------------------------------------------------------------------
    // Client-side validation
    // ------------------------------------------------------------------
    function validate() {
        var errs   = [];
        var title  = $.trim($('#doc-title-input').val());
        var fileEl = $('#doc-file-input')[0];
        var isEdit = !!$('#doc-edit-id').val();

        if (!title) {
            errs.push('Document title is required.');
        }

        if (fileEl.files && fileEl.files.length > 0) {
            var file = fileEl.files[0];
            var ext  = file.name.split('.').pop().toLowerCase();
            if (ALLOWED_EXT.indexOf(ext) === -1) {
                errs.push('Invalid file type. Allowed: ' + ALLOWED_EXT.join(', ') + '.');
            }
            if (file.size > MAX_BYTES) {
                errs.push('File exceeds the 5 MB limit.');
            }
        } else if (!isEdit) {
            errs.push('Please select a file to upload.');
        }

        return errs;
    }

    // ------------------------------------------------------------------
    // Append a new row to the table (avoids full page reload on add)
    // ------------------------------------------------------------------
    function appendRow(id, title, fileName) {
        removeEmptyRow();
        rowCount++;
        var fileUrl = BASE_URL + '/uploads/customer_docs/' + fileName;
        var $tr = $(
            '<tr id="doc-row-' + id + '">' +
                '<td>' + rowCount + '</td>' +
                '<td>' + $('<span>').text(title).html() + '</td>' +
                '<td>' +
                    '<a href="' + fileUrl + '" target="_blank" rel="noopener noreferrer">' +
                        '<i class="fa fa-file"></i> ' + $('<span>').text(fileName).html() +
                    '</a>' +
                '</td>' +
                '<td>' +
                    '<button type="button" class="btn btn-xs btn-info btn-edit-doc"' +
                            ' data-id="' + id + '"' +
                            ' data-title="' + $('<span>').text(title).html() + '"' +
                            ' data-file="' + $('<span>').text(fileName).html() + '">' +
                        '<i class="fa fa-pencil"></i> Edit' +
                    '</button> ' +
                    '<button type="button" class="btn btn-xs btn-danger btn-delete-doc"' +
                            ' data-id="' + id + '">' +
                        '<i class="fa fa-trash"></i> Remove' +
                    '</button>' +
                '</td>' +
            '</tr>'
        );
        $tbody.append($tr);
    }

    // ------------------------------------------------------------------
    // Update an existing row in place (avoids page reload on edit)
    // ------------------------------------------------------------------
    function updateRow(id, title, fileName) {
        var $tr      = $('#doc-row-' + id);
        var fileUrl  = BASE_URL + '/uploads/customer_docs/' + fileName;
        $tr.find('td:nth-child(2)').text(title);
        $tr.find('td:nth-child(3)').html(
            '<a href="' + fileUrl + '" target="_blank" rel="noopener noreferrer">' +
                '<i class="fa fa-file"></i> ' + $('<span>').text(fileName).html() +
            '</a>'
        );
        $tr.find('.btn-edit-doc')
            .data('title', title)
            .data('file', fileName);
    }

    // ------------------------------------------------------------------
    // Save (add or edit)
    // ------------------------------------------------------------------
    $('#btn-doc-confirm').on('click', function () {
        clearError();

        var errs = validate();
        if (errs.length) {
            showError(errs.join(' '));
            return;
        }

        var $btn   = $(this);
        var editId = $('#doc-edit-id').val();
        var title  = $.trim($('#doc-title-input').val());
        var fileEl = $('#doc-file-input')[0];

        $btn.prop('disabled', true).find('.btn-doc-label').text('Saving\u2026');

        var fd = new FormData();
        fd.append(CSRF_NAME,                              CSRF_VALUE);
        fd.append('CustomerDocuments[customer_id]',       CUSTOMER_ID);
        fd.append('CustomerDocuments[document_title]',    title);
        if (editId) {
            fd.append('CustomerDocuments[id]', editId);
        }
        if (fileEl.files && fileEl.files.length > 0) {
            fd.append('CustomerDocuments[customer_document]', fileEl.files[0]);
        }

        $.ajax({
            type       : 'POST',
            url        : SAVE_URL,
            data       : fd,
            dataType   : 'json',
            contentType: false,
            processData: false,
            success: function (res) {
                if (res.status === 'success') {
                    var newId    = res.id;
                    var fileName = res.filename || (fileEl.files && fileEl.files.length > 0
                                    ? fileEl.files[0].name
                                    : $('#doc-current-file').text().replace('Current file: ', '').trim());

                    if (editId) {
                        updateRow(editId, title, fileName);
                        t8.success('Document updated.');
                    } else {
                        appendRow(newId, title, fileName);
                        t8.success('Document added.');
                    }
                    closeForm();
                } else if (res.errors) {
                    var msgs = [];
                    $.each(res.errors, function (_, m) { $.each(m, function (_, v) { msgs.push(v); }); });
                    showError(msgs.join(' '));
                } else {
                    showError(res.message || 'Error saving document.');
                }
            },
            error: function (xhr) {
                showError('Request failed (' + xhr.status + '). Please try again.');
            },
            complete: function () {
                $btn.prop('disabled', false).find('.btn-doc-label').text('Save');
            }
        });
    });

    // ------------------------------------------------------------------
    // Remove (soft-delete — sets isActive = N)
    // ------------------------------------------------------------------
    $(document).on('click', '.btn-delete-doc', function () {
        if (!confirm('Are you sure you want to remove this document?')) { return; }

        var id  = $(this).data('id');
        var $tr = $('#doc-row-' + id);

        var payload = {};
        payload[CSRF_NAME] = CSRF_VALUE;
        payload.id         = id;
        payload.status     = 'Y'; // current status is Y → will be set to N

        $.ajax({
            type    : 'POST',
            url     : DISABLE_URL,
            dataType: 'json',
            data    : payload,
            success : function (res) {
                if (res.status === 'success') {
                    $tr.fadeOut(300, function () {
                        $(this).remove();
                        rowCount--;
                        // Renumber remaining rows
                        $tbody.find('tr[id^="doc-row-"]').each(function (i) {
                            $(this).find('td:first').text(i + 1);
                        });
                        // Show empty state if no rows left
                        if ($tbody.find('tr[id^="doc-row-"]').length === 0) {
                            $tbody.append(
                                '<tr id="no-docs-row">' +
                                    '<td colspan="4" class="text-center text-muted">No documents uploaded yet.</td>' +
                                '</tr>'
                            );
                        }
                    });
                    t8.success('Document removed.');
                } else {
                    t8.error(res.message || 'Could not remove document.');
                }
            },
            error: function (xhr) {
                t8.error('Request failed (' + xhr.status + '). Please try again.');
            }
        });
    });

}(jQuery));
</script>
<?php endif; ?>