@extends('backEnd.layouts.master')
@section('title',$order_status->name.' Order')

@section('css')
<style>
    .btn-action {
        width: 32px;
        height: 32px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        background: #fff;
        color: #64748b;
        transition: all 0.2s;
        padding: 0;
    }
    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        color: #0f172a;
    }
    .btn-view:hover { color: #8b5cf6; border-color: #8b5cf6; }
    .btn-edit:hover { color: #2563eb; border-color: #2563eb; }
    .btn-process:hover { color: #10b981; border-color: #10b981; }
    .btn-delete:hover { color: #ef4444; border-color: #ef4444; }
    .btn-block-ip:hover { color: #dc2626; border-color: #dc2626; background-color: #fef2f2; }
</style>
@endsection

@section('content')
<div class="container-fluid">
    
    <div class="row mb-3 mt-1">
        <div class="col-12 d-flex justify-content-between align-items-center">
            <h4 class="page-title mb-0">{{ $order_status->name }} Orders <span class="text-muted fs-5 ms-1">({{ $order_status->orders_count }})</span></h4>
            <div class="page-title-right">
                <a href="{{ route('admin.order.create') }}" class="btn btn-primary shadow-sm">
                    <i class="fe-shopping-cart me-1"></i> POS Create
                </a>
            </div>
        </div>
    </div>
    <div class="row order_page">
        <div class="col-12">
            <div class="card shadow border-0" style="border-radius: 10px;">
                <div class="card-body p-4">
                    <div class="row mb-4 align-items-center bg-light p-3 rounded mx-0 shadow-sm border border-light">
                        <div class="col-sm-9">
                            <div class="d-flex flex-wrap gap-2">
                                <a data-bs-toggle="modal" data-bs-target="#asignUser" class="btn btn-light btn-sm border fw-bold px-3"><i class="fe-user-plus me-1 text-primary"></i> Assign</a>
                                <a data-bs-toggle="modal" data-bs-target="#changeStatus" class="btn btn-light btn-sm border fw-bold px-3"><i class="fe-refresh-cw me-1 text-info"></i> Status</a>
                                <a href="{{ route('admin.order.bulk_destroy') }}" class="btn btn-light btn-sm border fw-bold px-3 order_delete text-danger"><i class="fe-trash-2 me-1"></i> Delete</a>
                                <a href="{{ route('admin.order.order_print') }}" class="btn btn-light btn-sm border fw-bold px-3 multi_order_print"><i class="fe-printer me-1"></i> Print</a>
                                <a href="{{ route('admin.order.order_print') }}" class="btn btn-light btn-sm border fw-bold px-3 multi_label_print"><i class="fe-tag me-1"></i> Label</a>
                                @if($steadfast)
                                    <a href="{{ route('admin.bulk_courier', 'steadfast') }}?status=5" class="btn btn-light btn-sm border fw-bold px-3 multi_order_courier"><i class="fe-truck me-1 text-primary"></i> Steadfast</a>
                                @endif
                                @if($pathao_info)
                                    <a data-bs-toggle="modal" data-bs-target="#pathao" class="btn btn-light btn-sm border fw-bold px-3"><i class="fe-truck me-1 text-warning"></i> Pathao</a>
                                @endif
                                @if(isset($redx_info) && $redx_info)
                                    <a href="{{ route('admin.bulk_courier', 'redx') }}?status=5" class="btn btn-light btn-sm border fw-bold px-3 multi_order_courier"><i class="fe-truck me-1 text-danger"></i> RedX</a>
                                @endif
                            </div>
                        </div>
                        <div class="col-sm-3">
                            <form class="custom_form" method="GET">
                                <div class="input-group shadow-sm border" style="border-radius: 6px; overflow: hidden;">
                                    <input type="text" name="keyword" placeholder="Search orders..." class="form-control border-0 bg-white shadow-none">
                                    <button class="btn btn-white border-0 bg-white"><i class="fe-search text-muted"></i></button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="table-responsive border rounded shadow-sm">
                        <table id="datatable-buttons" class="table table-hover align-middle w-100 mb-0 bg-white" style="font-size: 0.9rem;">
                            <thead class="table-light text-uppercase text-muted" style="font-size: 0.75rem; letter-spacing: 0.5px; border-bottom: 2px solid #e3e6f0;">
                                <tr>
                                    <th style="min-width: 40px; padding: 1rem;">
                                        <div class="form-check">
                                            <label class="form-check-label">
                                                <input type="checkbox" class="form-check-input checkall" value="">
                                            </label>
                                        </div>
                                    </th>
                                    <th style="min-width: 40px; padding: 1rem;">SL</th>
                                    <th style="min-width: 140px; padding: 1rem;">Action</th>
                                    <th style="min-width: 100px; padding: 1rem;">Invoice</th>
                                    <th style="min-width: 120px; padding: 1rem;">Date</th>
                                    <th style="min-width: 160px; padding: 1rem;">Name</th>
                                    <th style="min-width: 80px; padding: 1rem;">Type</th>
                                    <th style="min-width: 130px; padding: 1rem;">IP</th>
                                    <th style="min-width: 110px; padding: 1rem;">Order Note</th>
                                    <th style="min-width: 110px; padding: 1rem;">Admin Note</th>
                                    <th style="min-width: 100px; padding: 1rem;">Amount</th>
                                    <th style="min-width: 100px; padding: 1rem;">Status</th>
                                    <th style="min-width: 130px; padding: 1rem;">Courier</th>
                                    <th style="min-width: 80px; padding: 1rem;">Track</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($show_data as $key => $value)
                                    <tr>
                                        <td><input type="checkbox" class="checkbox form-check-input" value="{{ $value->id }}"></td>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>
                                            <div class="d-flex justify-content-center gap-1">
                                                <a href="{{ route('admin.order.invoice', ['invoice_id' => $value->invoice_id]) }}" class="btn-action btn-view" title="Invoice"><i class="fe-eye"></i></a>
                                                <a href="{{ route('admin.order.process', ['invoice_id' => $value->invoice_id]) }}" class="btn-action btn-process" title="Process"><i class="fe-settings"></i></a>
                                                <a href="{{ route('admin.order.edit', ['invoice_id' => $value->invoice_id]) }}" class="btn-action btn-edit" title="Edit"><i class="fe-edit"></i></a>
                                                <form method="post" action="{{ route('admin.order.destroy') }}" class="d-inline">
                                                    @csrf
                                                    <input type="hidden" value="{{ $value->id }}" name="id">
                                                    <button type="submit" title="Delete" class="delete-confirm btn-action btn-delete"><i class="fe-trash-2"></i></button>
                                                </form>
                                            </div>
                                        </td>
                                        <td><span class="fw-bold text-dark">{{ $value->invoice_id }}</span></td>
                                        <td>
                                            <div class="text-nowrap">
                                                <span class="d-block text-dark">{{ date('d-M-Y', strtotime($value->updated_at)) }}</span>
                                                <small class="text-muted"><i class="fe-clock"></i> {{ date('h:i A', strtotime($value->updated_at)) }}</small>
                                            </div>
                                        </td>
                                        <td>
                                            <strong>{{ $value->shipping ? $value->shipping->name : '' }}</strong>
                                            <p class="mb-1 text-muted" style="font-size: 0.8rem;">{{ $value->shipping ? $value->shipping->phone : '' }}</p>
                                            @if($value->shipping && $value->shipping->address)
                                                <p class="mb-1 text-muted small text-wrap" style="max-width: 180px; line-height: 1.3;" title="{{ $value->shipping->address }}">
                                                    <i class="fe-map-pin me-1 text-danger"></i>{{ Str::limit($value->shipping->address, 65) }}
                                                </p>
                                            @endif
                                            @if($value->shipping && $value->shipping->map)
                                                <a href="{{ $value->shipping->map }}" target="_blank" class="badge bg-success text-white py-1 px-2 d-inline-flex align-items-center gap-1 mt-1" style="font-size: 0.75rem; text-decoration: none; width: fit-content; border-radius: 4px;">
                                                    <i class="fe-map-pin"></i> Open Map
                                                </a>
                                            @endif
                                        </td>
                                        <td>
                                            @php
                                                $items = $value->orderDetails;
                                                $types = [];
                                                foreach ($items as $item) {
                                                    if ($item->product && $item->product->is_digital == 1) {
                                                        $types[] = 'Digital';
                                                    } else {
                                                        $types[] = 'Physical';
                                                    }
                                                }
                                                $types = array_unique($types);
                                                if (count($types) === 1) {
                                                    echo $types[0];
                                                } else {
                                                    echo "Mixed";
                                                }
                                            @endphp
                                        </td>


                                        <td>
                                            <div class="d-flex align-items-center gap-2">
                                                <span>{{ $value->ip_address }}</span>
                                                @if($value->ip_address)
                                                    @php
                                                        $isBlocked = in_array($value->ip_address, isset($blockedIps) ? $blockedIps : []);
                                                    @endphp
                                                    @if($isBlocked)
                                                        <button type="button" class="btn-action bg-light" title="This IP is blocked" disabled>
                                                            <i class="fe-shield text-secondary"></i>
                                                        </button>
                                                    @else
                                                        <button type="button" 
                                                                class="btn-action btn-block-ip block-ip-btn" 
                                                                data-ip="{{ $value->ip_address }}"
                                                                data-reason="ফেইক অর্ডার"
                                                                title="Block this IP - ফেইক অর্ডার">
                                                            <i class="fe-shield-off"></i>
                                                        </button>
                                                    @endif
                                                @endif
                                            </div>
                                        </td>
                                        {{-- Order Note (client) --}}
                                        <td>
                                            @php
                                                $orderNote = isset($value->order_note) ? $value->order_note : (isset($value->note) ? $value->note : '');
                                            @endphp

                                            <button
                                                type="button"
                                                class="btn btn-sm btn-outline-info note-modal-btn"
                                                data-type="order"
                                                data-id="{{ $value->id }}"
                                                data-note="{{ $orderNote }}"
                                            >
                                                {{ $orderNote ? 'View' : 'Add' }}
                                            </button>
                                        </td>

                                        {{-- Admin Note --}}
                                        <td>
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-outline-warning note-modal-btn"
                                                data-type="admin"
                                                data-id="{{ $value->id }}"
                                                data-note="{{ isset($value->admin_note) ? $value->admin_note : '' }}"
                                            >
                                                {{ $value->admin_note ? 'View' : 'Add' }}
                                            </button>
                                        </td>

                                        {{-- Amount (show remaining if partial paid) --}}
                                        <td>
                                            @php
                                                $payment = \App\Models\Payment::where('order_id', $value->id)->first();
                                                $paid = $payment ? floatval($payment->amount) : 0;
                                                $total = floatval($value->amount);
                                                $showAmount = $total;
                                                if ($paid > 0 && $paid < $total) {
                                                    $showAmount = $total - $paid;
                                                }
                                            @endphp
                                            ৳{{ number_format($showAmount, 2) }}
                                        </td>

                                        <td>
                                            <span class="badge bg-light text-dark border px-2 py-1 shadow-sm">{{ $value->status ? $value->status->name : '' }}</span>
                                        </td>

                                        {{-- Courier Information --}}
                                        <td>
                                            @php
                                                // Priority: courier_tracking_id > consignment_id
                                                $trackingId = isset($value->courier_tracking_id) ? $value->courier_tracking_id : $value->consignment_id;
                                                $courierType = $value->courier_type;
                                                
                                                // If no courier_type but has consignment_id, assume it's steadfast (backward compatibility)
                                                // This handles old orders that were sent via Steadfast but don't have courier_type
                                                if (!$courierType && $value->consignment_id) {
                                                    $courierType = 'steadfast';
                                                }
                                                
                                                // If still no courier_type but has tracking_id, assume steadfast
                                                if (!$courierType && $trackingId) {
                                                    $courierType = 'steadfast';
                                                }
                                            @endphp
                                            
                                            @if($trackingId)
                                                @php
                                                    $courierName = ucfirst(isset($courierType) ? $courierType : 'Steadfast');
                                                    $ct = isset($courierType) ? strtolower($courierType) : 'steadfast';
                                                    if ($ct === 'pathao') { $courierColor = 'info'; }
                                                    elseif ($ct === 'steadfast') { $courierColor = 'primary'; }
                                                    elseif ($ct === 'redx') { $courierColor = 'warning'; }
                                                    else { $courierColor = 'primary'; }
                                                @endphp
                                                <div>
                                                    <span class="badge bg-{{ $courierColor }} mb-1">
                                                        <i class="fe-truck"></i> {{ $courierName }}
                                                    </span>
                                                    <br>
                                                    <small class="text-muted" style="font-size: 0.75rem;">
                                                        ID: {{ Str::limit($trackingId, 15) }}
                                                    </small>
                                                    @if($value->courier_sent_at)
                                                        <br>
                                                        <small class="text-muted" style="font-size: 0.7rem;">
                                                            {{ date('d-m-Y', strtotime($value->courier_sent_at)) }}
                                                        </small>
                                                    @endif
                                                </div>
                                            @else
                                                <span class="text-muted">-</span>
                                            @endif
                                        </td>

                                        <td>
                                            @php
                                                // Get tracking ID (new field or fallback to old consignment_id)
                                                $trackingId = isset($value->courier_tracking_id) ? $value->courier_tracking_id : $value->consignment_id;
                                                $courierType = $value->courier_type;
                                                
                                                // If no courier_type but has consignment_id, assume it's steadfast
                                                if (!$courierType && $value->consignment_id) {
                                                    $courierType = 'steadfast';
                                                }
                                            @endphp
                                            
                                            @if(!empty($trackingId))
                                                @if($courierType == 'pathao')
                                                    <a href="https://merchant.pathao.com/public-tracking?consignment_id={{ $trackingId }}" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-info">
                                                        <i class="fe-truck"></i> Track
                                                    </a>
                                                @elseif($courierType == 'steadfast' || (!$courierType && $trackingId))
                                                    <a href="https://steadfast.com.bd/t/{{ $trackingId }}" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-primary">
                                                        <i class="fe-truck"></i> Track
                                                    </a>
                                                @elseif($courierType == 'redx')
                                                    <a href="https://redx.com.bd/track/{{ $trackingId }}" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-warning">
                                                        <i class="fe-truck"></i> Track
                                                    </a>
                                                @else
                                                    <span class="badge bg-secondary">{{ $trackingId }}</span>
                                                @endif
                                            @else
                                                <span class="text-muted">কোন রেকর্ড নেই</span>
                                            @endif
                                        </td>

                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                    <div class="custom-paginate mt-3">
                        {{ $show_data->links('pagination::bootstrap-4') }}
                    </div>
                </div> </div> </div></div>
</div>

<div class="modal fade" id="asignUser" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Assign Delivery Man</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="{{ route('admin.order.assign') }}" id="order_assign">
        <div class="modal-body">
            <div class="form-group">
                <select name="delivery_man_id" id="delivery_man_id" class="form-control">
                    <option value="">Select..</option>
                    @foreach($deliveryMen as $dm)
                        <option value="{{ $dm->id }}">{{ $dm->name }} @if($dm->phone)({{ $dm->phone }})@endif</option>
                    @endforeach
                </select>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="changeStatus" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Change Status</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="{{ route('admin.order.status') }}" id="order_status_form" novalidate>
        <div class="modal-body">
            <div class="form-group">
                <label class="form-label">Select Status <span class="text-danger">*</span></label>
                <select name="order_status" id="order_status" class="form-control">
                    <option value="">Select Status..</option>
                    @if(isset($orderstatus) && $orderstatus->count() > 0)
                        @foreach($orderstatus as $s)
                            <option value="{{ $s->id }}">{{ $s->name }}</option>
                        @endforeach
                    @else
                        <option value="">No status available</option>
                    @endif
                </select>
                <small class="text-muted">Select orders first, then choose status</small>
                <div class="invalid-feedback" id="status_error" style="display: none;">Please select a status</div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-success">Update Status</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="pathao" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Pathao Courier</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form action="{{ route('admin.order.pathao') }}" id="order_sendto_pathao" method="POST">
      @csrf
      <input type="hidden" name="order_ids" id="pathao_order_ids" value="">
      <div class="modal-body">
        <div class="form-group">
            <label for="pathaostore" class="form-label">Store</label>
           <select name="pathaostore" id="pathaostore" class="pathaostore form-control" >
             <option value="">Select Store...</option>
             @if(isset($pathaostore['data']['data']))
                 @foreach($pathaostore['data']['data'] as $store)
                     <option value="{{ $store['store_id'] }}">{{ $store['store_name'] }}</option>
                 @endforeach
             @endif
           </select>
        </div>

        <div class="form-group mt-3">
          <label for="pathaocity" class="form-label">City</label>
           <select name="pathaocity" id="pathaocity" class="chosen-select pathaocity form-control" style="width:100%" >
             <option value="">Select City...</option>
             @if(isset($pathaocities['data']['data']))
                 @foreach($pathaocities['data']['data'] as $city)
                     <option value="{{ $city['city_id'] }}">{{ $city['city_name'] }}</option>
                 @endforeach
             @endif
           </select>
        </div>

        <div class="form-group mt-3">
          <label class="form-label">Zone</label>
             <select name="pathaozone" id="pathaozone" class="pathaozone chosen-select form-control" style="width:100%"></select>
        </div>

        <div class="form-group mt-3">
          <label class="form-label">Area</label>
             <select name="pathaoarea" id="pathaoarea" class="pathaoarea chosen-select form-control" style="width:100%"></select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-success">Submit</button>
      </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="noteModal" tabindex="-1" aria-labelledby="noteModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="noteModalLabel">Note</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <div class="modal-body">
        <input type="hidden" id="note_order_id">
        <input type="hidden" id="note_type">

        <div class="form-group">
            <label id="note_label">Note</label>
            <textarea id="note_modal_text" class="form-control" rows="5" placeholder="Write note here..."></textarea>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success" id="saveNoteBtn">Save</button>
      </div>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){

    // Order Note / Admin Note popup open
    $(document).on('click', '.note-modal-btn', function (e) {
        e.preventDefault();
        let orderId = $(this).data('id');
        let type    = $(this).data('type');
        let note    = $(this).data('note') || '';

        $('#note_order_id').val(orderId);
        $('#note_type').val(type);
        $('#note_modal_text').val(note);

        if (type === 'admin') {
            $('#noteModalLabel').text('Admin Note');
            $('#note_label').text('Admin Note');
        } else {
            $('#noteModalLabel').text('Order Note (Customer)');
            $('#note_label').text('Order Note (Customer)');
        }

        $('#noteModal').modal('show');
    });

    // Save Note (AJAX)
    $('#saveNoteBtn').on('click', function () {
        let orderId = $('#note_order_id').val();
        let type    = $('#note_type').val();
        let note    = $('#note_modal_text').val();

        $.ajax({
            url: "{{ route('admin.order.update_note') }}",
            type: "POST",
            data: {
                _token: "{{ csrf_token() }}",
                order_id: orderId,
                note_type: type,
                note: note
            },
            success: function (res) {
                if (res.status === 'success') {
                    toastr.success('Note updated successfully');
                    let selector = '.note-modal-btn[data-id="' + orderId + '"][data-type="' + type + '"]';
                    let $btn = $(selector);
                    $btn.data('note', note);
                    $btn.text(note ? 'View' : 'Add');
                    $('#noteModal').modal('hide');
                } else {
                    toastr.error(res.message || 'Update failed');
                }
            },
            error: function () {
                toastr.error('Something went wrong');
            }
        });
    });

    // checkall
    $(".checkall").on('change',function(){
      $(".checkbox").prop('checked',$(this).is(":checked"));
    });

    // order assign
    $(document).on('submit', 'form#order_assign', function(e){
        e.preventDefault();
        var url = $(this).attr('action');
        let delivery_man_id = $('#delivery_man_id').val();

        var order = $('input.checkbox:checked').map(function(){
          return $(this).val();
        });
        var order_ids = order.get();

        if(order_ids.length == 0){
            toastr.error('Please Select An Order First !');
            return;
        }

        $.ajax({
           type: 'GET',
           url: url,
           data: { delivery_man_id: delivery_man_id, order_ids: order_ids },
           success: function(res){
               if(res.status == 'success'){
                   toastr.success(res.message);
                   window.location.reload();
               } else {
                   toastr.error(res.message || 'Failed something wrong');
               }
           },
           error: function(){
               toastr.error('Something went wrong');
           }
        });
    });

    // order status change
    $(document).on('submit', 'form#order_status_form', function(e){
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
        
        var url = $(this).attr('action');
        let order_status = $('#order_status').val();
        var $statusSelect = $('#order_status');
        var $statusError = $('#status_error');
        
        // Clear any previous validation state
        $statusSelect.removeClass('is-invalid is-valid');
        $statusError.hide();

        var order = $('input.checkbox:checked').map(function(){
          return $(this).val();
        });
        var order_ids = order.get();

        // Validate orders selected FIRST
        if(order_ids.length == 0){
            toastr.error('Please Select An Order First !');
            return false;
        }
        
        // Validate status selected - check multiple conditions
        var statusValue = String(order_status || '').trim();
        if(!statusValue || statusValue === '' || statusValue === 'null' || statusValue === 'undefined' || statusValue === '0'){
            $statusSelect.addClass('is-invalid');
            $statusError.text('Please select a status').show();
            toastr.error('Please Select A Status First !');
            // Focus on select field and scroll to it
            $statusSelect.focus();
            $('html, body').animate({
                scrollTop: $statusSelect.offset().top - 100
            }, 300);
            return false;
        }
        
        // Additional check - make sure it's a valid number
        if(isNaN(parseInt(statusValue)) || parseInt(statusValue) <= 0){
            $statusSelect.addClass('is-invalid');
            $statusError.text('Please select a valid status').show();
            toastr.error('Please Select A Valid Status !');
            $statusSelect.focus();
            return false;
        }

        // Show loading
        var $form = $(this);
        var $submitBtn = $form.find('button[type="submit"]');
        var originalHtml = $submitBtn.html();
        $submitBtn.prop('disabled', true).html('<i class="fe-loader"></i> Updating...');

        $.ajax({
           type: 'GET',
           url: url,
           data: { order_status: order_status, order_ids: order_ids },
           success: function(res){
               if(res.status == 'success'){
                   toastr.success(res.message);
                   $('#changeStatus').modal('hide');
                   setTimeout(function(){
                       window.location.reload();
                   }, 1000);
               } else {
                   toastr.error(res.message || 'Failed something wrong');
                   $submitBtn.prop('disabled', false).html(originalHtml);
               }
           },
           error: function(xhr){
               console.error('Status update error:', xhr);
               var errorMsg = 'Something went wrong';
               
               // Handle Laravel validation errors
               if(xhr.status === 422 && xhr.responseJSON && xhr.responseJSON.errors){
                   var errors = xhr.responseJSON.errors;
                   if(errors.order_status){
                       $statusSelect.addClass('is-invalid');
                       $statusError.text(errors.order_status[0]).show();
                       errorMsg = errors.order_status[0];
                   } else if(errors.order_ids){
                       errorMsg = errors.order_ids[0];
                   }
               } else if(xhr.responseJSON && xhr.responseJSON.message){
                   errorMsg = xhr.responseJSON.message;
               } else if(xhr.status === 400){
                   errorMsg = 'Bad request. Please check your selection.';
               }
               
               toastr.error(errorMsg);
               $submitBtn.prop('disabled', false).html(originalHtml);
           }
        });
        
        return false;
    });

    // order delete (bulk)
    $(document).on('click', '.order_delete', function(e){
        e.preventDefault();
        var url = $(this).attr('href');
        var order = $('input.checkbox:checked').map(function(){
          return $(this).val();
        });
        var order_ids = order.get();

        if(order_ids.length == 0){
            toastr.error('Please Select An Order First !');
            return;
        }

        $.ajax({
           type: 'GET',
           url: url,
           data: { order_ids: order_ids },
           success: function(res){
               if(res.status == 'success'){
                   toastr.success(res.message);
                   window.location.reload();
               } else {
                   toastr.error(res.message || 'Failed something wrong');
               }
           },
           error: function(){
               toastr.error('Something went wrong');
           }
        });
    });

    // multiple print
    $(document).on('click', '.multi_order_print', function(e){
        e.preventDefault();
        var url = $(this).attr('href');
        var order = $('input.checkbox:checked').map(function(){
          return $(this).val();
        });
        var order_ids = order.get();

        if(order_ids.length == 0){
            toastr.error('Please Select Atleast One Order!');
            return;
        }
        $.ajax({
           type: 'GET',
           url: url,
           data: { order_ids: order_ids },
           success: function(res){
               if(res.status == 'success'){
                   var myWindow = window.open("", "_blank");
                   myWindow.document.write(res.view);
               } else {
                   toastr.error(res.message || 'Failed something wrong');
               }
           },
           error: function(){
               toastr.error('Something went wrong');
           }
        });
    });

    // label print
    $(document).on('click', '.multi_label_print', function(e){
        e.preventDefault();
        var order_ids = $('input.checkbox:checked').map(function(){ return $(this).val(); }).get();
        if(order_ids.length == 0){ toastr.error('Please Select Atleast One Order!'); return; }
        $.ajax({
            type: 'GET',
            url: $(this).attr('href'),
            data: { order_ids: order_ids, type: 'label' },
            success: function(res){
                if(res.status == 'success'){
                    var w = window.open("","_blank");
                    w.document.write(res.view);
                } else { toastr.error(res.message || 'Failed'); }
            },
            error: function(){ toastr.error('Something went wrong'); }
        });
    });

    // multiple courier
    $(document).on('click', '.multi_order_courier', function(e){
        e.preventDefault();
        var url = $(this).attr('href');
        var order = $('input.checkbox:checked').map(function(){
          return $(this).val();
        });
        var order_ids = order.get();

        if(order_ids.length == 0){
            toastr.error('Please Select An Order First !');
            return;
        }
        
        // Show loading
        var $btn = $(this);
        var originalHtml = $btn.html();
        $btn.prop('disabled', true).html('<i class="fe-loader"></i> Sending...');

        $.ajax({
           type: 'GET',
           url: url,
           data: { order_ids: order_ids },
           success: function(res){
               console.log('Courier Response:', res); // Debug log
               
               if(res.status == 'success'){
                    if(res.success && res.success.length > 0){
                        toastr.success('Orders sent to courier successfully!');
                    }
                    if(res.failed && res.failed.length > 0){
                        res.failed.forEach(function(fail){
                            console.error('Failed order:', fail);
                            toastr.warning('Order ' + fail.order_id + ': ' + fail.message);
                        });
                    }
                    // Reload page to show courier information
                    setTimeout(function(){
                        window.location.reload();
                    }, 1000);
               } else {
                    toastr.error(res.message || 'Failed something wrong');
                    $btn.prop('disabled', false).html(originalHtml);
               }
           },
           error: function(xhr){
               console.error('Courier Error:', xhr);
               var errorMsg = 'Something went wrong';
               
               if(xhr.responseJSON){
                   // Check for failed orders with detailed messages
                   if(xhr.responseJSON.failed && xhr.responseJSON.failed.length > 0){
                       xhr.responseJSON.failed.forEach(function(fail){
                           var msg = fail.message || 'Failed to send order';
                           if(fail.status_code === 401){
                               msg = 'Account is not active! Please check your Steadfast account status and API credentials.';
                           } else if(fail.status_code === 403){
                               msg = 'Access forbidden! Please check your API credentials.';
                           } else if(fail.status_code === 404){
                               msg = 'API endpoint not found! Please check the API URL.';
                           }
                           toastr.error('Order ' + fail.order_id + ': ' + msg);
                       });
                   } else if(xhr.responseJSON.message){
                       errorMsg = xhr.responseJSON.message;
                   }
               } else if(xhr.status === 401){
                   errorMsg = 'Account is not active! Please check your Steadfast account status and API credentials.';
               } else if(xhr.status === 403){
                   errorMsg = 'Access forbidden! Please check your API credentials.';
               } else if(xhr.status === 404){
                   errorMsg = 'API endpoint not found! Please check the API URL.';
               }
               
               toastr.error(errorMsg);
               $btn.prop('disabled', false).html(originalHtml);
           }
        });
    });

    // Quick IP Block from order page
    $(document).on('click', '.block-ip-btn', function(e){
        e.preventDefault();
        var $btn = $(this);
        var ip = $btn.data('ip');
        var reason = $btn.data('reason') || 'ফেইক অর্ডার';
        
        if(!ip){
            toastr.error('IP address not found');
            return;
        }
        
        // Disable button and show loading
        $btn.prop('disabled', true);
        var originalHtml = $btn.html();
        $btn.html('<i class="fe-loader"></i> Blocking...');
        
        $.ajax({
            url: "{{ route('customers.ipblock.quick') }}",
            type: "POST",
            data: {
                _token: "{{ csrf_token() }}",
                ip: ip,
                reason: reason
            },
            success: function(res){
                if(res.status === 'success'){
                    toastr.success(res.message || 'IP blocked successfully');
                    // Change button to show blocked state (badge style)
                    $btn.replaceWith('<span class="badge bg-secondary" title="This IP is already blocked"><i class="fe-shield"></i> Blocked</span>');
                } else {
                    toastr.error(res.message || 'Failed to block IP');
                    $btn.prop('disabled', false);
                    $btn.html(originalHtml);
                }
            },
            error: function(xhr){
                var errorMsg = 'Failed to block IP';
                if(xhr.responseJSON && xhr.responseJSON.message){
                    errorMsg = xhr.responseJSON.message;
                }
                toastr.error(errorMsg);
                $btn.prop('disabled', false);
                $btn.html(originalHtml);
            }
        });
    });

    // Pathao Modal Open - Set selected order IDs
    $(document).on('click', '[data-bs-target="#pathao"]', function(e){
        var order = $('input.checkbox:checked').map(function(){
            return $(this).val();
        });
        var order_ids = order.get();
        
        if(order_ids.length == 0){
            toastr.error('Please Select Atleast One Order First!');
            e.preventDefault();
            return false;
        }
        
        $('#pathao_order_ids').val(order_ids.join(','));
    });

    // Pathao City Change - Load Zones
    $(document).on('change', '#pathaocity', function(){
        var cityId = $(this).val();
        if(!cityId){
            $('#pathaozone').html('<option value="">Select Zone...</option>');
            $('#pathaoarea').html('<option value="">Select Area...</option>');
            return;
        }
        
        $.ajax({
            url: "{{ route('pathaocity') }}",
            type: "GET",
            data: { city_id: cityId },
            success: function(res){
                var options = '<option value="">Select Zone...</option>';
                if(res && res.data && res.data.data && res.data.data.length > 0){
                    $.each(res.data.data, function(key, zone){
                        options += '<option value="' + zone.zone_id + '">' + zone.zone_name + '</option>';
                    });
                } else {
                    toastr.warning('No zones found for this city');
                }
                $('#pathaozone').html(options);
                $('#pathaoarea').html('<option value="">Select Area...</option>');
            },
            error: function(xhr){
                var errorMsg = 'Failed to load zones';
                if(xhr.responseJSON && xhr.responseJSON.message){
                    errorMsg = xhr.responseJSON.message;
                }
                toastr.error(errorMsg);
                $('#pathaozone').html('<option value="">Select Zone...</option>');
                $('#pathaoarea').html('<option value="">Select Area...</option>');
            }
        });
    });

    // Pathao Zone Change - Load Areas
    $(document).on('change', '#pathaozone', function(){
        var zoneId = $(this).val();
        if(!zoneId){
            $('#pathaoarea').html('<option value="">Select Area...</option>');
            return;
        }
        
        $.ajax({
            url: "{{ route('pathaozone') }}",
            type: "GET",
            data: { zone_id: zoneId },
            success: function(res){
                var options = '<option value="">Select Area...</option>';
                if(res && res.data && res.data.data && res.data.data.length > 0){
                    $.each(res.data.data, function(key, area){
                        options += '<option value="' + area.area_id + '">' + area.area_name + '</option>';
                    });
                } else {
                    toastr.warning('No areas found for this zone');
                }
                $('#pathaoarea').html(options);
            },
            error: function(xhr){
                var errorMsg = 'Failed to load areas';
                if(xhr.responseJSON && xhr.responseJSON.message){
                    errorMsg = xhr.responseJSON.message;
                }
                toastr.error(errorMsg);
                $('#pathaoarea').html('<option value="">Select Area...</option>');
            }
        });
    });

    // Pathao Form Submit
    $(document).on('submit', '#order_sendto_pathao', function(e){
        e.preventDefault();
        
        var orderIds = $('#pathao_order_ids').val();
        if(!orderIds){
            toastr.error('Please select orders first');
            return;
        }
        
        var formData = $(this).serialize();
        formData += '&order_ids=' + orderIds.split(',').map(function(id){ return id.trim(); }).join(',');
        
        // Validate required fields
        if(!$('#pathaostore').val() || !$('#pathaocity').val() || !$('#pathaozone').val() || !$('#pathaoarea').val()){
            toastr.error('Please fill all required fields (Store, City, Zone, Area)');
            return;
        }
        
        $.ajax({
            url: $(this).attr('action'),
            type: "POST",
            data: formData,
            success: function(res){
                if(res.status === 'success'){
                    var successCount = res.result.success ? res.result.success.length : 0;
                    var failedCount = res.result.failed ? res.result.failed.length : 0;
                    
                    if(successCount > 0){
                        toastr.success(successCount + ' order(s) sent to Pathao successfully');
                    }
                    if(failedCount > 0){
                        toastr.warning(failedCount + ' order(s) failed to send');
                    }
                    
                    $('#pathao').modal('hide');
                    setTimeout(function(){
                        window.location.reload();
                    }, 1500);
                } else {
                    toastr.error(res.message || 'Failed to send orders');
                }
            },
            error: function(xhr){
                var errorMsg = 'Failed to send orders';
                if(xhr.responseJSON && xhr.responseJSON.message){
                    errorMsg = xhr.responseJSON.message;
                }
                toastr.error(errorMsg);
            }
        });
    });

});
</script>
@endsection
