<?php
require_once __DIR__.'/../_pdo_db_connect.php';
require_once __DIR__.'/../middleware/auth_check.php';
require_once __DIR__.'/../../Controllers/TaskController.php';

$auth = new AuthCheck();
$user = $auth->requireAuth();

$data = json_decode(file_get_contents('php://input'), true);
$controller = new TaskController($pdo);
$result = $controller->createOrUpdate($data, $user);

echo json_encode($result);

$payload = require_auth();
$input = json_decode(file_get_contents('php://input'), true);
$pdo = get_db();
if (!empty($input['id'])){
    $stmt = $pdo->prepare('UPDATE sd_tasks SET title=?,description=?,assigned_to=?,status=?,due_date=? WHERE id=?');
    $stmt->execute([$input['title'],$input['description'],$input['assigned_to'],$input['status'],$input['due_date'],$input['id']]);
    json_res(['status'=>'updated']);
}else{
    $stmt = $pdo->prepare('INSERT INTO sd_tasks(title,description,assigned_to,created_by,status,due_date,created_at) VALUES(?,?,?,?,?,?,NOW())');
    $stmt->execute([$input['title'],$input['description'],$input['assigned_to'],$payload['sub'],$input['status'],$input['due_date']]);
    json_res(['status'=>'created','id'=>$pdo->lastInsertId()]);
}
