{{-- resources/views/party/customers/index.blade.php --}}
@extends('layouts.app')
@section('title','Customer List')

@push('styles')
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.dataTables.min.css">
<style>
  :root{
    --border:#e5e7eb;
    --muted:#6b7280;
    --ink:#111827;
    --ink-2:#334155;
    --btn:#1d4ed8;
    --btn-border:#1e40af;
    --bg:#ffffff;
    --bg-2:#f8fafc;
    --chip:#f3f6fa;
  }

  /* ===== Page title row ===== */
  .page-bar{
    display:flex;align-items:center;justify-content:space-between;
    gap:12px;margin-bottom:12px
  }
  .page-title{display:flex;gap:8px;align-items:center;font-size:18px;font-weight:700;color:var(--ink)}
  .page-actions{display:flex;gap:8px}
  .btn-head{
    display:inline-flex;gap:8px;align-items:center;
    padding:8px 12px;border-radius:8px;border:1px solid var(--border);
    background:#f3f6fa;color:#0f172a;font-weight:700;text-decoration:none
  }

  /* ===== Filter row ===== */
  .filters{
    display:grid;grid-template-columns:220px 1fr 260px 200px 200px 120px 44px 1fr;
    gap:8px;margin-bottom:8px;align-items:center
  }
  .filters .ctl,.filters select{
    height:36px;border:1px solid var(--border);border-radius:8px;padding:6px 10px;font-size:13px
  }
  .btn-blue{
    height:36px;border-radius:8px;background:var(--btn);border:1px solid var(--btn-border);
    color:#fff;font-weight:700;padding:0 12px
  }
  .btn-ghost{
    height:36px;border-radius:8px;border:1px solid var(--border);
    background:#fff;color:var(--ink);font-weight:700;padding:0 10px
  }

  /* ===== Top toolbar: Left = length, Center = buttons, Right = search ===== */
  .export-bar{
    display:grid;grid-template-columns:1fr auto 1fr;align-items:center;
    gap:12px;padding:8px;border:1px solid var(--border);border-radius:10px;background:var(--bg);margin-bottom:8px
  }
  .export-bar .eb-left{justify-self:start}
  .export-bar .eb-center{justify-self:center}
  .export-bar .eb-right{justify-self:end}

  .export-bar .dataTables_length label,
  .export-bar .dataTables_filter label{
    display:flex;align-items:center;gap:8px;margin:0;color:var(--ink-2);font-weight:700;font-size:12.5px
  }
  .export-bar .dataTables_length select,
  .export-bar .dataTables_filter input[type="search"]{
    height:32px;border:1px solid var(--border);border-radius:8px;padding:6px 10px;font-size:12.5px;outline:none
  }
  .export-bar .dataTables_filter input[type="search"]{min-width:220px}

  /* Buttons look */
  .dt-buttons .dt-button, button.dt-button, a.dt-button{
    background:var(--bg-2) !important;border:1px solid #dbe3f3 !important;border-radius:8px !important;
    padding:6px 10px !important;font-weight:700 !important;color:var(--ink) !important;box-shadow:none !important
  }

  /* ===== Table look ===== */
  .card-like{border:1px solid var(--border);border-radius:10px;background:#fff;overflow:hidden}
  .dataTables_wrapper .dataTables_scroll{border-top:1px solid var(--border)}
  table.dataTable thead th{
    background:var(--chip) !important;color:var(--ink-2) !important;
    font-weight:700 !important;font-size:12.5px !important;
    border-bottom:1px solid var(--border) !important;white-space:nowrap
  }
  table.dataTable tbody td{white-space:nowrap;font-size:12.5px}
  table.dataTable.stripe tbody tr:nth-child(odd){background:#fff}
  table.dataTable.stripe tbody tr:nth-child(even){background:#fbfcff}

  /* DataTables নিজে width হ্যান্ডেল করবে */
  #customersTable{width:100%}

  /* Info/Pagination row */
  .meta-bar{
    display:flex;align-items:center;justify-content:space-between;gap:10px;
    padding:8px;border:1px solid var(--border);border-top:0;background:#fff;border-radius:0 0 10px 10px
  }

  /* action icons */
  .btn-ico{width:26px;height:26px;border-radius:6px;border:0;color:#fff;display:inline-flex;align-items:center;justify-content:center}
  .btn-ico.info{background:#3b82f6}.btn-ico.edit{background:#22c55e}.btn-ico.del{background:#ef4444}

  /* ✅ numeric columns right align (HTML view) */
  table.dataTable thead th.dt-head-right{ text-align:right; }
  table.dataTable tbody td.dt-body-right{ text-align:right; }
</style>
@endpush

@section('content')
@php
  $csvList   = collect(['party.customers.csv','customers.csv'])->first(fn($n)=>Route::has($n));
  $csvUpload = collect(['party.customers.csv.upload','customers.csv.upload'])->first(fn($n)=>Route::has($n));
  $addRoute  = collect(['party.customers.create','customers.create'])->first(fn($n)=>Route::has($n));
  $editRoute = collect(['party.customers.edit','customers.edit'])->first(fn($n)=>Route::has($n));
  $delRoute  = collect(['party.customers.destroy','customers.destroy'])->first(fn($n)=>Route::has($n));
  $customers = $customers ?? collect();
@endphp

{{-- Top bar --}}
<div class="page-bar">
  <div class="page-title"><i class="fa-solid fa-list"></i> Customer List</div>
  <div class="page-actions">
    <a class="btn-head" href="{{ $csvList ? route($csvList) : '#' }}"><i class="fa-solid fa-table-list"></i> CSV List</a>
    <a class="btn-head" href="{{ $csvUpload ? route($csvUpload) : '#' }}"><i class="fa-solid fa-upload"></i> Upload CSV</a>
    <a class="btn-head" href="{{ $addRoute ? route($addRoute) : '#' }}"><i class="fa-solid fa-user-plus"></i> Add Customer</a>
  </div>
</div>

{{-- Filters --}}
<form method="GET" action="{{ url()->current() }}" class="filters">
  <select class="ctl" name="customer_id">
    <option value="">Customer</option>
    @foreach($customers as $c) @if(is_object($c))
      <option value="{{ $c->id }}" {{ request('customer_id')==$c->id?'selected':'' }}>{{ $c->name }}</option>
    @endif @endforeach
  </select>

  <input class="ctl" type="text" name="company" value="{{ request('company') }}" placeholder="Company Name">
  <input class="ctl" type="text" name="phone"   value="{{ request('phone')   }}" placeholder="Search by phone">

  <select class="ctl" name="executive_id">
    <option value="">Executive</option>
    @foreach(($executives ?? []) as $e)
      <option value="{{ is_object($e)?$e->id:$e['id'] }}" {{ request('executive_id')==(is_object($e)?$e->id:$e['id'])?'selected':'' }}>
        {{ is_object($e)?$e->name:$e['name'] }}
      </option>
    @endforeach
  </select>

  <select class="ctl" name="area_id">
    <option value="">Area</option>
    @foreach(($areas ?? []) as $a)
      <option value="{{ is_object($a)?$a->id:$a['id'] }}" {{ request('area_id')==(is_object($a)?$a->id:$a['id'])?'selected':'' }}>
        {{ is_object($a)?$a->name:$a['name'] }}
      </option>
    @endforeach
  </select>

  <button class="btn-blue" type="submit"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
  <a class="btn-ghost" href="{{ url()->current() }}" title="Refresh"><i class="fa-solid fa-rotate-right"></i></a>

  <div></div>
</form>

{{-- Export toolbar: Left (length) + Center (buttons) + Right (search) --}}
<div class="export-bar" id="exportBar">
  <div class="eb-left"  id="dtLen"></div>
  <div class="eb-center" id="dtButtons"></div>
  <div class="eb-right" id="dtFilter"></div>
</div>

<div class="card-like">
  <div class="dataTables_wrapper">
    <div class="dataTables_scroll">
      <div class="dataTables_scrollHead">
        <div class="dataTables_scrollHeadInner">
          <table class="display stripe" id="customersTable" style="width:100%">
            <thead>
            <tr>
              <th>SL.</th>
              <th>Customer ID</th>
              <th>Customer Name</th>
              <th>Company Name</th>
              <th>Email</th>
              <th>Address</th>
              <th>Phone Personal</th>
              <th>Executive</th>
              <th>Area</th>
              <th class="dt-head-right">Opening Balance</th>
              <th class="dt-head-right">Customer Due Limit</th>
              <th class="dt-head-right">Current Balance</th>
              <th>Remark</th>
              <th>Image</th>
              <th>Status</th>
              <th>Action</th>
            </tr>
            </thead>
            <tbody>
            @foreach($customers as $row)
              @php
                $sl        = method_exists($customers,'firstItem') ? $customers->firstItem() + $loop->index : $loop->iteration;
                $code      = $row->code ?? ($row->customerId ?? ('CO'.str_pad($row->id,4,'0',STR_PAD_LEFT)));
                $createdBy = $row->created_by_name ?? ($row->creator->name ?? 'System Admin');
                $updatedBy = $row->updated_by_name ?? ($row->updater->name ?? 'System Admin');
              @endphp
              <tr>
                <td>{{ $sl }}</td>
                <td>{{ $code }}</td>
                <td>{{ $row->name }}</td>
                <td>{{ $row->company_name }}</td>
                <td>{{ $row->email }}</td>
                <td>{{ $row->address }}</td>
                <td>{{ $row->personal_phone }}</td>
                <td>{{ $row->executive_name }}</td>
                <td>{{ $row->area_name ?? '' }}</td>
                <td class="dt-body-right">{{ number_format($row->opening_balance ?? 0,2) }}</td>
                <td class="dt-body-right">{{ number_format($row->due_limit ?? 0,2) }}</td>
                <td class="dt-body-right">{{ number_format($row->current_balance ?? 0,2) }}</td>
                <td>{{ $row->remarks }}</td>
                <td>{{ $row->image ? 'Available' : 'Not available' }}</td>
                <td>{{ ($row->status ?? 1) ? 'Active' : 'Inactive' }}</td>
                <td>
                  <div style="display:flex;gap:6px">
                    <button type="button" class="btn-ico info js-info"
                            data-created-by="{{ $createdBy }}"
                            data-created-at="{{ optional($row->created_at)->format('Y-m-d H:i:s') }}"
                            data-updated-by="{{ $updatedBy }}"
                            data-updated-at="{{ optional($row->updated_at)->format('Y-m-d H:i:s') }}">
                      <i class="fa-solid fa-circle-info"></i>
                    </button>
                    @if($editRoute)
                      <a class="btn-ico edit" href="{{ route($editRoute,$row->id) }}"><i class="fa-solid fa-pen-to-square"></i></a>
                    @endif
                    @if($delRoute)
                      <form action="{{ route($delRoute,$row->id) }}" method="POST"
                            onsubmit="return confirm('Delete this customer?')">
                        @csrf @method('DELETE')
                        <button class="btn-ico del"><i class="fa-solid fa-trash-can"></i></button>
                      </form>
                    @endif
                  </div>
                </td>
              </tr>
            @endforeach
            </tbody>
          </table>
        </div>
      </div>
      <div class="dataTables_scrollBody" style="position:relative; overflow:auto; width:100%;"></div>
    </div>
  </div>

  <div class="meta-bar">
    <div id="dtInfo"></div>
    <div id="dtPager"></div>
  </div>
</div>
@endsection

@push('scripts')
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.colVis.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>

<script>
  $(function(){
    const dt = $('#customersTable').DataTable({
      dom: 'Blfrtip',
      pageLength: 25,
      lengthMenu: [[25,50,100,200,500,1000,-1],[25,50,100,200,500,'1,000','All']],
      autoWidth: false,
      deferRender: true,
      scrollX: true,
      scrollCollapse: true,
      responsive: false,
      buttons: [
        { extend:'csvHtml5',   text:'Export to CSV' },
        { extend:'excelHtml5', text:'Export to Excel' },
        { extend:'print',      text:'Print', exportOptions:{columns:':visible'} },
        { extend:'colvis',     text:'Column visibility' },
        { extend:'pdfHtml5',   text:'Export to PDF',
          orientation:'landscape', pageSize:'A3',
          exportOptions:{columns:':visible'},
          title: '', // avoid default duplicate title
          customize: function(doc){
            // Title (single, centered)
            if (doc.content.length && doc.content[0].text !== undefined) {
              doc.content[0].text = 'Customer List';
              doc.content[0].alignment = 'center';
              doc.content[0].margin = [0, 0, 0, 8];
              doc.content[0].fontSize = 14;
              doc.content[0].bold = true;
            } else {
              doc.content.unshift({text:'Customer List', alignment:'center', margin:[0,0,0,8], fontSize:14, bold:true});
            }

            // Styles
            doc.styles.tableHeader = {fillColor:'#f3f6fa',color:'#1f2937',bold:true};
            doc.defaultStyle.fontSize = 9;

            // Find the exported table
            var tableIdx = doc.content.findIndex(function(it){ return it.table; });
            if (tableIdx === -1) return; // safety
            var tbl = doc.content[tableIdx].table;

            // Right-align specific numeric columns in PDF by header text (robust even if columns hidden/reordered)
            var headerRow = tbl.body[0] || [];
            var targetHeaders = ['Opening Balance','Customer Due Limit','Current Balance'];
            var rightCols = [];

            for (var i=0;i<headerRow.length;i++){
              var cell = headerRow[i];
              var txt = (cell && (cell.text || cell))+'';
              if (targetHeaders.indexOf(txt.trim()) !== -1){
                rightCols.push(i);
                // header cell align
                if (cell && typeof cell === 'object') cell.alignment = 'right';
              }
            }

            // apply to all rows
            tbl.body.forEach(function(row, rIdx){
              rightCols.forEach(function(ci){
                if (row[ci]){
                  if (typeof row[ci] === 'object'){
                    row[ci].alignment = 'right';
                  } else {
                    row[ci] = { text: row[ci], alignment: 'right' };
                  }
                }
              });
            });

            // Optional: light borders
            doc.content[tableIdx].layout = {
              hLineWidth:function(){return .4}, vLineWidth:function(){return .4},
              hLineColor:function(){return '#dde3ea'}, vLineColor:function(){return '#dde3ea'}
            };
          }
        }
      ],
      columnDefs:[
        {targets:[0,15], orderable:false},
        // HTML view right align (0-based indexes)
        {targets:[9,10,11], className:'dt-head-right dt-body-right'}
      ],
      initComplete: function(){
        const api   = this.api();
        const $wrap = $(api.table().container());

        // center buttons
        $('#dtButtons').empty().append($(api.buttons().container()));
        // left/right default controls
        $('#dtLen').empty().append($wrap.find('.dataTables_length'));
        $('#dtFilter').empty().append($wrap.find('.dataTables_filter'));
        // info/pager at bottom
        $('#dtInfo').empty().append($('#customersTable_info'));
        $('#dtPager').empty().append($('#customersTable_paginate'));

        const adjust = ()=> api.columns.adjust();
        adjust(); setTimeout(adjust,50); setTimeout(adjust,300);
        $(window).on('load', adjust);
        if (window.ResizeObserver) new ResizeObserver(adjust).observe(document.querySelector('.dataTables_scroll'));
      },
      drawCallback: function(){ this.api().columns.adjust(); }
    });

    let t;
    $(window).on('resize', function(){
      clearTimeout(t);
      t = setTimeout(()=> dt.columns.adjust(), 120);
    });

    /* Info popover (unchanged) */
    const pop=document.createElement('div');
    pop.style.cssText='position:fixed;display:none;min-width:280px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;box-shadow:0 12px 28px rgba(0,0,0,.15);z-index:99999;padding:10px';
    pop.innerHTML = `
      <div style="font-weight:700;margin-bottom:6px;color:#065f46">Log Information</div>
      <div style="display:flex;gap:8px;margin:4px 0"><b style="min-width:110px;color:#334155">Created By:</b> <span class="cr-by"></span></div>
      <div style="display:flex;gap:8px;margin:4px 0"><b style="min-width:110px;color:#334155">Created At :</b> <span class="cr-at"></span></div>
      <div style="display:flex;gap:8px;margin:4px 0"><b style="min-width:110px;color:#334155">Updated By:</b> <span class="up-by"></span></div>
      <div style="display:flex;gap:8px;margin:4px 0"><b style="min-width:110px;color:#334155">Updated At :</b> <span class="up-at"></span></div>`;
    document.body.appendChild(pop);
    function showPop(btn){
      const r=btn.getBoundingClientRect(); const gap=8;
      pop.style.display='block';
      let top=r.top-pop.offsetHeight-gap, left=r.right-pop.offsetWidth;
      if(top<8) top=r.bottom+gap;
      left=Math.max(8,Math.min(left,window.innerWidth-pop.offsetWidth-8));
      pop.style.top=top+'px'; pop.style.left=left+'px';
    }
    function hidePop(){pop.style.display='none'}
    $(document).on('mouseenter','.js-info',function(e){
      pop.querySelector('.cr-by').textContent=$(this).data('created-by')||'System Admin';
      pop.querySelector('.cr-at').textContent=$(this).data('created-at')||'';
      pop.querySelector('.up-by').textContent=$(this).data('updated-by')||'System Admin';
      pop.querySelector('.up-at').textContent=$(this).data('updated-at')||'';
      showPop(this);
    }).on('mouseleave','.js-info',function(e){ if(!pop.contains(e.relatedTarget)) hidePop(); });
    pop.addEventListener('mouseleave', hidePop);
    window.addEventListener('scroll', hidePop, {passive:true});
  });
</script>
@endpush


