<?php
/**
 * views/customerdocument/create.php
 *
 * Create / edit form for a CustomerDocuments record.
 * Rendered inside a Bootstrap modal via loadPopupModal().
 *
 * @var CActiveForm       $form
 * @var CustomerDocuments $model
 * @var array             $customers   id => customer_name map
 */

$isEdit  = !empty($model->id);
$saveUrl = Yii::app()->createUrl('front/customerdocument/savedocument');
$baseUrl = Yii::app()->baseUrl;

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

$allowedExt = array('pdf', 'doc', 'docx', 'png', 'jpg', 'jpeg');
$maxSizeMB  = 5;

$form = $this->beginWidget('CActiveForm', array(
    'id'                     => 'customerdocuments-form',
    'enableAjaxValidation'   => false,
    'enableClientValidation' => false,
    'htmlOptions'            => array(
        'enctype'          => 'multipart/form-data',
        'data-save-url'    => $saveUrl,
        'data-csrf-name'   => $csrfName,
        'data-csrf-value'  => $csrfVal,
        'data-allowed-ext' => implode(',', $allowedExt),
        'data-max-size-mb' => $maxSizeMB,
    ),
));
?>

<div class="tab-content">
    <div class="tab-pane active">

        {{!-- Global error banner --}}
        <div id="doc-form-errors" class="alert alert-danger" style="display: none; margin: 0 15px 10px;">
            <ul class="error-list" style="margin: 0; padding-left: 18px;"></ul>
        </div>

        <ul class="clearfix form-ul material">

            {{!-- Customer --}}
            <li class="col-sm-6">
                <label>
                    <?php echo $model->getAttributeLabel('customer_id'); ?>
                    <span class="text-danger">*</span>
                </label>
                <?php echo $form->dropDownList(
                    $model,
                    'customer_id',
                    $customers,
                    array(
                        'class'      => 'form-control',
                        'prompt'     => 'Select Customer',
                        'data-label' => 'Customer',
                    )
                ); ?>
                <?php echo $form->error($model, 'customer_id', array('class' => 'text-danger small')); ?>
            </li>

            {{!-- Document Title --}}
            <li class="col-sm-6">
                <label>
                    <?php echo $model->getAttributeLabel('document_title'); ?>
                    <span class="text-danger">*</span>
                </label>
                <?php echo $form->textField(
                    $model,
                    'document_title',
                    array(
                        'class'       => 'form-control',
                        'placeholder' => 'Enter Document Title',
                        'maxlength'   => 255,
                    )
                ); ?>
                <?php echo $form->error($model, 'document_title', array('class' => 'text-danger small')); ?>
            </li>

            {{!-- Document upload --}}
            <li class="col-sm-6">
                <label>
                    <?php echo $model->getAttributeLabel('customer_document'); ?>
                    <?php if (!$isEdit): ?>
                        <span class="text-danger">*</span>
                    <?php endif; ?>
                    <small class="text-muted">
                        (<?php echo implode(', ', $allowedExt); ?> &mdash; max <?php echo $maxSizeMB; ?> MB)
                    </small>
                </label>
                <?php echo $form->fileField(
                    $model,
                    'customer_document',
                    array(
                        'class'  => 'form-control',
                        'accept' => '.pdf,.doc,.docx,.png,.jpg,.jpeg',
                    )
                ); ?>
                <?php echo $form->error($model, 'customer_document', array('class' => 'text-danger small')); ?>

                <?php if ($isEdit && !empty($model->customer_document)): ?>
                    <small class="text-muted">
                        Current:&nbsp;
                        <a href="<?php echo $baseUrl . '/uploads/customer_docs/' . CHtml::encode($model->customer_document); ?>"
                           target="_blank"
                           rel="noopener noreferrer">
                            <?php echo CHtml::encode($model->customer_document); ?>
                        </a>
                        &nbsp;<em>(leave blank to keep existing file)</em>
                    </small>
                <?php endif; ?>
            </li>

            <?php echo $form->hiddenField($model, 'id'); ?>

        </ul>

        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-theme" id="btn-save-document">
                <span class="btn-label">Save</span>
            </button>
        </div>

    </div>
</div>

<?php $this->endWidget(); ?>

<script>
(function ($) {
    'use strict';

    var $form    = $('#customerdocuments-form');
    var $btn     = $('#btn-save-document');
    var $errors  = $('#doc-form-errors');
    var $errList = $errors.find('.error-list');

    var saveUrl    = $form.data('save-url');
    var csrfName   = $form.data('csrf-name');
    var csrfValue  = $form.data('csrf-value');
    var allowedExt = ($form.data('allowed-ext') + '').split(',');
    var maxBytes   = $form.data('max-size-mb') * 1024 * 1024;

    // ------------------------------------------------------------------
    // Client-side validation
    // ------------------------------------------------------------------
    function validateForm() {
        var errs = [];

        if (!$form.find('#CustomerDocuments_customer_id').val()) {
            errs.push('Please select a customer.');
        }

        if (!$.trim($form.find('#CustomerDocuments_document_title').val())) {
            errs.push('Document title is required.');
        }

        var fileInput = $form.find('#CustomerDocuments_customer_document')[0];
        var isEdit    = !!$form.find('#CustomerDocuments_id').val();

        if (fileInput && fileInput.files && fileInput.files.length > 0) {
            var file = fileInput.files[0];
            var ext  = file.name.split('.').pop().toLowerCase();

            if (allowedExt.indexOf(ext) === -1) {
                errs.push('Invalid file type. Allowed: ' + allowedExt.join(', ') + '.');
            }
            if (file.size > maxBytes) {
                errs.push('File exceeds maximum size of ' + $form.data('max-size-mb') + ' MB.');
            }
        } else if (!isEdit) {
            errs.push('Please select a document to upload.');
        }

        return errs;
    }

    // ------------------------------------------------------------------
    // Show / clear error banner
    // ------------------------------------------------------------------
    function showErrors(errs) {
        $errList.empty();
        $.each(errs, function (_, msg) {
            $errList.append($('<li>').text(msg));
        });
        $errors.show();
        $errors[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function clearErrors() {
        $errors.hide();
        $errList.empty();
    }

    // ------------------------------------------------------------------
    // Handle server-side field errors  { errors: { field: [msg, ...] } }
    // ------------------------------------------------------------------
    function handleServerErrors(errors) {
        var errs = [];
        $.each(errors, function (field, messages) {
            $.each(messages, function (_, msg) {
                errs.push(msg);
            });
        });
        showErrors(errs);
    }

    // ------------------------------------------------------------------
    // Submit
    // ------------------------------------------------------------------
    $btn.off('click').on('click', function () {
        clearErrors();

        var clientErrs = validateForm();
        if (clientErrs.length > 0) {
            showErrors(clientErrs);
            return;
        }

        if ($btn.data('sending')) { return; }
        $btn.data('sending', true)
            .prop('disabled', true)
            .find('.btn-label').text('Saving\u2026');

        var formData = new FormData($form[0]);
        formData.append(csrfName, csrfValue);

        $('#loader').show();

        $.ajax({
            type       : 'POST',
            url        : saveUrl,
            data       : formData,
            dataType   : 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                if (response.status === 'success') {
                    t8.success('Document saved successfully.');
                    reloadTable('#tbl_customer_documents');
                    setTimeout(function () { $('.modal').modal('hide'); }, 300);
                } else if (response.errors) {
                    handleServerErrors(response.errors);
                } else {
                    t8.error(response.message || 'Error saving document.');
                }
            },
            error: function (xhr) {
                t8.error('Request failed (' + xhr.status + '). Please try again.');
            },
            complete: function () {
                $('#loader').hide();
                $btn.data('sending', false)
                    .prop('disabled', false)
                    .find('.btn-label').text('Save');
            }
        });
    });

}(jQuery));
</script>