<?php

use yii\helpers\{Arrayhelper, Html, Json};
use yii\widgets\ActiveForm;
use kartik\date\DatePicker;
use kartik\time\timepicker;
use yii\widgets\Pjax; 

/* @var $this yii\web\View */
/* @var $model modules\forms\models\Dt135 */
/* @var $form yii\widgets\ActiveForm */
//$this->registerJsFile('/js/touch.js'); 
$this->registerJsFile('/js/touch_0.js'); 
$this->registerJsFile('/js/touch_1.js'); 
//$this->registerJsFile('/js/touch_2.js'); 
//$this->registerJsFile('/js/touch_3.js');
//$model->time = date('H:i', strtotime('now'));
$users = \modules\users\models\User::EmployeesU();
$vehicles = yii\helpers\ArrayHelper::map(\modules\cors\models\Vehiclebe::find()->orderby(['reg' => SORT_ASC])->all(), 'id', 'reg');
    $runningtotal = 0;
?>

<script>
$(function() {
    //init(); //Drawing
    init0(); //canvas_0
    init1(); //canvas_1
    //init2(); //canvas_2
    //init3(); //canvas_3
    
    // Function to calculate HAV values
    function calculateHAV(rowKey) {
        var magnitude = parseFloat($('input[name="Dt135[rowMagnitudeUser][' + rowKey + ']"]').val()) || 0;
        var hours = parseFloat($('input[name="Dt135[rowhours][' + rowKey + ']"]').val()) || 0;
        var minutes = parseFloat($('input[name="Dt135[rowminutes][' + rowKey + ']"]').val()) || 0;
        
        // Convert total time to minutes
        var totalMinutes = (hours * 60) + minutes;
        
        // Get the pre-calculated Task Points per Hour from the field
        var pph = parseFloat($('input[name="Dt135[rowpph][' + rowKey + ']"]').val()) || 0;
        
        // Calculate Time to reach EAV (2.5 m/s²): (2.5 / magnitude)² × 8 hours
        if (magnitude > 0) {
            var eavHours = Math.pow(2.5 / magnitude, 2) * 8;
            var eavHH = Math.floor(eavHours);
            var eavMM = Math.round((eavHours - eavHH) * 60);
            $('input[name="Dt135[rowEAV][' + rowKey + ']"]').val(
                String(eavHH).padStart(2, '0') + ':' + String(eavMM).padStart(2, '0')
            );
            
            // Calculate Time to reach ELV (5.0 m/s²): (5.0 / magnitude)² × 8 hours
            var elvHours = Math.pow(5.0 / magnitude, 2) * 8;
            var elvHH = Math.floor(elvHours);
            var elvMM = Math.round((elvHours - elvHH) * 60);
            $('input[name="Dt135[rowELV][' + rowKey + ']"]').val(
                String(elvHH).padStart(2, '0') + ':' + String(elvMM).padStart(2, '0')
            );
        } else {
            $('input[name="Dt135[rowEAV][' + rowKey + ']"]').val('');
            $('input[name="Dt135[rowELV][' + rowKey + ']"]').val('');
        }
        
        // Calculate Partial Exposure m/s² A(8): magnitude × √(totalMinutes / 480)
        var partialExposure = magnitude * Math.sqrt(totalMinutes / 480);
        $('input[name="Dt135[rowtoolms2][' + rowKey + ']"]').val(partialExposure.toFixed(1));
        
        // Calculate Partial Exposure Points: pph × (totalMinutes / 60)
        var points = pph * (totalMinutes / 60);
        $('input[name="Dt135[rowpoints][' + rowKey + ']"]').val(points.toFixed(0));
        
        // Update running total
        updateRunningTotal();
    }
    
    // Function to update running total
    function updateRunningTotal() {
        // Update operator subtotals
        var operatorTotals = {};
        var operatorExposures = {};
        
        $('tr.datarows').each(function() {
            var operator = $(this).data('operator');
            var pointsInput = $(this).find('input[name^="Dt135[rowpoints]"]');
            var exposureInput = $(this).find('input[name^="Dt135[rowtoolms2]"]');
            var points = parseFloat(pointsInput.val()) || 0;
            var exposure = parseFloat(exposureInput.val()) || 0;
            
            if (!operatorTotals[operator]) {
                operatorTotals[operator] = 0;
                operatorExposures[operator] = 0;
            }
            operatorTotals[operator] += points;
            
            // Sum of squares for daily exposure (root sum of squares method)
            operatorExposures[operator] += Math.pow(exposure, 2);
        });
        
        // Update each operator subtotal for points
        $('.operator-subtotal').each(function() {
            var operator = $(this).data('operator');
            var total = operatorTotals[operator] || 0;
            $(this).text(total.toFixed(0));
        });
        
        // Update each operator subtotal for partial exposure (daily exposure A(8))
        $('.operator-exposure-subtotal').each(function() {
            var operator = $(this).data('operator');
            var sumOfSquares = operatorExposures[operator] || 0;
            var dailyExposure = Math.sqrt(sumOfSquares);
            $(this).text(dailyExposure.toFixed(1));
        });
        
        // Calculate and update grand total
        var grandTotal = 0;
        $.each(operatorTotals, function(operator, total) {
            grandTotal += total;
        });
        $('#grand-total').text(grandTotal.toFixed(0));
    }
    
    // Attach change events to magnitude, hours, and minutes inputs
    $(document).on('input change', 'input[name^="Dt135[rowMagnitudeUser]"], input[name^="Dt135[rowhours]"], input[name^="Dt135[rowminutes]"]', function() {
        var name = $(this).attr('name');
        var match = name.match(/\[([^\]]+)\]$/);
        if (match) {
            var rowKey = match[1];
            calculateHAV(rowKey);
        }
    });
    
    // Initialize calculations for existing rows on page load
    $('input[name^="Dt135[rowMagnitudeUser]"]').each(function() {
        var name = $(this).attr('name');
        var match = name.match(/\[([^\]]+)\]$/);
        if (match) {
            var rowKey = match[1];
            calculateHAV(rowKey);
        }
    });
});

</script>
<div class="dt135-form">
    <?php $form = ActiveForm::begin(['options' => ['id' => 'dynamic-form', 'enctype' => 'multipart/form-data', 'enableClientValidation' => false]]); ?>
    <table class="table table-borderless">
        <thead>
            <tr>
                <th colspan="11" class="h3">Hand Arm Vibration – Tool Usage Assessment Form DT135</th>
            </tr>
        </thead>
        <tbody>
        <tr class="DarkerBlue">
            <th>Position</th>
            <th>Job No</th>
            <th>Location</th>
            <th>Date</th>
        </tr>
        <tr>
            <td><?= $form->field($model, 'position')->textInput()->label(false) ?></td>
            <td><?= $form->field($model, 'jobno')->textInput()->label(false) ?></td>
            <td><?= $form->field($model, 'location')->textInput()->label(false) ?></td>
            <td><?= $form->field($model, 'date')->widget(DatePicker::class, ['type' => 1, 'pluginOptions' => ['showMeridian' =>false, 'format' => 'dd/mm/yyyy']])->label(false) ?>
            </td>
        </tr>
        <tr class="DarkerBlue">
            <th>Description</th>
        </tr>
        <tr>
            <td><?= $form->field($model, 'description')->textInput()->label(false) ?></td>
        </tr>
        <tr>
            <td colspan="4">

                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th rowspan="2">Employee</th>
                            <th rowspan="2">Tool</th>
                            <th colspan="2">Vibration Magnitude m/s² A(8)</th>
                            
                            <th rowspan="2">Task Points per Hour</th>
                            <th rowspan="2">Time to reach EAV hh:mm</th>
                            <th rowspan="2">Time to reach ELV hh:mm</th>

                            <th colspan="2">Exposure Duration</th>
                            <th rowspan="2">Partial Exposure m/s² A(8)</th>
                            <th rowspan="2">Partial Exposure Points</th>
                        </tr>
                        <tr>
                            <th>HSE</th>
                            <th>User</th>
                            <th>Hours</th>
                            <th>Minutes</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $row = 0;
                        $currentOperator = null;
                        $operatorTotal = 0;
                        $grandTotal = 0;
                        foreach($model->rowOperator as $x => $array) { 
                            $operator = $model->rowOperator[$x];
                            
                            // If operator changed, show subtotal for previous operator
                            if ($currentOperator !== null && $currentOperator !== $operator) {
                                ?>
                                <tr class="table-secondary">
                                    <td rowspan="1" colspan="9" class="text-left font-weight-bold">Totals for <?= $currentOperator ?>:</td>
                                    <th>Daily Exposure m/s² A(8)</th>
                                    <th>Daily Exposure points</th>
                                </tr>
                                <tr class="table-secondary">
                                    <th rowspan="2" colspan="2">
                                        Operator Signature <br />
                                        <?= Html::button('Reset', [ 'class' => 'btn btn-primary', 'onclick' => 'ClearCanvasX(' . $row . ');' ]); ?>
                                    </th>
                                    <td rowspan="2" colspan="7">
                                        <canvas id="canvas_<?= $row ?>" class="canvas"></canvas>
                                        <div class="d-none">
                                            <?= $form->field($model, "rowSign[$x]")->hiddenInput(['id' => 'signature' . $row])->label(false) ?>
                                        </div>
                                    </td>
                                    <td class="font-weight-bold operator-exposure-subtotal" data-operator="<?= htmlspecialchars($currentOperator) ?>">0.0</td>
                                    <td class="font-weight-bold operator-subtotal" data-operator="<?= htmlspecialchars($currentOperator) ?>"><?= $operatorTotal ?></td>
                                </tr>
                                <?php
                                $operatorTotal = 0;
                            }
                            
                            $currentOperator = $operator;
                        ?>
                            <tr class="datarows" data-operator="<?= htmlspecialchars($operator) ?>">
                                <td><?= $operator ?></td>
                                <td><?= $model->rowToolname[$x] ?></td>
                                <td><?= $form->field($model, "rowMagnitudeHSE[$x]")->textInput(['readonly' => true])->label(false) ?></td>
                                <td><?= $form->field($model, "rowMagnitudeUser[$x]")->textInput([])->label(false) ?></td>
                                <td><?= $form->field($model, "rowpph[$x]")->textInput(['readonly' => true])->label(false) ?></td>
                                <td><?= $form->field($model, "rowEAV[$x]")->textInput(['readonly' => true])->label(false) ?></td>
                                <td><?= $form->field($model, "rowELV[$x]")->textInput(['readonly' => true])->label(false) ?></td>
                                <td><?= $form->field($model, "rowhours[$x]")->textInput()->label(false) ?></td>
                                <td><?= $form->field($model, "rowminutes[$x]")->textInput()->label(false) ?></td>
                                <td><?= $form->field($model, "rowtoolms2[$x]")->textInput(['readonly' => true])->label(false) ?></td>
                                <td><?= $form->field($model, "rowpoints[$x]")->textInput(['readonly' => true])->label(false) ?></td>
                            </tr>
                            <?php 
                            $points = isset($model->rowpoints[$x]) ? $model->rowpoints[$x] : 0;
                            $operatorTotal += $points;
                            $grandTotal += $points;
                        } 
                        
                        // Show subtotal for last operator
                        if ($currentOperator !== null) {
                            ?>
                            <tr class="table-secondary">
                                <td rowspan="1" colspan="9" class="text-left font-weight-bold">Totals for <?= $currentOperator ?>:</td>
                                <th>Daily Exposure m/s² A(8)</th>
                                <th>Daily Exposure points</th>
                            </tr>
                                <tr class="table-secondary">
                                    <th rowspan="2" colspan="2">
                                        Operator Signature <br />
                                        <?= Html::button('Reset', [ 'class' => 'btn btn-primary', 'onclick' => 'ClearCanvasX(' . $row . ');' ]); ?>
                                    </th>
                                    <td rowspan="2" colspan="7">
                                        <canvas id="canvas_<?= $row ?>" class="canvas"></canvas>
                                        <div class="d-none">
                                            <?= $form->field($model, "rowSign[$x]")->hiddenInput(['id' => 'signature' . $row])->label(false) ?>
                                        </div>
                                    </td>
                                    <td class="font-weight-bold operator-exposure-subtotal" data-operator="<?= htmlspecialchars($currentOperator) ?>">0.0</td>
                                    <td class="font-weight-bold operator-subtotal" data-operator="<?= htmlspecialchars($currentOperator) ?>"><?= $operatorTotal ?></td>
                                </tr>
                            <?php
                            $row++;
                        }
                        ?>
                    </tbody>
                </table>
    
            </td>
        </tr>
    </tbody>
</table>
<?= $form->field($model, 'actid')->hiddenInput(['id' => 'actid'])->label(false) ?>
<div class="form-group">
    <?= Html::submitButton('Save', ['class' => 'btn btn-primary', 'onclick' => 'saveImages()' ]) ?>
</div>
<?php ActiveForm::end(); ?>

</div>
<script>
x = 0;

function saveImages() {
    while (x <= 1) {
        id = "signature" + x;
        cavid = "canvas_" + x;
        document.getElementById(id).value = document.getElementById(cavid).toDataURL();
        x++
    }
}
</script>