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

$pdo = crm_pdo();

$start = $_GET['start'] ?? date('Y-m-01');
$end = $_GET['end'] ?? date('Y-m-d');

$sql = "
SELECT 
employee_id,
SUM(TIMESTAMPDIFF(MINUTE,start_time,end_time))/60 as hours,
SUM((TIMESTAMPDIFF(MINUTE,start_time,end_time)/60)*hourly_rate) as cost
FROM work_sessions
WHERE end_time IS NOT NULL
AND work_date BETWEEN ? AND ?
GROUP BY employee_id
";

$stmt = $pdo->prepare($sql);
$stmt->execute([$start,$end]);
$data = $stmt->fetchAll();
?>

<h2>Time Reports</h2>

<form>
<input type="date" name="start" value="<?=$start?>">
<input type="date" name="end" value="<?=$end?>">
<button>Filter</button>
</form>

<table>
<tr><th>Employee</th><th>Hours</th><th>Cost</th></tr>
<?php foreach($data as $r): ?>
<tr>
<td><?=$r['employee_id']?></td>
<td><?=round($r['hours'],2)?></td>
<td><?=round($r['cost'],2)?></td>
</tr>
<?php endforeach; ?>
</table>
