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

$pdo = crm_pdo();
$page_title = 'Monthly payroll';

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

$month = trim((string)($_GET['month'] ?? date('Y-m')));
$employeeId = (int)($_GET['employee_id'] ?? 0);

$employees = $pdo->query("SELECT id, full_name FROM employees WHERE active = 1 ORDER BY full_name ASC")->fetchAll();

$from = $month . '-01';
$to = date('Y-m-t', strtotime($from));
$monthLabel = date('F Y', strtotime($from));

$where = ["ws.end_time IS NOT NULL", "DATE(ws.start_time) BETWEEN :d1 AND :d2"];
$params = [
    ':d1' => $from,
    ':d2' => $to,
];

if ($employeeId > 0) {
    $where[] = 'ws.employee_id = :eid';
    $params[':eid'] = $employeeId;
}

$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
    WHERE " . implode(' AND ', $where) . "
    ORDER BY e.full_name ASC, ws.start_time ASC
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

function payroll_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 payroll_billable_hours(int $minutes): float
{
    if ($minutes <= 0) {
        return 0.0;
    }
    return ceil($minutes / 30) * 0.5;
}

$grouped = [];
$grandActualMinutes = 0;
$grandBillableHours = 0.0;
$grandCost = 0.0;

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

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

    $eid = (int)($row['employee_id'] ?? 0);
    if (!isset($grouped[$eid])) {
        $grouped[$eid] = [
            'employee_name' => (string)($row['full_name'] ?? 'Unknown'),
            'rows' => [],
            'actual_minutes' => 0,
            'billable_hours' => 0.0,
            'cost' => 0.0,
        ];
    }

    $grouped[$eid]['rows'][] = $row;
    $grouped[$eid]['actual_minutes'] += $minutes;
    $grouped[$eid]['billable_hours'] += $billableHours;
    $grouped[$eid]['cost'] += $cost;

    $grandActualMinutes += $minutes;
    $grandBillableHours += $billableHours;
    $grandCost += $cost;
}

$selectedEmployeeName = 'All employees';
if ($employeeId > 0) {
    foreach ($employees as $employee) {
        if ((int)$employee['id'] === $employeeId) {
            $selectedEmployeeName = (string)$employee['full_name'];
            break;
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>
<style>
.payroll-toolbar-card{margin-bottom:14px}
.payroll-summary-grid{
  display:grid;
  grid-template-columns:repeat(3,minmax(0,1fr));
  gap:14px;
  margin-bottom:14px;
}
.payroll-summary-card{
  border:1px solid rgba(15,23,42,.08);
  border-radius:18px;
  padding:18px;
  background:rgba(255,255,255,.45);
}
.payroll-summary-label{
  font-size:.86rem;
  opacity:.72;
  margin-bottom:6px;
}
.payroll-summary-value{
  font-size:2rem;
  font-weight:800;
  line-height:1.1;
}
.payroll-print-header{
  display:none;
  border:1px solid rgba(15,23,42,.08);
  border-radius:18px;
  padding:18px;
  margin-bottom:14px;
  background:#fff;
}
.payroll-print-title{
  font-size:1.5rem;
  font-weight:800;
  margin-bottom:8px;
}
.payroll-print-meta{
  display:grid;
  grid-template-columns:repeat(3,minmax(0,1fr));
  gap:10px;
}
.payroll-print-meta-item{
  border:1px solid rgba(15,23,42,.08);
  border-radius:12px;
  padding:10px 12px;
}
.payroll-print-meta-label{
  font-size:.8rem;
  opacity:.72;
  margin-bottom:4px;
}
.payroll-print-meta-value{
  font-weight:700;
}
.payroll-employee-block{
  margin-bottom:16px;
}
.payroll-employee-header{
  display:flex;
  align-items:flex-start;
  justify-content:space-between;
  gap:12px;
  flex-wrap:wrap;
  margin-bottom:12px;
}
.payroll-employee-name{
  font-size:1.05rem;
  font-weight:800;
}
.payroll-employee-meta{
  font-size:.92rem;
  opacity:.82;
}
.payroll-table th,
.payroll-table td{
  vertical-align:middle;
  white-space:nowrap;
}
.payroll-table td:nth-child(2){
  white-space:normal;
  min-width:280px;
}
.table-responsive{
  overflow-x:auto;
}
@media (max-width: 900px){
  .payroll-summary-grid{
    grid-template-columns:1fr;
  }
  .payroll-print-meta{
    grid-template-columns:1fr;
  }
}
@media print {
  .navbar-gp,
  .page-header-actions,
  .payroll-toolbar-card,
  .form-actions {
    display:none !important;
  }
  body {
    background:#fff !important;
    color:#000 !important;
  }
  .container-gp {
    max-width:none !important;
    padding:0 !important;
  }
  .payroll-print-header{
    display:block !important;
  }
  .card,
  .payroll-summary-card,
  .payroll-print-meta-item {
    box-shadow:none !important;
    background:#fff !important;
  }
  .payroll-summary-grid{
    break-inside:avoid;
  }
  .payroll-employee-block{
    break-inside:avoid;
  }
}
</style>

<div class="page-header">
  <div class="page-header-title">
    <h1>Monthly payroll</h1>
    <span>Calculated from work sessions</span>
  </div>
</div>

<div class="payroll-print-header">
  <div class="payroll-print-title">Monthly Payroll Report</div>
  <div class="payroll-print-meta">
    <div class="payroll-print-meta-item">
      <div class="payroll-print-meta-label">Month</div>
      <div class="payroll-print-meta-value"><?php echo h($monthLabel); ?></div>
    </div>
    <div class="payroll-print-meta-item">
      <div class="payroll-print-meta-label">Employee</div>
      <div class="payroll-print-meta-value"><?php echo h($selectedEmployeeName); ?></div>
    </div>
    <div class="payroll-print-meta-item">
      <div class="payroll-print-meta-label">Printed on</div>
      <div class="payroll-print-meta-value"><?php echo h(date('Y-m-d H:i')); ?></div>
    </div>
  </div>
</div>

<div class="card payroll-toolbar-card">
  <form method="get">
    <div class="form-grid">
      <div class="form-group">
        <label>Month</label>
        <input type="month" name="month" value="<?php echo h($month); ?>">
      </div>
      <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>
    <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="payroll-summary-grid">
  <div class="payroll-summary-card">
    <div class="payroll-summary-label">Actual hours</div>
    <div class="payroll-summary-value"><?php echo h(number_format($grandActualMinutes / 60, 2)); ?> h</div>
  </div>
  <div class="payroll-summary-card">
    <div class="payroll-summary-label">Billable hours</div>
    <div class="payroll-summary-value"><?php echo h(number_format($grandBillableHours, 2)); ?> h</div>
  </div>
  <div class="payroll-summary-card">
    <div class="payroll-summary-label">Payroll total</div>
    <div class="payroll-summary-value">€ <?php echo h(number_format($grandCost, 2)); ?></div>
  </div>
</div>

<?php if (!$grouped): ?>
  <div class="card">
    <p class="small">No payroll records found for the selected month.</p>
  </div>
<?php else: ?>
  <?php foreach ($grouped as $employeeData): ?>
    <div class="card payroll-employee-block">
      <div class="payroll-employee-header">
        <div class="payroll-employee-name"><?php echo h($employeeData['employee_name']); ?></div>
        <div class="payroll-employee-meta">
          Actual: <?php echo h(number_format($employeeData['actual_minutes'] / 60, 2)); ?> h ·
          Billable: <?php echo h(number_format($employeeData['billable_hours'], 2)); ?> h ·
          Total: € <?php echo h(number_format($employeeData['cost'], 2)); ?>
        </div>
      </div>

      <div class="table-responsive">
        <table class="table payroll-table">
          <thead>
            <tr>
              <th>Date</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 ($employeeData['rows'] as $row): ?>
            <tr>
              <td><?php echo h((string)($row['work_date'] ?? date('Y-m-d', strtotime((string)$row['start_time'])))); ?></td>
              <td><?php echo h(($row['project_code'] ?? '') . ' · ' . ($row['project_title'] ?? '')); ?></td>
              <td><?php echo h((string)$row['start_time']); ?></td>
              <td><?php echo h((string)$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 endforeach; ?>
<?php endif; ?>

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