<?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') {
    gp_require_csrf();
    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('/gopools/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, status, due_date, notes) VALUES (:pid,:title,'todo',:due,:notes)");
            $stmt->execute([
                ':pid' => $projectId,
                ':title' => $title,
                ':due' => $due !== '' ? $due : null,
                ':notes' => $notes !== '' ? $notes : null,
            ]);
            redirect('/gopools/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';
?>
<?php gp_render_project_menu($pdo, $projectId); ?>

<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="/gopools/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">? ??s? st? ????</a>
  </div>
</div>

<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">
      <?php echo csrf_field(); ?>
      <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>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>Due</th><th>Status</th><th>Notes</th></tr></thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td>
              <form method="post">
      <?php echo csrf_field(); ?>
                <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(gp_date((string)$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'; ?>
