<!doctype html>
<html lang="en">
  <head>
    {{template "backend_head" .}}
    <style>
      #employeeTable thead th {
        text-align: center !important;
        vertical-align: middle !important;
      }
      #groupDetailTable {
        font-size: 90%;
      }
      /* จัดการ sorting icon ของ DataTables ให้ไม่ดันข้อความ */
      table.dataTable thead th.dt-orderable-asc,
      table.dataTable thead th.dt-orderable-desc {
        padding-right: 30px !important;
      }
      .clickable-number {
        cursor: pointer;
        text-decoration: underline;
        color: #0d6efd;
      }
      .clickable-number:hover {
        color: #0a58ca;
        background-color: rgba(13, 110, 253, 0.1);
      }
      .text-orange {
        color: #fd7e14 !important;
      }
    </style>
  </head>
  <body class="layout-fixed sidebar-expand-lg sidebar-open bg-body-tertiary">
    <div class="app-wrapper">
      {{template "backend_header" .}}
      {{template "backend_menu" .}}
      <main class="app-main">
        <div class="app-content-header">
          <div class="container-fluid">
            <div class="row">
              <div class="col-sm-6"><h3 class="mb-0">รายงานผลการจัดเก็บสินเชื่อ 3</h3></div>
              <div class="col-sm-6">
                <ol class="breadcrumb float-sm-end">
                  <li class="breadcrumb-item"><a href="/ehongmd/main">หน้าหลัก</a></li>
                  <li class="breadcrumb-item active" aria-current="page">รายงานผลการจัดเก็บสินเชื่อ 3</li>
                </ol>
              </div>
            </div>
          </div>
        </div>
        <div class="app-content">
          <div class="container-fluid">
            
            <!-- ฟิลเตอร์เลือก ปี/เดือน -->
            <div class="card mb-3 shadow-sm">
              <div class="card-body py-2">
                <form method="GET" class="row g-2 align-items-center">
                  <div class="col-auto">
                    <label class="col-form-label fw-bold"><i class="bi bi-calendar3"></i> เลือกช่วงเวลา:</label>
                  </div>
                  <div class="col-auto">
                    <input type="number" name="year" id="filterYear" class="form-control form-control-sm" value="{{.SelectedYear}}" style="width: 100px;" placeholder="ระบุปี">
                  </div>
                  <div class="col-auto">
                    <select name="month" id="filterMonth" class="form-select form-select-sm">
                      {{$selMonth := .SelectedMonth}}
                      <option value="1" {{if eq $selMonth "1"}}selected{{end}}>เดือน 1</option>
                      <option value="2" {{if eq $selMonth "2"}}selected{{end}}>เดือน 2</option>
                      <option value="3" {{if eq $selMonth "3"}}selected{{end}}>เดือน 3</option>
                      <option value="4" {{if eq $selMonth "4"}}selected{{end}}>เดือน 4</option>
                      <option value="5" {{if eq $selMonth "5"}}selected{{end}}>เดือน 5</option>
                      <option value="6" {{if eq $selMonth "6"}}selected{{end}}>เดือน 6</option>
                      <option value="7" {{if eq $selMonth "7"}}selected{{end}}>เดือน 7</option>
                      <option value="8" {{if eq $selMonth "8"}}selected{{end}}>เดือน 8</option>
                      <option value="9" {{if eq $selMonth "9"}}selected{{end}}>เดือน 9</option>
                      <option value="10" {{if eq $selMonth "10"}}selected{{end}}>เดือน 10</option>
                      <option value="11" {{if eq $selMonth "11"}}selected{{end}}>เดือน 11</option>
                      <option value="12" {{if eq $selMonth "12"}}selected{{end}}>เดือน 12</option>
                    </select>
                  </div>
                  <div class="col-auto">
                    <button type="submit" class="btn btn-primary btn-sm px-3">
                      <i class="bi bi-search"></i> รายงาน
                    </button>
                  </div>
                  <div class="col text-end">
                    <span class="badge text-bg-info">ข้อมูล ณ ปี {{.SelectedYear}} เดือน {{.SelectedMonth}}</span>
                  </div>
                </form>
              </div>
            </div>

            <!-- ส่วนสรุปรายพนักงาน -->
            <div id="summarySection">
              <div class="card shadow-sm">
                  <div class="card-header border-bottom-0">
                      <h3 class="card-title">รายชื่อพนักงาน - แผนกสินเชื่อ 3 (Loan 3)</h3>
                      <div class="card-tools">
                          <span class="badge text-bg-primary">{{len .Employees}} คน</span>
                      </div>
                  </div>
                  <div class="card-body p-0">
                      <div class="table-responsive">
                          <table id="employeeTable" class="table table-bordered table-striped table-hover align-middle mb-0">
                              <thead class="align-middle">
                                  <!-- Row 1: Main Headers -->
                                  <tr class="table-dark text-center">
                                      <th rowspan="2" width="" style="text-align: center !important;">ลำดับ</th>
                                      <th rowspan="2" style="text-align: center !important;">ชื่อ-นามสกุล</th>
                                      <th rowspan="2" width="" style="text-align: center !important;">ชื่อเล่น</th>
                                      <th colspan="5" class="bg-primary bg-opacity-25 text-dark" style="text-align: center !important;">บัญชี (จำนวนราย)</th>
                                      <th colspan="5" class="bg-success bg-opacity-25 text-dark" style="text-align: center !important;">มูลค่า (บาท)</th>
                                      <th colspan="10" class="bg-info bg-opacity-25 text-dark" style="text-align: center !important;">ลูกค้าจ่ายค่างวด (ราย / %)</th>
                                      <th colspan="10" class="bg-warning bg-opacity-25 text-dark" style="text-align: center !important;">มูลค่าที่จ่าย (บาท / %)</th>
                                  </tr>

                                  <!-- Row 3: Sub Labels -->
                                  <tr class="text-center">
                                      <th class="bg-primary bg-opacity-25 text-dark small" style="text-align: center !important;">รวม</th>
                                      <th class="bg-primary bg-opacity-25 text-dark small text-danger" style="text-align: center !important;">1-3 งวด</th>
                                      <th class="bg-primary bg-opacity-25 text-dark small text-info" style="text-align: center !important;">NPL</th>
                                      <th class="bg-primary bg-opacity-25 text-dark small text-orange" style="text-align: center !important;">ค้าง 1-2</th>
                                      <th class="bg-primary bg-opacity-25 text-dark small text-secondary" style="text-align: center !important;">ค้าง >= 3</th>
  
                                      <th class="bg-success bg-opacity-25 text-dark small" style="text-align: center !important;">รวม</th>
                                      <th class="bg-success bg-opacity-25 text-dark small text-danger" style="text-align: center !important;">1-3 งวด</th>
                                      <th class="bg-success bg-opacity-25 text-dark small text-info" style="text-align: center !important;">NPL</th>
                                      <th class="bg-success bg-opacity-25 text-dark small text-orange" style="text-align: center !important;">ค้าง 1-2</th>
                                      <th class="bg-success bg-opacity-25 text-dark small text-secondary" style="text-align: center !important;">ค้าง >= 3</th>

                                      <!-- ลูกค้าจ่ายค่างวด (ราย / %) -->
                                      <th class="bg-info bg-opacity-25 text-dark small" style="text-align: center !important;">รวม</th>
                                      <th class="bg-primary bg-opacity-10 text-dark small" style="text-align: center !important;">%</th>
                                      <th class="bg-info bg-opacity-25 text-dark small text-danger" style="text-align: center !important;">1-3 งวด</th>
                                      <th class="bg-primary bg-opacity-10 text-dark small text-danger" style="text-align: center !important;">%</th>
                                      <th class="bg-info bg-opacity-25 text-dark small text-info" style="text-align: center !important;">NPL</th>
                                      <th class="bg-primary bg-opacity-10 text-dark small text-info" style="text-align: center !important;">%</th>
                                      <th class="bg-info bg-opacity-25 text-dark small text-orange" style="text-align: center !important;">ค้าง 1-2</th>
                                      <th class="bg-primary bg-opacity-10 text-dark small text-orange" style="text-align: center !important;">%</th>
                                      <th class="bg-info bg-opacity-25 text-dark small text-secondary" style="text-align: center !important;">ค้าง >= 3</th>
                                      <th class="bg-primary bg-opacity-10 text-dark small text-secondary" style="text-align: center !important;">%</th>

                                      <!-- มูลค่าที่จ่าย (บาท / %) -->
                                      <th class="bg-warning bg-opacity-25 text-dark small" style="text-align: center !important;">รวม</th>
                                      <th class="bg-success bg-opacity-10 text-dark small" style="text-align: center !important;">%</th>
                                      <th class="bg-warning bg-opacity-25 text-dark small text-danger" style="text-align: center !important;">1-3 งวด</th>
                                      <th class="bg-success bg-opacity-10 text-dark small text-danger" style="text-align: center !important;">%</th>
                                      <th class="bg-warning bg-opacity-25 text-dark small text-info" style="text-align: center !important;">NPL</th>
                                      <th class="bg-success bg-opacity-10 text-dark small text-info" style="text-align: center !important;">%</th>
                                      <th class="bg-warning bg-opacity-25 text-dark small text-orange" style="text-align: center !important;">ค้าง 1-2</th>
                                      <th class="bg-success bg-opacity-10 text-dark small text-orange" style="text-align: center !important;">%</th>
                                      <th class="bg-warning bg-opacity-25 text-dark small text-secondary" style="text-align: center !important;">ค้าง >= 3</th>
                                      <th class="bg-success bg-opacity-10 text-dark small text-secondary" style="text-align: center !important;">%</th>
                                  </tr>
                              </thead>
                              <tbody>
                                  {{range $index, $e := .Employees}}
                                  <tr>
                                      <td class="text-center">{{add $index 1}}.</td>
                                      <td><div class="fw-bold">{{.TNAME}} {{.FNAME}} {{.LNAME}}</div></td>
                                      <td class="text-center">{{.NICK}}</td>
                                      <td class="text-center fw-bold text-success clickable-number" onclick="showGroupDetails('TOTAL', 'ทั้งหมด', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .TotalCount 0}}{{.TotalCount}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-danger clickable-number" onclick="showGroupDetails('1', '1-3 งวด', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .G1Count 0}}{{.G1Count}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-info clickable-number" onclick="showGroupDetails('NPL', 'NPL', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .GNPLCount 0}}{{.GNPLCount}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-orange clickable-number" onclick="showGroupDetails('2', 'ค้าง 1-2', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .G2Count 0}}{{.G2Count}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-secondary clickable-number" onclick="showGroupDetails('3', 'ค้าง >= 3', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .G3Count 0}}{{.G3Count}}{{else}}0{{end}}</td>
                                      <td class="text-end text-success fw-bold format-price">{{if gt .TotalPrice 0.0}}{{.TotalPrice}}{{else}}0.00{{end}}</td>
                                      <td class="text-end text-danger fw-bold format-price">{{if gt .G1Price 0.0}}{{.G1Price}}{{else}}0.00{{end}}</td>
                                      <td class="text-end text-info fw-bold format-price">{{if gt .GNPLPrice 0.0}}{{.GNPLPrice}}{{else}}0.00{{end}}</td>
                                      <td class="text-end text-orange fw-bold format-price">{{if gt .G2Price 0.0}}{{.G2Price}}{{else}}0.00{{end}}</td>
                                      <td class="text-end text-secondary fw-bold format-price">{{if gt .G3Price 0.0}}{{.G3Price}}{{else}}0.00{{end}}</td>
                                      <!-- ลูกค้าจ่ายค่างวด (ราย / %) -->
                                      <td class="text-center fw-bold text-info clickable-number" onclick="showTranDetails('TOTAL', 'ทั้งหมด', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .TotalTranCount 0}}{{.TotalTranCount}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-primary bg-primary bg-opacity-10">{{percent .TotalTranCount .TotalCount}}%</td>
                                      <td class="text-center fw-bold text-danger clickable-number" onclick="showTranDetails('1', '1-3 งวด', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .G1TranCount 0}}{{.G1TranCount}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-danger bg-primary bg-opacity-10">{{percent .G1TranCount .G1Count}}%</td>
                                      <td class="text-center fw-bold text-info clickable-number" onclick="showTranDetails('NPL', 'NPL', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .GNPLTranCount 0}}{{.GNPLTranCount}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-info bg-primary bg-opacity-10">{{percent .GNPLTranCount .GNPLCount}}%</td>
                                      <td class="text-center fw-bold text-orange clickable-number" onclick="showTranDetails('2', 'ค้าง 1-2', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .G2TranCount 0}}{{.G2TranCount}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-orange bg-primary bg-opacity-10">{{percent .G2TranCount .G2Count}}%</td>
                                      <td class="text-center fw-bold text-secondary clickable-number" onclick="showTranDetails('3', 'ค้าง >= 3', '{{.US_NAME}}', '{{.TNAME}} {{.FNAME}} {{.LNAME}}')">{{if gt .G3TranCount 0}}{{.G3TranCount}}{{else}}0{{end}}</td>
                                      <td class="text-center fw-bold text-secondary bg-primary bg-opacity-10">{{percent .G3TranCount .G3Count}}%</td>
                                      <!-- มูลค่าที่จ่าย (บาท / %) -->
                                      <td class="text-end text-success fw-bold format-price-tran">{{if gt .TotalTranPrice 0.0}}{{.TotalTranPrice}}{{else}}0.00{{end}}</td>
                                      <td class="text-center fw-bold text-success bg-success bg-opacity-10">{{percent .TotalTranPrice .TotalPrice}}%</td>
                                      <td class="text-end text-danger fw-bold format-price-tran">{{if gt .G1TranPrice 0.0}}{{.G1TranPrice}}{{else}}0.00{{end}}</td>
                                      <td class="text-center fw-bold text-danger bg-success bg-opacity-10">{{percent .G1TranPrice .G1Price}}%</td>
                                      <td class="text-end text-info fw-bold format-price-tran">{{if gt .GNPLTranPrice 0.0}}{{.GNPLTranPrice}}{{else}}0.00{{end}}</td>
                                      <td class="text-center fw-bold text-info bg-success bg-opacity-10">{{percent .GNPLTranPrice .GNPLPrice}}%</td>
                                      <td class="text-end text-orange fw-bold format-price-tran">{{if gt .G2TranPrice 0.0}}{{.G2TranPrice}}{{else}}0.00{{end}}</td>
                                      <td class="text-center fw-bold text-orange bg-success bg-opacity-10">{{percent .G2TranPrice .G2Price}}%</td>
                                      <td class="text-end text-secondary fw-bold format-price-tran">{{if gt .G3TranPrice 0.0}}{{.G3TranPrice}}{{else}}0.00{{end}}</td>
                                      <td class="text-center fw-bold text-secondary bg-success bg-opacity-10">{{percent .G3TranPrice .G3Price}}%</td>
                                  </tr>
                                  {{else}}
                                  <tr>
                                      <td colspan="33" class="text-center py-4 text-muted">ไม่พบข้อมูลพนักงาน</td>
                                  </tr>
                                  {{end}}
                              </tbody>
                              <tfoot>
                                  <tr class="text-center fw-bold bg-light">
                                      <td colspan="3" class="text-end bg-dark text-light">รวมทั้งหมด</td>
                                      <td class="text-center bg-primary bg-opacity-10 text-success">0</td>
                                      <td class="text-center text-danger bg-primary bg-opacity-10">0</td>
                                      <td class="text-center text-info bg-primary bg-opacity-10">0</td>
                                      <td class="text-center text-orange bg-primary bg-opacity-10">0</td>
                                      <td class="text-center text-secondary bg-primary bg-opacity-10">0</td>
                                      <td class="text-end text-success fw-bold bg-success bg-opacity-10"></td>
                                      <td class="text-end text-danger fw-bold bg-success bg-opacity-10"></td>
                                      <td class="text-end text-info fw-bold bg-success bg-opacity-10"></td>
                                      <td class="text-end text-orange fw-bold bg-success bg-opacity-10"></td>
                                      <td class="text-end text-secondary fw-bold bg-success bg-opacity-10"></td>
                                      <!-- ลูกค้าจ่ายค่างวด (ราย / %) -->
                                      <td class="text-center text-info bg-info bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-primary bg-primary bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-center text-danger bg-info bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-danger bg-primary bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-center text-info bg-info bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-info bg-primary bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-center text-orange bg-info bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-orange bg-primary bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-center text-secondary bg-info bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-secondary bg-primary bg-opacity-10 fw-bold">0.00%</td>
                                      <!-- มูลค่าที่จ่าย (บาท / %) -->
                                      <td class="text-end text-success bg-warning bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-success bg-success bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-end text-danger bg-warning bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-danger bg-success bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-end text-info bg-warning bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-info bg-success bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-end text-orange bg-warning bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-orange bg-success bg-opacity-10 fw-bold">0.00%</td>
                                      <td class="text-end text-secondary bg-warning bg-opacity-10 fw-bold"></td>
                                      <td class="text-center text-secondary bg-success bg-opacity-10 fw-bold">0.00%</td>
                                  </tr>
                              </tfoot>
                          </table>
                      </div>
                  </div>
              </div>
            </div>
          </div>
        </div>
      </main>

      <!-- Modal สำหรับแสดงรายละเอียดข้อมูลกลุ่ม -->
      <div class="modal fade" id="groupDetailModal" tabindex="-1" aria-labelledby="groupDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl" style="max-width: 98%; margin-top: 1vh; margin-bottom: 1vh;">
          <div class="modal-content">
            <div class="modal-header bg-primary text-white">
              <h5 class="modal-title" id="groupDetailModalLabel">รายละเอียดข้อมูลสัญญา</h5>
              <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <div id="modalLoading" class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                  <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">กำลังโหลดข้อมูล...</p>
              </div>
              <div id="modalTableContainer" style="display: none;">
                <div class="table-responsive">
                  <table id="groupDetailTable" class="table table-bordered table-striped table-hover align-middle table-sm">
                    <thead class="table-dark text-center" style="white-space: nowrap">
                      <tr>
                        <th>ลำดับ</th>
                        <th>พนง.</th>
                        <th>กลุ่ม</th>
                        <th>เลขที่บัญชี</th>
                        <th>ชื่อลูกค้า</th>
                        <th>ค่างวด</th>
                        <th>ค้างชำระ</th>
                        <th>ค้างงวด</th>
                        <th>Non</th>
                        <th>ยอดรวม</th>
                        <th>งวดชำระ</th>
                        <th>ชำระแล้ว</th>
                        <th>หนี้คงเหลือ</th>
                        <th>ชำระไปแล้ว %</th>
                        <th>สถานะหนี้</th>
                        <th>#เขต</th>
                        <th>ชื่อเขต</th>
                        <th>จังหวัดเขต</th>
                        <th>ที่อยู่</th>
                        <th>ตำบล</th>
                        <th>อำเภอ</th>
                        <th>จังหวัด</th>
                        <th>อาชีพ</th>
                        <th>ยี่ห้อ</th>
                        <th>ตระกูลสินค้า</th>
                        <th>ประเภทหนี้</th>
                      </tr>
                    </thead>
                    <tbody id="groupDetailBody" style="white-space: nowrap">
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Modal ลูกค้าจ่ายค่างวด (tran detail) -->
      <div class="modal fade" id="tranDetailModal" tabindex="-1" aria-labelledby="tranDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl" style="max-width: 98%; margin-top: 1vh; margin-bottom: 1vh;">
          <div class="modal-content">
            <div class="modal-header bg-success text-white">
              <h5 class="modal-title" id="tranDetailModalLabel">รายละเอียดลูกค้าจ่ายค่างวด</h5>
              <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <div id="tranModalLoading" class="text-center py-5">
                <div class="spinner-border text-success" role="status">
                  <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">กำลังโหลดข้อมูล...</p>
              </div>
              <div id="tranModalTableContainer" style="display: none;">
                <div class="table-responsive">
                  <table id="tranDetailTable" class="table table-bordered table-striped table-hover align-middle table-sm">
                    <thead class="table-success text-center" style="white-space: nowrap">
                      <tr>
                        <th>ลำดับ</th>
                        <th>เลขที่บัญชี</th>
                        <th>ชื่อลูกค้า</th>
                        <th>กลุ่ม</th>
                        <th>พนักงาน</th>
                        <th>วันที่จ่าย</th>
                        <th>ยอดจ่าย</th>
                        <th>ค่างวด</th>
                        <th>ค้างชำระ</th>
                      </tr>
                    </thead>
                    <tbody id="tranDetailBody" style="white-space: nowrap">
                    </tbody>
                    <tfoot>
                      <tr class="fw-bold bg-light">
                        <td colspan="6" class="text-end bg-dark text-light">รวมทั้งหมด</td>
                        <td class="text-end text-success"></td>
                        <td class="text-end"></td>
                        <td class="text-end text-danger"></td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <footer class="app-footer">
        {{template "backend_footer" .}}
      </footer>
    </div>

    <!-- Modal สำหรับอัพโหลด CSV -->
    <div class="modal fade" id="uploadCsvModal" tabindex="-1" aria-labelledby="uploadCsvModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="uploadCsvModalLabel">นำเข้าข้อมูล excel .csv ลงฐานข้อมูล</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <form id="uploadCsvForm" enctype="multipart/form-data">
            <div class="modal-body">
              <div class="mb-3">
                <label for="csv_file" class="form-label">เลือกไฟล์ excel .csv (คอลัมน์: CT_NO, UPDATE_Y, UPDATE_M, L_TYPE)</label>
                <input class="form-control" type="file" id="csv_file" name="csv_file" accept=".csv" required>
              </div>
              <div id="uploadStatus"></div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ปิด</button>
              <button type="submit" class="btn btn-primary">บันทึกข้อมูลลงฐานข้อมูล</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    {{template "backend_js" .}}
    <script>
      $(document).ready(function() {
          $('#employeeTable').DataTable({
              "language": { "url": "https://cdn.datatables.net/plug-ins/1.10.24/i18n/Thai.json" },
              "layout": { "topStart": "buttons", "topEnd": "search" },
              "buttons": [
                  { "extend": "excelHtml5", "text": '<i class="bi bi-file-earmark-excel"></i> Export Excel', "className": "btn btn-success btn-sm mb-3", "title": "รายชื่อพนักงานแผนกสินเชื่อ 3" }
              ],
              "paging": false,
              "scrollY": "600px",
              "scrollX": true,
              "scrollCollapse": true,
              "info": false,
              "order": [[0, "asc"]],
              "footerCallback": function ( row, data, start, end, display ) {
                  var api = this.api();
                  var intVal = function ( i ) { 
                      return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0; 
                  };

                  // 1. Calculate all totals first
                  let totals = {};
                  for(let i=3; i<=32; i++) {
                      totals[i] = api.column( i ).data().reduce( function (a, b) {
                          let valA = typeof a === 'string' ? a.replace(/<[^>]*>?/gm, '') : a;
                          let valB = typeof b === 'string' ? b.replace(/<[^>]*>?/gm, '') : b;
                          return intVal(valA) + intVal(valB);
                      }, 0 );
                  }

                  // 2. Display totals and percentages
                  for(let i=3; i<=32; i++) {
                      let total = totals[i];
                      
                      // For percentage columns (14,16,18,20,22 and 24,26,28,30,32)
                      if (i >= 14 && i <= 32 && i % 2 === 0) {
                          let baseCol;
                          if (i <= 22) {
                              baseCol = 3 + (i - 14)/2; // Count base columns 3 to 7
                          } else {
                              baseCol = 8 + (i - 24)/2; // Price base columns 8 to 12
                          }
                          let targetCol = i - 1;
                          let baseTotal = totals[baseCol];
                          let targetTotal = totals[targetCol];
                          
                          let pct = baseTotal > 0 ? (targetTotal / baseTotal * 100).toFixed(2) : "0.00";
                          $( api.column( i ).footer() ).html( pct + '%' );
                          continue;
                      }

                      let displayHtml = total;
                      // Price columns: 8-12 (มูลค่า), and odd columns from 23-31 (มูลค่าที่จ่าย)
                      if ((i >= 8 && i <= 12) || (i >= 23 && i <= 31 && i % 2 !== 0)) { 
                          displayHtml = total.toLocaleString('en-US', {minimumFractionDigits: 2}); 
                      }
                      
                      if (i >= 3 && i <= 7) {
                          let type = ['TOTAL', '1', 'NPL', '2', '3'][i-3];
                          let title = ['ทั้งหมด', '1-3 งวด', 'NPL', 'ค้าง 1-2', 'ค้าง >= 3'][i-3];
                          displayHtml = `<span class="clickable-number" onclick="showGroupDetails('${type}', '${title}', 'ASSIGNED_ONLY', 'พนักงานทุกคน')">${displayHtml}</span>`;
                      }

                      // Tran count columns: odd columns from 13-21
                      if (i >= 13 && i <= 21 && i % 2 !== 0) {
                          let typeIndex = (i - 13) / 2;
                          let type = ['TOTAL', '1', 'NPL', '2', '3'][typeIndex];
                          let title = ['ทั้งหมด', '1-3 งวด', 'NPL', 'ค้าง 1-2', 'ค้าง >= 3'][typeIndex];
                          displayHtml = `<span class="clickable-number" onclick="showTranDetails('${type}', '${title}', 'ASSIGNED_ONLY', 'พนักงานทุกคน')">${displayHtml}</span>`;
                      }

                      $( api.column( i ).footer() ).html( displayHtml );
                  }
              }
          });

          // Format prices in table rows (มูลค่า)
          $('.format-price').each(function() {
              let val = parseFloat($(this).text());
              if(val > 0) {
                  $(this).text(val.toLocaleString('en-US', {minimumFractionDigits: 2}));
              } else {
                  $(this).text('0.00');
              }
          });
          // Format prices in table rows (มูลค่าที่มาจ่าย)
          $('.format-price-tran').each(function() {
              let val = parseFloat($(this).text());
              if(val > 0) {
                  $(this).text(val.toLocaleString('en-US', {minimumFractionDigits: 2}));
              } else {
                  $(this).text('0.00');
              }
          });
      });

      function showGroupDetails(type, title, employeeUsName = null, employeeName = null) {
          if (employeeUsName) {
              $('#groupDetailModalLabel').text('รายละเอียดข้อมูลของ ' + employeeName + ' : ' + title);
          } else {
              $('#groupDetailModalLabel').text('รายละเอียดข้อมูล (ว่าง): ' + title);
          }
          $('#modalLoading').show();
          $('#modalTableContainer').hide();

          $('#groupDetailModal').modal('show');

          const year = $('#filterYear').val();
          const month = $('#filterMonth').val();

          $.ajax({
              url: 'api/loan3/group_details',
              data: { year: year, month: month, type: type, usName: employeeUsName || '' },
              method: 'GET',
              success: function(data) {
                  let html = '';
                  if (data && data.length > 0) {
                      data.forEach(function(item, index) {
                          html += `<tr class="text-center">
                              <td>${index + 1}.</td>

                              <td class="text-start">${item.EMP_NAME ? `${item.EMP_NAME}` : '<span class="text-muted small">-</span>'}</td>
                              <td>${getGroupText(item.L_TYPE)}</td>
                              <td class="fw-bold text-primary" style="font-family:monospace;">${item.CT_NO}</td>
                              <td class="text-start">${item.PS_NAME}</td>
                              <td class="text-end">${formatNumber(item.DUE_AMNT)}</td>
                              <td class="text-end text-danger">${formatNumber(item.NOTPAY_AMNT)}</td>
                              <td class="text-danger fw-bold">${item.STNPY} -> ${item.NOTPAY_COUNT}</td>
                              <td class="text-danger fw-bold">${item.STNON} -> ${item.NON_COUNT}</td>
                              <td class="text-end">${formatNumber(item.PRICE)}</td>
                              <td>${item.PAYDUE_COUNT}</td>
                              <td class="text-end">${formatNumber(item.PAYAMNT)}</td>
                              <td class="text-end fw-bold">${formatNumber(item.BL_DUE_1)}</td>
                              <td class="text-primary fw-bold">${getPaidPercent(item.PRICE, item.PAYAMNT)}%</td>
                              <td class="text-start">
                                  <span class="text-muted small">${getXStatusText(item.XSTATUS)}</span> <span class="fw-bold text-primary">${getLockStatusText(item.LOCK_STATUS, item.BL_DUE_1)}</span>
                              </td>
                              <td>${item.ZONE_CODE}</td>
                              <td>เขต${item.DF_AMNAME}</td>
                              <td>${item.DF_PRNAME}</td>
                              <td class="text-start">${item.DF_ADDRHOME}</td>
                              <td>${item.DF_TUNAME}</td>
                              <td>${item.DF_AMNAME}</td>
                              <td>${item.DF_PRNAME}</td>
                              <td>${item.OCCUPATION_NAME}</td>
                              <td>${item.BRAND_NAME}</td>
                              <td>${item.FML_NAME}</td>
                              <td></td>
                          </tr>`;
                      });
                  } else {
                      html = '<tr><td colspan="25" class="text-center py-3">ไม่พบข้อมูล</td></tr>';
                  }
                  
                  if ($.fn.DataTable.isDataTable('#groupDetailTable')) {
                      $('#groupDetailTable').DataTable().destroy();
                  }

                  $('#groupDetailBody').html(html);
                  $('#modalLoading').hide();
                  $('#modalTableContainer').show();

                  $('#groupDetailTable').DataTable({
                      "language": { "url": "https://cdn.datatables.net/plug-ins/1.10.24/i18n/Thai.json" },
                      "layout": {
                          "topStart": "buttons",
                          "topEnd": "search"
                      },
                      "buttons": [
                          {
                              "extend": "excelHtml5",
                              "text": '<i class="bi bi-file-earmark-excel"></i> Export Excel',
                              "className": "btn btn-success btn-sm mb-2",
                              "title": "รายละเอียดสินเชื่อ",
                              "exportOptions": {
                                  "columns": ":visible"
                              }
                          }
                      ],
                      "order": [[0, "asc"]],
                      "paging": false,
                      "scrollY": "85vh",
                      "scrollX": true,
                      "scrollCollapse": true,
                      "info": false
                  });
              },
              error: function() {
                  $('#groupDetailBody').html('<tr><td colspan="25" class="text-center text-danger py-3">เกิดข้อผิดพลาดในการโหลดข้อมูล</td></tr>');
                  $('#modalLoading').hide();
                  $('#modalTableContainer').show();
              }
          });
      }

      function getGroupText(t) {
          t = (t || '').trim();
          switch(t) {
              case '1': return '1-3 งวด';
              case '2': return 'ค้าง 1-2';
              case '3': return 'ค้าง >= 3';
              case 'NPL': return 'NPL';
              default: return t;
          }
      }

      function showTranDetails(type, title, employeeUsName, employeeName) {
          const displayName = employeeName || 'พนักงานทุกคน';
          $('#tranDetailModalLabel').text('ลูกค้าจ่ายค่างวด — ' + displayName + ' : ' + title);
          $('#tranModalLoading').show();
          $('#tranModalTableContainer').hide();
          $('#tranDetailModal').modal('show');

          const year = $('#filterYear').val();
          const month = $('#filterMonth').val();

          $.ajax({
              url: 'api/loan3/tran_details',
              data: {
                  year: year,
                  month: month,
                  type: (type === 'TOTAL' ? '' : type),
                  usName: employeeUsName || ''
              },
              method: 'GET',
              success: function(data) {
                  let html = '';
                  if (data && data.length > 0) {
                      const grouped = {};
                      data.forEach(function(item) {
                          if (!grouped[item.CT_NO]) {
                              grouped[item.CT_NO] = {
                                  ...item,
                                  TOTAL_PAY_AMNT: item.PAY_AMNT,
                                  PAY_COUNT: 1,
                                  PAY_DETAILS: [{ date: item.TR_DATE, amnt: item.PAY_AMNT }]
                              };
                          } else {
                              grouped[item.CT_NO].TOTAL_PAY_AMNT += item.PAY_AMNT;
                              grouped[item.CT_NO].PAY_COUNT += 1;
                              grouped[item.CT_NO].PAY_DETAILS.push({ date: item.TR_DATE, amnt: item.PAY_AMNT });
                          }
                      });

                      const displayData = Object.values(grouped);
                      displayData.forEach(function(item, index) {
                          let dateHtml = `${item.TR_DATE} (${formatNumber(item.PAY_AMNT)})`;
                          if (item.PAY_COUNT > 1) {
                              let detailText = item.PAY_DETAILS.map(d => `${d.date} = ${formatNumber(d.amnt)}`).join(', ');
                              dateHtml = `<span class="fw-bold text-info"><i class="bi bi-repeat"></i> ${item.PAY_COUNT} ครั้ง</span> 
                                          <span class="small text-muted" style="font-size: 0.8rem;">(${detailText})</span>`;
                          }

                          html += `<tr class="text-center">
                              <td>${index + 1}.</td>
                              <td class="fw-bold text-primary" style="font-family:monospace;">${item.CT_NO}</td>
                              <td class="text-start">${item.PS_NAME}</td>
                              <td>${getGroupText(item.L_TYPE)}</td>
                              <td class="text-start">${item.EMP_NAME || '<span class="text-muted">-</span>'}</td>
                              <td class="text-center">${dateHtml}</td>
                              <td class="text-end fw-bold text-success">${formatNumber(item.TOTAL_PAY_AMNT)}</td>
                              <td class="text-end">${formatNumber(item.DUE_AMNT)}</td>
                              <td class="text-end text-danger">${formatNumber(item.NOTPAY_AMNT)}</td>
                          </tr>`;
                      });
                  } else {
                      html = '<tr><td colspan="9" class="text-center py-3 text-muted">ไม่พบข้อมูลลูกค้าที่มาจ่ายในช่วงเวลานี้</td></tr>';
                  }

                  if ($.fn.DataTable.isDataTable('#tranDetailTable')) {
                      $('#tranDetailTable').DataTable().destroy();
                  }
                  $('#tranDetailBody').html(html);
                  $('#tranModalLoading').hide();
                  $('#tranModalTableContainer').show();

                  $('#tranDetailTable').DataTable({
                      "language": { "url": "https://cdn.datatables.net/plug-ins/1.10.24/i18n/Thai.json" },
                      "layout": {
                          "topStart": "buttons",
                          "topEnd": "search"
                      },
                      "buttons": [{
                          "extend": "excelHtml5",
                          "text": '<i class="bi bi-file-earmark-excel"></i> Export Excel',
                          "className": "btn btn-success btn-sm mb-2",
                          "title": "รายละเอียดลูกค้าจ่ายค่างวด"
                      }],
                      "order": [[0, "asc"]],
                      "paging": false,
                      "scrollY": "75vh",
                      "scrollX": true,
                      "scrollCollapse": true,
                      "info": false,
                      "footerCallback": function ( row, data, start, end, display ) {
                          var api = this.api();
                          var intVal = function ( i ) {
                              return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0;
                          };
                          [6, 7, 8].forEach(function(i) {
                              var total = api.column( i, { search: 'applied' } ).data().reduce( function (a, b) {
                                  let valA = typeof a === 'string' ? a.replace(/<[^>]*>?/gm, '') : a;
                                  let valB = typeof b === 'string' ? b.replace(/<[^>]*>?/gm, '') : b;
                                  return intVal(valA) + intVal(valB);
                              }, 0 );
                              $( api.column( i ).footer() ).html( total.toLocaleString('en-US', {minimumFractionDigits: 2}) );
                          });
                      }
                  });
              },
              error: function() {
                  $('#tranDetailBody').html('<tr><td colspan="9" class="text-center text-danger py-3">เกิดข้อผิดพลาดในการโหลดข้อมูล</td></tr>');
                  $('#tranModalLoading').hide();
                  $('#tranModalTableContainer').show();
              }
          });
      }

      function getPaidPercent(price, payamnt) {
          if (!price || price <= 0) return "0.00";
          return ((payamnt / price) * 100).toFixed(2);
      }

      function getXStatusText(s) {
          s = (s || '').trim();
          switch (s) {
              case "0": return "ปกติ";
              case "1": return "สินค้าขายต่อ";
              case "2": return "สินค้าหาย";
              case "3": return "สินค้าจำนำ";
              case "4": return "สินค้าอยู่ต่างจังหวัด";
              case "5": return "สินค้าเกิดอุบัติเหตุ";
              case "6": return "สินค้าอยู่ สน.";
              case "7": return "สินค้าไม่มีข้อมูล(พบซื้อหรือค้ำแต่ไม่พบสินค้า)";
              case "8": return "แก๊งค์";
              case "9": return "สินค้าไม่มีข้อมูล(ไม่พบซื้อและค้ำและสินค้า)";
              default: return s;
          }
      }

      function getLockStatusText(s, blDue1) {
          s = (s || '').trim();
          if (s === "N" || s === "") return "ปกติ";
          else if (s === "E") return "ผิดปกติ (มีปัญหา)";
          else if (s === "W") return "รับคืนรอไถ่ถอน";
          else if (s === "R") return "รับคืน ปิดสัญญา";
          else if (s === "O") return "รับสินค้าตีเทิร์น ปิดสัญญา";
          else if (s === "C") return "รับคืนสินค้า ปิดสัญญา";
          else if (s === "L") return "หนี้สูญ ปิดสัญญา";
          else if (s === "X") return "สัญญาถูกยกเลิกแล้ว";
          else if (s === "D" || s === "Y") return "ติดต่อสินเชื่อ";
          else if (s === "F") {
              if (blDue1 <= 0) return "หมดงวด (B/L)";
              else return "หมดงวด(ค้างค่าเบี้ยปรับและค่าอื่นฯ)";
          }
          return s;
      }

      function formatNumber(num) {
          return parseFloat(num).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      }

      $(document).ready(function() {
          $('#uploadCsvForm').on('submit', function(e) {
              e.preventDefault();
              var formData = new FormData(this);
              $('#uploadStatus').html('<div class="text-info"><div class="spinner-border spinner-border-sm" role="status"></div> กำลังบันทึกข้อมูล...</div>');
              $.ajax({
                  url: '/ehongmd/main_1/upload_csv',
                  type: 'POST',
                  data: formData,
                  processData: false,
                  contentType: false,
                  success: function(response) {
                      if (response === 'Success') {
                          $('#uploadStatus').html('<div class="text-success"><i class="bi bi-check-circle-fill"></i> บันทึกข้อมูลลงฐานข้อมูล CONFIG.dbo.LOAN3_CSV เรียบร้อยแล้ว!</div>');
                          setTimeout(function() {
                              $('#uploadCsvModal').modal('hide');
                              $('#uploadCsvForm')[0].reset();
                              $('#uploadStatus').html('');
                              location.reload();
                          }, 2500);
                      } else {
                          $('#uploadStatus').html('<div class="text-danger">เกิดข้อผิดพลาด: ' + response + '</div>');
                      }
                  },
                  error: function(xhr) {
                      $('#uploadStatus').html('<div class="text-danger">เกิดข้อผิดพลาด: ' + xhr.responseText + '</div>');
                  }
              });
          });
      });
    </script>
  </body>
</html>
