<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();

$pdo = crm_pdo();
$page_title = 'Work report';

if (!gp_is_full_project_access_role(gp_user_role($pdo))) {
    http_response_code(403);
    exit('Access denied.');
}

$employees = $pdo->query("SELECT id, full_name FROM employees ORDER BY full_name ASC")->fetchAll();
$projects = $pdo->query("SELECT id, code, title FROM projects ORDER BY code ASC")->fetchAll();

$employeeId = (int)($_GET['employee_id'] ?? 0);
$projectId = (int)($_GET['project_id'] ?? 0);
$from = trim((string)($_GET['from'] ?? date('Y-m-01')));
$to = trim((string)($_GET['to'] ?? date('Y-m-d')));

$where = ["ws.end_time IS NOT NULL"];
$params = [];

if ($employeeId > 0) {
    $where[] = 'ws.employee_id = :eid';
    $params[':eid'] = $employeeId;
}
if ($projectId > 0) {
    $where[] = 'ws.project_id = :pid';
    $params[':pid'] = $projectId;
}
if ($from !== '') {
    $where[] = 'ws.start_time >= :d1';
    $params[':d1'] = $from . ' 00:00:00';
}
if ($to !== '') {
    $where[] = 'ws.start_time <= :d2';
    $params[':d2'] = $to . ' 23:59:59';
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

$sql = "
    SELECT
        ws.*,
        e.full_name,
        p.code AS project_code,
        p.title AS project_title
    FROM work_sessions ws
    LEFT JOIN employees e ON e.id = ws.employee_id
    LEFT JOIN projects p ON p.id = ws.project_id
    $whereSql
    ORDER BY ws.start_time DESC
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

function gp_session_minutes(array $row): int
{
    $start = strtotime((string)($row['start_time'] ?? ''));
    $end = strtotime((string)($row['end_time'] ?? ''));
    if (!$start || !$end || $end < $start) {
        return 0;
    }
    return max(0, (int)round(($end - $start) / 60));
}

function gp_billable_half_hours(int $minutes): float
{
    if ($minutes <= 0) {
        return 0.0;
    }
    return ceil($minutes / 30) * 0.5;
}

$totalMinutes = 0;
$totalBillableHours = 0.0;
$totalCost = 0.0;

foreach ($rows as &$row) {
    $minutes = gp_session_minutes($row);
    $billableHours = gp_billable_half_hours($minutes);
    $rate = (float)($row['hourly_rate'] ?? 0);
    $cost = $billableHours * $rate;

    $row['_minutes'] = $minutes;
    $row['_actual_hours'] = $minutes / 60;
    $row['_billable_hours'] = $billableHours;
    $row['_cost'] = $cost;

    $totalMinutes += $minutes;
    $totalBillableHours += $billableHours;
    $totalCost += $cost;
}
unset($row);

include __DIR__ . '/../includes/header.php';
?>
<style>
.work-summary-grid{
  display:grid;
  grid-template-columns:repeat(3, minmax(0, 1fr));
  gap:14px;
  margin-bottom:14px;
}
.work-summary-card{
  border:1px solid rgba(15,23,42,.08);
  border-radius:18px;
  padding:18px;
  background:rgba(255,255,255,.45);
}
.work-summary-label{
  font-size:.86rem;
  opacity:.72;
  margin-bottom:6px;
}
.work-summary-value{
  font-size:2rem;
  font-weight:800;
  line-height:1.1;
}
.table th,
.table td{
  vertical-align:middle;
  white-space:nowrap;
}
.table td:nth-child(2){
  white-space:normal;
  min-width:280px;
}
.table-responsive{
  overflow-x:auto;
}
@media (max-width: 900px){
  .work-summary-grid{
    grid-template-columns:1fr;
  }
}
@media print {
  .navbar-gp, form, .form-actions, .page-header-actions { display:none !important; }
  body { background:#fff !important; color:#000 !important; }
  .card { box-shadow:none !important; }
}
</style>

<div class="page-header">
  <div class="page-header-title">
    <h1>Work report</h1>
    <span>Employee hours and labor costing</span>
  </div>
</div>

<div class="card" style="margin-bottom:14px">
  <form method="get">
    <div class="form-grid">
      <div class="form-group">
        <label>Employee</label>
        <select name="employee_id">
          <option value="0">All</option>
          <?php foreach ($employees as $employee): ?>
            <option value="<?php echo (int)$employee['id']; ?>" <?php echo $employeeId === (int)$employee['id'] ? 'selected' : ''; ?>>
              <?php echo h($employee['full_name']); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>Project</label>
        <select name="project_id">
          <option value="0">All</option>
          <?php foreach ($projects as $project): ?>
            <option value="<?php echo (int)$project['id']; ?>" <?php echo $projectId === (int)$project['id'] ? 'selected' : ''; ?>>
              <?php echo h($project['code'] . ' · ' . $project['title']); ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label>From</label>
        <input type="date" name="from" value="<?php echo h($from); ?>">
      </div>
      <div class="form-group">
        <label>To</label>
        <input type="date" name="to" value="<?php echo h($to); ?>">
      </div>
    </div>
    <div class="form-actions">
      <button class="btn btn-primary" type="submit">Filter</button>
      <button class="btn btn-secondary" type="button" onclick="window.print()">Print</button>
    </div>
  </form>
</div>

<div class="work-summary-grid">
  <div class="work-summary-card">
    <div class="work-summary-label">Actual hours</div>
    <div class="work-summary-value"><?php echo h(number_format($totalMinutes / 60, 2)); ?> h</div>
  </div>

  <div class="work-summary-card">
    <div class="work-summary-label">Billable hours</div>
    <div class="work-summary-value"><?php echo h(number_format($totalBillableHours, 2)); ?> h</div>
  </div>

  <div class="work-summary-card">
    <div class="work-summary-label">Labor cost</div>
    <div class="work-summary-value">€ <?php echo h(number_format($totalCost, 2)); ?></div>
  </div>
</div>

<div class="card">
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>Employee</th>
          <th>Project</th>
          <th>Start</th>
          <th>End</th>
          <th>Actual hours</th>
          <th>Billable hours</th>
          <th>Hourly rate</th>
          <th>Cost</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($rows as $row): ?>
        <tr>
          <td><?php echo h($row['full_name'] ?? ''); ?></td>
          <td><?php echo h(($row['project_code'] ?? '') . ' · ' . ($row['project_title'] ?? '')); ?></td>
          <td><?php echo h($row['start_time'] ?? ''); ?></td>
          <td><?php echo h($row['end_time'] ?? ''); ?></td>
          <td><?php echo h(number_format((float)$row['_actual_hours'], 2)); ?> h</td>
          <td><?php echo h(number_format((float)$row['_billable_hours'], 2)); ?> h</td>
          <td>€ <?php echo h(number_format((float)($row['hourly_rate'] ?? 0), 2)); ?></td>
          <td>€ <?php echo h(number_format((float)$row['_cost'], 2)); ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
