<?php
// /api/tasks.php
require_once __DIR__ . '/middleware.php';
require_once __DIR__ . '/../Controllers/TaskController.php';

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

$ctrl = new Controllers\TaskController();
header('Content-Type: application/json');

switch($action){
  case 'get':
    $id = $input['id'] ?? $_GET['id'] ?? null;
    if (!$id) { echo json_encode(['status'=>0,'error'=>'missing_id']); exit; }
    echo json_encode($ctrl->get($id));
    break;
  case 'create':
    $user = api_authenticate_or_die();
    echo json_encode($ctrl->create($input, $user));
    break;
  case 'update':
    $user = api_authenticate_or_die();
    $id = $input['id'] ?? null;
    echo json_encode($ctrl->update($id, $input, $user));
    break;
  case 'delete':
    $user = api_authenticate_or_die();
    $id = $input['id'] ?? null;
    echo json_encode($ctrl->delete($id, $user));
    break;
  case 'list':
  default:
    $page = intval($_GET['page'] ?? 1);
    $per = intval($_GET['per'] ?? 25);
    echo json_encode($ctrl->list($page, $per, $_GET));
    break;
}
?>