@extends('layouts.app')

@section('title', 'Controlled Drug Stocktake')

@section('css')
@include('vetClinic::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1>
        <i class="fas fa-balance-scale"></i> Controlled-Drug Stocktake
        <small>Physical count vs system balance · variance auto-adjusts</small>
    </h1>
</section>

<section class="content">

    <div class="row">
        <div class="col-md-7">
            <div class="box box-solid">
                <div class="box-header with-border">
                    <h3 class="box-title"><i class="fa fa-check-double"></i> New stocktake</h3>
                </div>
                <div class="box-body">

                    <div class="alert alert-info" style="font-size:13px;">
                        <i class="fa fa-info-circle"></i>
                        Enter the <strong>physical count</strong> from the cupboard. If it does not
                        match the system, the variance is logged as a paired
                        <em>adjust / correction</em> movement so the running balance reconciles to
                        reality — the audit chain stays intact.
                    </div>

                    <form id="stocktake-form">
                        @csrf
                        <div class="form-group">
                            <label>Medicine *</label>
                            <select name="medicine_id" id="medicine_id" class="form-control select2" required>
                                <option value="">— pick a controlled medicine —</option>
                                @foreach($medicines as $m)
                                    <option value="{{ $m->id }}" data-unit="{{ $m->unit }}">
                                        {{ $m->name }} ({{ $m->controlled_schedule }})
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Batch # <small class="text-muted">(blank = sum of all batches)</small></label>
                            <input type="text" name="batch_no" id="batch_no" class="form-control" maxlength="60">
                        </div>

                        <div class="row">
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>System balance</label>
                                    <input type="text" id="expected_qty" class="form-control" readonly
                                        style="background:#f1f5f9;font-weight:700;font-family:monospace;">
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="form-group">
                                    <label>Counted quantity *</label>
                                    <input type="number" step="0.001" min="0" name="counted_qty"
                                        id="counted_qty" class="form-control" required
                                        style="font-weight:700;font-family:monospace;">
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Variance</label>
                            <div id="variance-display"
                                style="padding:10px 14px;border-radius:6px;background:#f8fafc;
                                       font-family:monospace;font-size:15px;font-weight:700;
                                       border:1px solid #e2e8f0;">
                                Pick a medicine + enter a count.
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Witness <small class="text-muted">(another staff member who counted with you)</small></label>
                            <select name="witnessed_by" class="form-control select2">
                                <option value="">— none —</option>
                                @foreach($witnesses as $u)
                                    <option value="{{ $u->id }}">{{ $u->first_name }} {{ $u->last_name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Notes</label>
                            <textarea name="notes" rows="2" class="form-control" maxlength="500"
                                placeholder="Reason for variance (spill, miscount, expiry write-off, …)"></textarea>
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="fa fa-save"></i> Record stocktake
                        </button>
                        <a href="{{ route('vc.controlled-register.index') }}" class="btn btn-default">
                            Cancel
                        </a>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-5">
            <div class="box box-solid">
                <div class="box-header with-border">
                    <h3 class="box-title"><i class="fa fa-history"></i> Recent stocktakes</h3>
                </div>
                <div class="box-body" style="padding:0;">
                    @if($recent->isEmpty())
                        <p class="text-muted" style="padding:16px;text-align:center;">No stocktakes recorded yet.</p>
                    @else
                        <table class="table table-bordered" style="margin-bottom:0;font-size:12px;">
                            <thead>
                                <tr>
                                    <th>Ref</th>
                                    <th>Medicine</th>
                                    <th class="text-right">Expected</th>
                                    <th class="text-right">Counted</th>
                                    <th class="text-right">Variance</th>
                                    <th>By</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($recent as $r)
                                    @php
                                        $vColor = $r->variance > 0.0005 ? '#15803d' :
                                                  ($r->variance < -0.0005 ? '#b91c1c' : '#64748b');
                                    @endphp
                                    <tr>
                                        <td><small>{{ $r->reference }}</small></td>
                                        <td>
                                            <strong>{{ optional($r->medicine)->name }}</strong>
                                            @if($r->batch_no)
                                                <br><small class="text-muted">batch {{ $r->batch_no }}</small>
                                            @endif
                                        </td>
                                        <td class="text-right">{{ rtrim(rtrim(number_format((float) $r->expected_qty, 3, '.', ''), '0'), '.') }}</td>
                                        <td class="text-right">{{ rtrim(rtrim(number_format((float) $r->counted_qty, 3, '.', ''), '0'), '.') }}</td>
                                        <td class="text-right" style="color:{{ $vColor }};font-weight:700;">
                                            {{ $r->variance > 0 ? '+' : '' }}{{ rtrim(rtrim(number_format((float) $r->variance, 3, '.', ''), '0'), '.') }}
                                        </td>
                                        <td>
                                            <small>{{ optional($r->createdBy)->first_name }}<br>
                                            {{ optional($r->stocktake_at)->format('d M Y') }}</small>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    @endif
                </div>
            </div>
        </div>
    </div>

</section>
@endsection

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

    var EXPECTED_URL = '{{ route('vc.controlled-register.expected-balance') }}';
    var STORE_URL    = '{{ route('vc.controlled-register.reconcile.store') }}';

    function fmt(v) {
        var n = parseFloat(v) || 0;
        return n.toFixed(3).replace(/\.?0+$/, '');
    }

    function refreshExpected() {
        var mid = $('#medicine_id').val();
        if (!mid) {
            $('#expected_qty').val('');
            recalcVariance();
            return;
        }
        $.get(EXPECTED_URL, {
            medicine_id: mid,
            batch_no:    $('#batch_no').val()
        }).done(function (res) {
            $('#expected_qty').val(fmt(res.expected));
            recalcVariance();
        });
    }

    function recalcVariance() {
        var exp = parseFloat($('#expected_qty').val()) || 0;
        var cnt = parseFloat($('#counted_qty').val());
        var box = $('#variance-display');
        if ($('#expected_qty').val() === '' || isNaN(cnt)) {
            box.css({ background: '#f8fafc', color: '#1e293b' })
               .text('Pick a medicine + enter a count.');
            return;
        }
        var v = cnt - exp;
        if (Math.abs(v) < 0.0005) {
            box.css({ background: '#ecfdf5', color: '#065f46', border: '1px solid #a7f3d0' })
               .html('✓ Count matches the register — no adjustment will be made.');
        } else if (v > 0) {
            box.css({ background: '#dbeafe', color: '#1e40af', border: '1px solid #93c5fd' })
               .html('+ ' + fmt(v) + ' — surplus. A <em>correction</em> row will raise the balance.');
        } else {
            box.css({ background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca' })
               .html('− ' + fmt(Math.abs(v)) + ' — shortfall. An <em>adjust</em> row will lower the balance.');
        }
    }

    $('#medicine_id, #batch_no').on('change', refreshExpected);
    $('#counted_qty').on('input', recalcVariance);

    $('#stocktake-form').on('submit', function (e) {
        e.preventDefault();
        var btn = $(this).find('button[type=submit]');
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving…');
        $.ajax({
            url: STORE_URL,
            method: 'POST',
            data: $(this).serialize(),
            success: function (res) {
                if (res.success) {
                    toastr.success(res.msg);
                    setTimeout(function () { window.location.reload(); }, 1200);
                } else {
                    toastr.error(res.msg || 'Could not save stocktake.');
                    btn.prop('disabled', false).html('<i class="fa fa-save"></i> Record stocktake');
                }
            },
            error: function (xhr) {
                var m = xhr.responseJSON && xhr.responseJSON.msg;
                toastr.error(m || 'Server error.');
                btn.prop('disabled', false).html('<i class="fa fa-save"></i> Record stocktake');
            }
        });
    });
});
</script>
@endsection
