<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");

// 접근 권한 체크
if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    sleep(1);
    header("Location:" . $WebSite . "login/login_form.php");
    exit;
}

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
$title_message = '견적 통계';
$title_prefix = '발주처별 견적 통계자료';
?>
  
<title><?= $title_prefix ?> <?= $title_message ?></title>
</head>
<body>
<?php 
require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); 
require_once($_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'); 
// estimate 테이블 통계 관련 함수 (발주처별 견적금액 합계, 차트 데이터 등)
require_once($_SERVER['DOCUMENT_ROOT'] . '/estimate/func_statistics.php');  


?>

<!-- 기간 설정 폼 -->
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">    
  <div class="container">    
    <div class="d-flex mt-4 mb-4 align-items-center justify-content-center">         
      <span class="text-center fs-5"><?= $title_message ?></span>       
      <button type="button" class="btn btn-dark btn-sm mx-2" onclick="location.reload();">
        <i class="bi bi-arrow-clockwise"></i>
      </button>  	   		  								
    </div>        
    <div class="d-flex mt-2 mb-3 align-items-center justify-content-center">               
      <!-- 기간부터 검색까지 연결 -->
      <span id="showdate" class="btn btn-dark btn-sm mx-1"> 기간 </span>&nbsp; 
      <div id="showframe" class="card" style="width:500px;">
        <div class="card-header" style="padding:2px;">
          <div class="d-flex justify-content-center align-items-center">기간 설정</div>
        </div>
        <div class="card-body">
          <div class="d-flex justify-content-center align-items-center">  	
            <button type="button" class="btn btn-outline-success btn-sm me-1 change_dateRange" onclick="alldatesearch()">전체</button>  
            <button type="button" id="preyear" class="btn btn-outline-primary btn-sm me-1 change_dateRange" onclick="pre_year()">전년도</button>  
            <button type="button" id="three_month" class="btn btn-dark btn-sm me-1 change_dateRange" onclick="three_month_ago()">M-3월</button>
            <button type="button" id="prepremonth" class="btn btn-dark btn-sm me-1 change_dateRange" onclick="prepre_month()">전전월</button>	
            <button type="button" id="premonth" class="btn btn-dark btn-sm me-1 change_dateRange" onclick="pre_month()">전월</button> 						
            <button type="button" class="btn btn-outline-danger btn-sm me-1 change_dateRange" onclick="this_today()">오늘</button>
            <button type="button" id="thismonth" class="btn btn-dark btn-sm me-1 change_dateRange" onclick="this_month()">당월</button>
            <button type="button" id="thisyear" class="btn btn-dark btn-sm me-1 change_dateRange" onclick="this_year()">당해년도</button> 
          </div>
        </div>
      </div>		
      <input type="date" id="fromdate" name="fromdate" size="12" class="form-control" style="width:100px;" value="<?= $fromdate ?>">  
      &nbsp; ~ &nbsp;  
      <input type="date" id="todate" name="todate" size="12" class="form-control" style="width:100px;" value="<?= $todate ?>">  
      &nbsp;&nbsp;		      
      <button class="btn btn-dark btn-sm mx-1" type="button" id="searchBtn">
        <i class="bi bi-search"></i>
      </button>             
      
    </div>       
  </div>  
</form>

<!-- 요약 테이블 -->
<div class="container mt-4">
  <div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-center align-items-center">
    <div class="card w-50">
      <div class="card-header text-center">
        <h5>발주처별 견적금액 합계</h5>
      </div>
      <div class="card-body">
        <?php include $_SERVER['DOCUMENT_ROOT'] . '/estimate/estimate_table.php'; ?>
      </div>
    </div>
  </div>
</div>

<!-- 금액 통계 차트 (Highcharts) -->
<div class="container mt-4">
  <div class="card">
    <div class="card-header text-center">
      <h5>발주처별 견적금액 그래프</h5>
    </div>
    <div class="card-body">
      <div id="amountChart" style="height: 500px;"></div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const chartData = <?= $jsonChartData ?>;
  Highcharts.chart('amountChart', {
    chart: { type: 'column' },
    title: { text: '' },
    xAxis: {
      type: 'category',
      title: { text: '발주처' }
    },
    yAxis: {
      min: 0,
      title: { text: '견적금액 합계' }
    },
    tooltip: {
      pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b><br/>'
    },
    series: [{
      name: '견적금액 합계',
      data: chartData
    }]
  });
});
</script>

<!-- 로딩 오버레이 제거 및 방문기록 남김 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  var loader = document.getElementById('loadingOverlay');
  if (loader) loader.style.display = 'none';
});
$(document).ready(function(){    
  var title_message = '<?= $title_message ?>';
  saveMenuLog(title_message);
});
</script>

<!-- 업체별 견적 내역 상세 테이블 (반응형 적용) -->
<div class="container mt-4">        
  <div class="row">
    <?php foreach ($rows as $row): ?>
      <?php
      // 통계 쿼리에서 secondord를 supplier alias로 사용하였으므로, 상세 조회는 secondord 기준
      $supplierName = $row['supplier'];
      // 해당 발주처의 견적 내역 조회 (견적번호, 접수일, 현장명, 견적금액)
      $sqlDetail = "SELECT pjnum, indate, outworkplace, estimateTotal
                    FROM {$DB}.{$tablename}
                    WHERE secondord = :supplier
                      AND indate BETWEEN :fromdate AND :todate
                      AND is_deleted IS NULL
                    ORDER BY indate DESC";
      $stmtDetail = $pdo->prepare($sqlDetail);
      $stmtDetail->bindValue(':supplier', $supplierName);
      $stmtDetail->bindValue(':fromdate', $fromdate);
      $stmtDetail->bindValue(':todate', $todate);
      $stmtDetail->execute();
      $details = $stmtDetail->fetchAll(PDO::FETCH_ASSOC);
      ?>
      <div class="col-12 col-sm-4 mb-3">
        <div class="card h-100">
          <div class="card-header">
            <h6><?= htmlspecialchars($supplierName) ?> (총 견적금액: <?= number_format($row['total_amount']) ?>)</h6>
          </div>
          <div class="card-body p-0">
            <table class="table table-bordered mb-0">
              <thead class="table-secondary">
                <tr>
                  <th style="width:30%;">견적번호</th>
                  <th style="width:20%;">접수일</th>
                  <th style="width:30%;">현장명</th>
                  <th style="width:20%;" class="text-end">견적금액</th>
                </tr>
              </thead>
              <tbody>
                <?php if(count($details) > 0): ?>
                  <?php foreach ($details as $detail): ?>
                    <tr>
                      <td><?= htmlspecialchars($detail['pjnum']) ?></td>
                      <td><?= htmlspecialchars($detail['indate']) ?></td>
                      <td><?= htmlspecialchars($detail['outworkplace']) ?></td>
                      <td class="text-end">
                        <?= is_numeric($detail['estimateTotal']) ? number_format($detail['estimateTotal']) : htmlspecialchars($detail['estimateTotal']) ?>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php else: ?>
                  <tr>
                    <td colspan="4" class="text-center">견적 내역이 없습니다.</td>
                  </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>    
</body>
</html>
