<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/session.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/common.php');    // $DB 정의
require_once($_SERVER['DOCUMENT_ROOT'] . '/lib/mydb.php');
$pdo = db_connect();

// 입력값: 년도, 회사(필터)
$year = isset($_POST['year'])  ? (int)$_POST['year']  : (int)date('Y');
$corp = isset($_POST['corp'])  ? trim($_POST['corp']) : '';

// 1) eworks 테이블에서 실제 사용된 연차만 월별 집계 (author → member.name JOIN)
$sql1 = "
  SELECT
    m.id                           AS uid,
    MONTH(CAST(e.al_askdatefrom AS DATE)) AS mon,
    SUM(CAST(e.al_usedday AS DECIMAL(10,1))) AS used
  FROM {$DB}.eworks e
  JOIN {$DB}.member m
    ON TRIM(e.author) = m.name
       AND (m.quitDate IS NULL OR m.quitDate = '0000-00-00')
  WHERE e.eworks_item = '연차'
    AND e.is_deleted IS NULL
    AND e.status    = 'end'
    AND e.done      = 'done'
    AND YEAR(CAST(e.al_askdatefrom AS DATE)) = :year
    AND CAST(e.al_usedday AS DECIMAL(10,1)) > 0
";
if ($corp !== '') {
    $sql1 .= " AND m.division LIKE :corp ";
}
$sql1 .= "
  GROUP BY m.id, mon
";

$stmt1 = $pdo->prepare($sql1);
$stmt1->bindValue(':year', $year, PDO::PARAM_INT);
if ($corp !== '') {
    $stmt1->bindValue(':corp', "%{$corp}%", PDO::PARAM_STR);
}
$stmt1->execute();
$rows = $stmt1->fetchAll(PDO::FETCH_ASSOC);

// Pivot: [uid][month] = used
$usageData = [];
foreach ($rows as $r) {
    $uid = $r['uid'];
    $mon = (int)$r['mon'];
    $usageData[$uid][$mon] = ($usageData[$uid][$mon] ?? 0) + (float)$r['used'];
}

// 2) member 테이블에서 재직 중 전체 직원 조회 (퇴직자 제외, 회사 필터)
$sql2 = "
  SELECT
    m.id       AS uid,
    m.name     AS name,
    m.division AS corp,
    m.part     AS dept,
    m.position AS position
  FROM {$DB}.member m
  WHERE (m.quitDate IS NULL OR m.quitDate = '0000-00-00')
";
if ($corp !== '') {
    $sql2 .= " AND m.division LIKE :corp ";
}
$stmt2 = $pdo->prepare($sql2);
if ($corp !== '') {
    $stmt2->bindValue(':corp', "%{$corp}%", PDO::PARAM_STR);
}
$stmt2->execute();
$members = $stmt2->fetchAll(PDO::FETCH_ASSOC);

// 3) 전체 직원 기준으로 초기 배열 구성
$data = [];
foreach ($members as $m) {
    $data[] = [
        'uid'      => $m['uid'],
        'corp'     => $m['corp'],
        'dept'     => $m['dept'],
        'position' => $m['position'],
        'name'     => $m['name'],
        'months'   => array_fill(1, 12, 0),
    ];
}

// 4) 사용량이 있는 달에만 값 채우기
foreach ($data as &$row) {
    $uid = $row['uid'];
    if (isset($usageData[$uid])) {
        foreach ($usageData[$uid] as $mon => $used) {
            $row['months'][$mon] = $used;
        }
    }
}
unset($row);

// 5) 결과 테이블 출력
?>
<table class="table table-bordered text-center">
  <thead class="table-secondary">
    <tr>
      <th>번호</th>
      <th>소속</th>
      <th>부서</th>
      <th>직위</th>
      <th>이름</th>
<?php for ($m = 1; $m <= 12; $m++): ?>
      <th><?= $m ?>월</th>
<?php endfor; ?>
      <th>합계</th>
    </tr>
  </thead>
  <tbody>
<?php
$no = 1;
foreach ($data as $row):
    $sum = array_sum($row['months']);
?>
    <tr>
      <td><?= $no++ ?></td>
      <td><?= htmlspecialchars($row['corp'], ENT_QUOTES) ?></td>
      <td><?= htmlspecialchars($row['dept'], ENT_QUOTES) ?></td>
      <td><?= htmlspecialchars($row['position'], ENT_QUOTES) ?></td>
      <td><?= htmlspecialchars($row['name'], ENT_QUOTES) ?></td>
<?php foreach ($row['months'] as $v): ?>
      <td><?= $v !== 0 ? $v : '' ?></td>
<?php endforeach; ?>
      <td><?= $sum !== 0 ? $sum : '' ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
