<?php
$CURRENT_SECTION = 'order';
include '../inc/header.php';
?>
<div class="container" style="max-width:1280px; margin-top:18px;">

    <!-- 상단 툴바 -->
    <div class="sam-toolbar mb-2">
        <div class="sam-title">수주 리스트</div>
        <div class="sam-actions">
            <select class="form-select form-select-sm" id="selStatus">
                <option value="">상태(전체)</option>
                <option>접수</option><option>견적</option><option>발주</option>
                <option>생산</option><option>출고</option>
            </select>
            <select class="form-select form-select-sm" id="selType">
                <option value="">구분(전체)</option>
                <option>스크린</option><option>철재</option>
            </select>
            <input type="date" class="form-control form-control-sm" id="fromDate" />
            <span class="text-muted">~</span>
            <input type="date" class="form-control form-control-sm" id="toDate" />
            <input type="text" class="form-control form-control-sm" id="keyword" placeholder="발주처/현장/모델 등" />
            <button class="btn btn-sm btn-outline-secondary" id="btnSearch">검색</button>
            <button class="btn btn-sm btn-primary" id="btnNew">+ 신규 생산</button>
        </div>
    </div>

    <div class="card">
        <div class="card-body p-2">
            <div class="table-responsive">
                <table class="table table-hover table-sam m-0" id="estTable">
                    <thead>
                    <tr>
                        <th style="width:60px;">NO</th>
                        <th style="width:110px;">접수일</th>
                        <th style="width:80px;">상태</th>
                        <th style="width:160px;">생산로트</th>
                        <th style="width:80px;">구분</th>
                        <th style="width:140px;">발주처</th>
                        <th style="width:110px;">제품모델명</th>
                        <th>현장명</th>
                        <th style="width:80px;">수량</th>
                        <th style="width:110px;">출고일</th>
                        <th style="width:90px;">운송현황</th>
                    </tr>
                    </thead>
                    <tbody id="estTbody"><!-- JS 렌더 --></tbody>
                </table>
            </div>

            <!-- 페이지네이션 -->
            <div class="d-flex justify-content-between align-items-center mt-2">
                <div class="text-muted small" id="resultInfo"></div>
                <nav aria-label="pagination">
                    <ul class="pagination pagination-sm mb-0" id="pager"><!-- JS --></ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<style>
    /* 상태 배지 */
    .q-badge{display:inline-block; padding:.25rem .45rem; border-radius:.5rem; font-weight:600;}
    .q-접수{background:#e8f0ff; color:#204a9a;}
    .q-견적{background:#fff1bf; color:#6a5300;}
    .q-대기{background:#d7f5e6; color:#0b6b3e;}
    /* 현장명 말줄임 */
    #estTable td:nth-child(8){max-width:320px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;}
</style>

<script>
    $(function(){
        // ---- 샘플 데이터 ----
        const rows = [
            {no:1,  recv:'2025-07-15', status:'대기', lot:'KD-PR-250715-11', type:'철재',  buyer:'SK텔레콤',  model:'KWE01', site:'판교센터',       qty:3, ship:'2025-07-25', shipstat:'택배'},
            {no:2,  recv:'2025-07-14', status:'견적', lot:'KD-PR-250714-12', type:'스크린', buyer:'현대건설',  model:'KQTS01', site:'서울현장',       qty:2, ship:'2025-07-28', shipstat:'화물차'},
            {no:3,  recv:'2025-07-13', status:'견적', lot:'KD-PR-250713-13', type:'철재',  buyer:'KT',       model:'KTE01',  site:'강남센터',       qty:5, ship:'2025-07-30', shipstat:'트럭'},
            {no:4,  recv:'2025-07-12', status:'견적', lot:'KD-PR-250712-14', type:'스크린', buyer:'LG전자',   model:'KDSS01', site:'평택공장',       qty:1, ship:'2025-08-01', shipstat:'택배'},
            {no:5,  recv:'2025-07-11', status:'대기', lot:'KD-PR-250711-15', type:'철재',  buyer:'삼성SDI',  model:'KSS01',  site:'천안사업장',     qty:5, ship:'2025-08-01', shipstat:'화물차'},
            {no:6,  recv:'2025-07-10', status:'대기', lot:'KD-PR-250710-01', type:'스크린', buyer:'롯데쇼핑',  model:'KSS01',  site:'서울물류센터',   qty:3, ship:'2025-08-02', shipstat:'택배'},
            {no:7,  recv:'2025-07-09', status:'대기', lot:'KD-PR-250709-02', type:'스크린', buyer:'두산중공업',model:'KSS02',  site:'울산공장',       qty:1, ship:'2025-08-05', shipstat:'트럭'},
            {no:8,  recv:'2025-07-08', status:'견적', lot:'KD-PR-250708-03', type:'철재',  buyer:'CJ대한통운',model:'KSS02',  site:'인천사업장',     qty:3, ship:'2025-08-02', shipstat:'화물차'},
            {no:9,  recv:'2025-07-07', status:'대기', lot:'KD-PR-250707-04', type:'스크린', buyer:'포스코',    model:'KSS01',  site:'포항공장',       qty:2, ship:'2025-07-28', shipstat:'택배'},
            {no:10, recv:'2025-07-06', status:'견적', lot:'KD-PR-250706-05', type:'철재',  buyer:'현대자동차',model:'KSS02',  site:'울산공장',       qty:8, ship:'2025-08-03', shipstat:'화물차'},
            {no:6,  recv:'2025-07-10', status:'대기', lot:'KD-PR-250710-01', type:'스크린', buyer:'롯데쇼핑',  model:'KSS01',  site:'서울물류센터',   qty:3, ship:'2025-08-02', shipstat:'택배'},
            {no:7,  recv:'2025-07-09', status:'대기', lot:'KD-PR-250709-02', type:'스크린', buyer:'두산중공업',model:'KSS02',  site:'울산공장',       qty:1, ship:'2025-08-05', shipstat:'트럭'},
            {no:8,  recv:'2025-07-08', status:'견적', lot:'KD-PR-250708-03', type:'철재',  buyer:'CJ대한통운',model:'KSS02',  site:'인천사업장',     qty:3, ship:'2025-08-02', shipstat:'화물차'},
            {no:9,  recv:'2025-07-07', status:'견적', lot:'KD-PR-250707-04', type:'스크린', buyer:'포스코',    model:'KSS01',  site:'포항공장',       qty:2, ship:'2025-07-28', shipstat:'택배'},
            {no:10, recv:'2025-07-06', status:'견적', lot:'KD-PR-250706-05', type:'철재',  buyer:'현대자동차',model:'KSS02',  site:'울산공장',       qty:8, ship:'2025-08-03', shipstat:'화물차'},
        ];

        // ---- 상태 배지 ----
        const badge = s => `<span class="q-badge q-${s}">${s}</span>`;

        // ---- 페이징 ----
        const pageSize = 10;
        let curPage = 1, filtered = [...rows];

        function render(){
            const start = (curPage-1)*pageSize;
            const slice = filtered.slice(start, start+pageSize);
            $('#estTbody').html(slice.map(r=>`
      <tr data-no="${r.no}" class="row-open">
        <td>${r.no}</td>
        <td>${r.recv}</td>
        <td>${badge(r.status)}</td>
        <td>${r.lot}</td>
        <td>${r.type}</td>
        <td>${r.buyer}</td>
        <td>${r.model}</td>
        <td title="${r.site}">${r.site}</td>
        <td>${r.qty}</td>
        <td>${r.ship}</td>
        <td>${r.shipstat}</td>
      </tr>
    `).join(''));

            const total = Math.max(1, Math.ceil(filtered.length/pageSize));
            let p = `
      <li class="page-item ${curPage===1?'disabled':''}"><a class="page-link" href="#" data-p="prev">«</a></li>`;
            for(let i=1;i<=total;i++){
                p += `<li class="page-item ${i===curPage?'active':''}"><a class="page-link" href="#" data-p="${i}">${i}</a></li>`;
            }
            p += `<li class="page-item ${curPage===total?'disabled':''}"><a class="page-link" href="#" data-p="next">»</a></li>`;
            $('#pager').html(p);
            $('#resultInfo').text(`총 ${filtered.length.toLocaleString()}건`);
        }

        // 검색
        $('#btnSearch').on('click', function(){
            const st = $('#selStatus').val();
            const tp = $('#selType').val();
            const kw = ($('#keyword').val()||'').toLowerCase();
            const from = $('#fromDate').val();
            const to   = $('#toDate').val();
            filtered = rows.filter(r=>{
                const okSt = !st || r.status===st;
                const okTp = !tp || r.type===tp;
                const okKw = !kw || [r.buyer,r.site,r.model,r.lot].some(v=>String(v).toLowerCase().includes(kw));
                const okDt = (!from || r.recv>=from) && (!to || r.recv<=to);
                return okSt && okTp && okKw && okDt;
            });
            curPage=1; render();
        });

        // 페이징
        $(document).on('click', '#pager .page-link', function(e){
            e.preventDefault();
            const v = $(this).data('p');
            const total = Math.max(1, Math.ceil(filtered.length/pageSize));
            if(v==='prev'){ if(curPage>1) curPage--; }
            else if(v==='next'){ if(curPage<total) curPage++; }
            else curPage = parseInt(v,10);
            render();
        });

        // 행 클릭 (상세로 이동/모달 호출 등)
        $(document).on('click', 'tr.row-open', function(){
            const no = $(this).data('no');
            // 예시: 상세 페이지로 이동
            // location.href = '/tenant/estimate/estimate_view.php?no='+no;
            alert('견적 상세 열기 (NO: '+no+')');
        });

        // 버튼
        $('#btnNew').on('click', ()=>location.href='estimate_form.php');

        render();
    });
</script>

<?php include '../inc/footer.php'; ?>
