<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/project_menu.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');
gp_require_project_edit($pdo, $projectId);

$stmt = $pdo->prepare("SELECT p.*, c.name AS customer_name FROM projects p LEFT JOIN customers c ON c.id = p.customer_id WHERE p.id = :id LIMIT 1");
$stmt->execute([':id' => $projectId]);
$project = $stmt->fetch();
if (!$project) die('Project not found.');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (($_POST['action'] ?? '') === 'toggle') {
        $taskId = (int)($_POST['task_id'] ?? 0);
        $stmt = $pdo->prepare("UPDATE project_tasks SET status = CASE WHEN status='done' THEN 'todo' ELSE 'done' END WHERE id = :id AND project_id = :pid");
        $stmt->execute([':id' => $taskId, ':pid' => $projectId]);
        redirect('/public/projects/tasks.php?project_id=' . $projectId);
    } else {
        $title = trim((string)($_POST['title'] ?? ''));
        $assigned = (int)($_POST['assigned_employee_id'] ?? 0);
        $due = trim((string)($_POST['due_date'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));
        if ($title === '') $errors[] = 'Task title is required.';
        if (!$errors) {
            $stmt = $pdo->prepare("INSERT INTO project_tasks (project_id, title, assigned_employee_id, status, due_date, notes) VALUES (:pid,:title,:emp,'todo',:due,:notes)");
            $stmt->execute([
                ':pid' => $projectId,
                ':title' => $title,
                ':emp' => $assigned > 0 ? $assigned : null,
                ':due' => $due !== '' ? $due : null,
                ':notes' => $notes !== '' ? $notes : null,
            ]);
            redirect('/public/projects/tasks.php?project_id=' . $projectId);
        }
    }
}

$stmt = $pdo->prepare("SELECT pt.*, e.full_name FROM project_tasks pt LEFT JOIN employees e ON e.id = pt.assigned_employee_id WHERE pt.project_id = :pid ORDER BY pt.status ASC, pt.due_date ASC, pt.id DESC");
$stmt->execute([':pid' => $projectId]);
$rows = $stmt->fetchAll();

$total = count($rows);
$done = 0;
foreach ($rows as $row) {
    if (($row['status'] ?? '') === 'done') $done++;
}
$progress = $total > 0 ? round(($done / $total) * 100) : 0;

$page_title = 'Project tasks';
include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Tasks · <?php echo h($project['title']); ?></h1>
    <span><?php echo h($project['code']); ?> · <?php echo h($project['customer_name']); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">Back to project</a>
  </div>
</div>

<div class="card" style="margin-bottom:14px">
  <div class="small">Checklist progress</div>
  <div style="font-size:2rem;font-weight:700"><?php echo (int)$progress; ?>%</div>
  <div class="small"><?php echo (int)$done; ?> / <?php echo (int)$total; ?> done</div>
</div>

<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="grid-2">
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Add task</h1></div>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Title</label><input type="text" name="title" required></div>
        <div class="form-group"><label>Assigned employee</label><select name="assigned_employee_id"><option value="0">None</option><?php foreach ($employees as $e): ?><option value="<?php echo (int)$e['id']; ?>"><?php echo h($e['full_name']); ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label>Due date</label><input type="date" name="due_date"></div>
        <div class="form-group"><label>Notes</label><input type="text" name="notes"></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Save task</button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Task list</h1></div>
    <div class="table-responsive">
      <table class="table">
        <thead><tr><th>Done</th><th>Title</th><th>Assigned</th><th>Due</th><th>Status</th><th>Notes</th></tr></thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td>
              <form method="post">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
                <input type="hidden" name="task_id" value="<?php echo (int)$r['id']; ?>">
                <input type="checkbox" <?php echo ($r['status'] === 'done') ? 'checked' : ''; ?> onchange="this.form.submit()">
              </form>
            </td>
            <td><?php echo h($r['title']); ?></td>
            <td><?php echo h($r['full_name']); ?></td>
            <td><?php echo h($r['due_date']); ?></td>
            <td><?php echo h($r['status']); ?></td>
            <td><?php echo h($r['notes']); ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
