@extends('layouts.app')

@section('title', __('purchaseRequisition::lang.purchase_requisition_settings'))

@section('content')

<!-- Content Header -->
<section class="content-header">
    <h1>@lang('purchaseRequisition::lang.purchase_requisition_settings')</h1>
</section>

<!-- Main content -->
<section class="content">
    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])
                <div class="row">
                    <div class="col-md-12">
                        {!! Form::open(['url' => action([\Modules\PurchaseRequisition\Http\Controllers\PrSettingsController::class, 'store']), 'method' => 'post']) !!}

                        <h4>@lang('purchaseRequisition::lang.default_values')</h4>
                        <div class="col-md-4">
                            <div class="form-group">
                                {!! Form::label('selling_interval', __('purchaseRequisition::lang.selling_interval_days') . ':*') !!}
                                {!! Form::number('selling_interval', $settings['selling_interval'], ['class' => 'form-control', 'required', 'min' => 1]) !!}
                                <small class="text-muted">@lang('purchaseRequisition::lang.default_365_days')</small>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                {!! Form::label('stock_cover_interval', __('purchaseRequisition::lang.stock_cover_interval_days') . ':*') !!}
                                {!! Form::number('stock_cover_interval', $settings['stock_cover_interval'], ['class' => 'form-control', 'required', 'min' => 1]) !!}
                                <small class="text-muted">@lang('purchaseRequisition::lang.default_180_days')</small>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                {!! Form::label('margin_ratio', __('purchaseRequisition::lang.margin_ratio_percentage') . ':*') !!}
                                {!! Form::number('margin_ratio', $settings['margin_ratio'], ['class' => 'form-control', 'required', 'min' => 0, 'step' => '0.01']) !!}
                                <small class="text-muted">@lang('purchaseRequisition::lang.default_20_percent')</small>
                            </div>
                        </div>

                        <div class="clearfix"></div>
                        <hr>

                        <h4>@lang('purchaseRequisition::lang.calculation_options')</h4>
                        <div class="col-md-4">
                            <div class="form-group">
                                {!! Form::label('avg_cost_period', __('purchaseRequisition::lang.avg_cost_period') . ':') !!}
                                {!! Form::select('avg_cost_period', [
                                    'all' => __('purchaseRequisition::lang.avg_cost_all_time'),
                                    'year_ago' => __('purchaseRequisition::lang.avg_cost_year_ago'),
                                ], $settings['avg_cost_period'] ?? 'all', ['class' => 'form-control']) !!}
                                <small class="text-muted">@lang('purchaseRequisition::lang.avg_cost_period_help')</small>
                            </div>
                        </div>

                        <div class="clearfix"></div>
                        <hr>

                        <h4>@lang('purchaseRequisition::lang.background_colors')</h4>
                        <div class="col-md-3">
                            <div class="form-group">
                                {!! Form::label('bg_color_no_purchase', __('purchaseRequisition::lang.no_previous_purchase') . ':') !!}
                                {!! Form::text('bg_color_no_purchase', $settings['bg_color_no_purchase'], ['class' => 'form-control color-picker']) !!}
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group">
                                {!! Form::label('bg_color_no_purchase_no_stock', __('purchaseRequisition::lang.no_previous_purchase_no_stock') . ':') !!}
                                {!! Form::text('bg_color_no_purchase_no_stock', $settings['bg_color_no_purchase_no_stock'], ['class' => 'form-control color-picker']) !!}
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group">
                                {!! Form::label('bg_color_zero_qty', __('purchaseRequisition::lang.zero_quantity') . ':') !!}
                                {!! Form::text('bg_color_zero_qty', $settings['bg_color_zero_qty'], ['class' => 'form-control color-picker']) !!}
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="form-group">
                                {!! Form::label('bg_color_low_margin', __('purchaseRequisition::lang.low_margin') . ':') !!}
                                {!! Form::text('bg_color_low_margin', $settings['bg_color_low_margin'], ['class' => 'form-control color-picker']) !!}
                            </div>
                        </div>

                        <div class="col-md-12">
                            <button type="submit" class="btn btn-primary">@lang('messages.save')</button>
                        </div>

                        {!! Form::close() !!}
                    </div>
                </div>
            @endcomponent
        </div>
    </div>

    <!-- Currencies Section -->
    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('purchaseRequisition::lang.currencies')])
                <div class="row">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-primary btn-sm" id="add_currency_btn">
                            <i class="fa fa-plus"></i> @lang('purchaseRequisition::lang.add_currency')
                        </button>
                    </div>
                </div>
                <br>
                <div class="row">
                    <div class="col-md-12">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="currencies_table">
                                <thead>
                                    <tr>
                                        <th>@lang('purchaseRequisition::lang.code')</th>
                                        <th>@lang('purchaseRequisition::lang.name')</th>
                                        <th>@lang('purchaseRequisition::lang.symbol')</th>
                                        <th>@lang('purchaseRequisition::lang.conversion_rate_to_egp')</th>
                                        <th>@lang('purchaseRequisition::lang.status')</th>
                                        <th>@lang('messages.action')</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            @endcomponent
        </div>
    </div>

    <!-- User Permissions Section -->
    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('purchaseRequisition::lang.user_permissions')])
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i> @lang('purchaseRequisition::lang.user_access_info')
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped" id="users_table">
                        <thead>
                            <tr>
                                <th>@lang('business.username')</th>
                                <th>@lang('purchaseRequisition::lang.full_name')</th>
                                <th>@lang('user.role')</th>
                                <th>@lang('business.email')</th>
                                <th>@lang('purchaseRequisition::lang.module_access')</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            @endcomponent
        </div>
    </div>
</section>

<!-- Currency Modal -->
<div class="modal fade" id="currency_modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                <h4 class="modal-title">@lang('purchaseRequisition::lang.add_currency')</h4>
            </div>
            <div class="modal-body">
                {!! Form::open(['id' => 'currency_form']) !!}
                {!! Form::hidden('id', null, ['id' => 'currency_id']) !!}

                <div class="form-group">
                    {!! Form::label('code', __('purchaseRequisition::lang.currency_code') . ':*') !!}
                    {!! Form::text('code', null, ['class' => 'form-control', 'required', 'maxlength' => 10]) !!}
                </div>

                <div class="form-group">
                    {!! Form::label('name', __('purchaseRequisition::lang.currency_name') . ':*') !!}
                    {!! Form::text('name', null, ['class' => 'form-control', 'required', 'maxlength' => 100]) !!}
                </div>

                <div class="form-group">
                    {!! Form::label('symbol', __('purchaseRequisition::lang.currency_symbol') . ':*') !!}
                    {!! Form::text('symbol', null, ['class' => 'form-control', 'required', 'maxlength' => 10]) !!}
                </div>

                <div class="form-group">
                    {!! Form::label('conversion_rate_to_egp', __('purchaseRequisition::lang.conversion_rate_to_egp') . ':*') !!}
                    {!! Form::number('conversion_rate_to_egp', 1, ['class' => 'form-control', 'required', 'min' => 0, 'step' => '0.0001']) !!}
                </div>

                <div class="form-group">
                    <div class="checkbox">
                        <label>
                            {!! Form::checkbox('is_active', 1, true) !!}
                            @lang('purchaseRequisition::lang.active')
                        </label>
                    </div>
                </div>

                {!! Form::close() !!}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">@lang('messages.close')</button>
                <button type="button" class="btn btn-primary" id="save_currency_btn">@lang('messages.save')</button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('javascript')
<script type="text/javascript">
$(document).ready(function() {

    // Initialize color pickers
    $('.color-picker').colorpicker();

    // Currencies DataTable
    var currencies_table = $('#currencies_table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrSettingsController::class, "getCurrencies"]) }}',
        columns: [
            { data: 'code', name: 'code' },
            { data: 'name', name: 'name' },
            { data: 'symbol', name: 'symbol' },
            { data: 'conversion_rate_to_egp', name: 'conversion_rate_to_egp' },
            { data: 'is_active', name: 'is_active' },
            { data: 'action', name: 'action', orderable: false, searchable: false }
        ]
    });

    // Users DataTable
    var users_table = $('#users_table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrSettingsController::class, "indexUsers"]) }}',
        columns: [
            { data: 'username', name: 'username' },
            { data: 'full_name', name: 'full_name' },
            { data: 'role', name: 'role' },
            { data: 'email', name: 'email' },
            { data: 'has_access', name: 'has_access', orderable: false, searchable: false }
        ]
    });

    // Toggle user access
    $(document).on('change', '.toggle-user-access', function() {
        var userId = $(this).data('user-id');
        var hasAccess = $(this).is(':checked') ? 1 : 0;

        $.ajax({
            method: 'POST',
            url: '{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrSettingsController::class, "toggleUserAccess"]) }}',
            data: {
                user_id: userId,
                has_access: hasAccess
            },
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    toastr.success(result.msg);
                } else {
                    toastr.error(result.msg);
                    users_table.ajax.reload();
                }
            },
            error: function() {
                toastr.error('@lang("messages.something_went_wrong")');
                users_table.ajax.reload();
            }
        });
    });

    // Add currency button
    $('#add_currency_btn').click(function() {
        $('#currency_form')[0].reset();
        $('#currency_id').val('');
        $('#currency_modal .modal-title').text('@lang("purchaseRequisition::lang.add_currency")');
        $('#currency_modal').modal('show');
    });

    // Edit currency
    $(document).on('click', '.edit-currency', function(e) {
        e.preventDefault();
        var id = $(this).data('id');

        // Get currency data via AJAX (you can implement this)
        $('#currency_modal .modal-title').text('@lang("messages.edit")');
        $('#currency_modal').modal('show');
    });

    // Save currency
    $('#save_currency_btn').click(function() {
        var formData = $('#currency_form').serialize();

        $.ajax({
            method: 'POST',
            url: '{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrSettingsController::class, "storeCurrency"]) }}',
            data: formData,
            dataType: 'json',
            success: function(result) {
                if (result.success) {
                    toastr.success(result.msg);
                    $('#currency_modal').modal('hide');
                    currencies_table.ajax.reload();
                } else {
                    toastr.error(result.msg);
                }
            }
        });
    });

    // Delete currency
    $(document).on('click', '.delete-currency', function(e) {
        e.preventDefault();
        var id = $(this).data('id');

        swal({
            title: '@lang("messages.sure")',
            icon: "warning",
            buttons: true,
            dangerMode: true,
        }).then((willDelete) => {
            if (willDelete) {
                $.ajax({
                    method: 'DELETE',
                    url: '{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrSettingsController::class, "deleteCurrency"], ["id" => "__id__"]) }}'.replace('__id__', id),
                    dataType: 'json',
                    success: function(result) {
                        if (result.success) {
                            toastr.success(result.msg);
                            currencies_table.ajax.reload();
                        } else {
                            toastr.error(result.msg);
                        }
                    }
                });
            }
        });
    });
});
</script>
@endsection
