<?php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../inc/auth.php';
$session = auth_require('engineer', 'technician');

$pdo = getDB();
$userId = $session['user_id'];
$role = $session['user_role'];

$sql = "SELECT t.*, o.name as object_name, o.address FROM tasks t JOIN objects o ON o.id=t.object_id WHERE t.status IN ('open','in_progress')";
$params = [];

if ($role === 'technician') {
    $sql .= " AND t.assigned_to = ?";
    $params[] = $userId;
}

$sql .= " ORDER BY CASE t.priority WHEN 'P1' THEN 1 WHEN 'P2' THEN 2 WHEN 'P3' THEN 3 WHEN 'P4' THEN 4 END, t.deadline ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
echo json_encode($stmt->fetchAll());
