<?php
// /Controllers/TaskController.php
namespace Controllers;
require_once __DIR__ . '/../_Core/bootstrap.php';

class TaskController {
  protected $pdo;
  public function __construct(){ $this->pdo = Database::getConnection(); }

  public function list($page=1, $per=25, $params=[]){
    $offset = max(0, ($page-1)*$per);
    $user = $params['user'] ?? null;
    $sql = "SELECT t.* FROM sd_tasks t";
    $clauses = [];
    $p = [];
    if ($user) { $clauses[] = "t.assigned_to = ?"; $p[] = $user; }
    if ($clauses) $sql .= " WHERE " . implode(' AND ', $clauses);
    $sql .= " ORDER BY t.created_at DESC LIMIT ? OFFSET ?";
    $p[] = $per; $p[] = $offset;
    $stmt = $this->pdo->prepare($sql);
    $stmt->execute($p);
    $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    return ['status'=>1,'data'=>$rows,'page'=>$page,'per'=>$per];
  }

  public function get($id){
    $stmt = $this->pdo->prepare("SELECT * FROM sd_tasks WHERE id = ? LIMIT 1");
    $stmt->execute([$id]); $r = $stmt->fetch(\PDO::FETCH_ASSOC);
    if (!$r) return ['status'=>0,'error'=>'not_found']; return ['status'=>1,'data'=>$r];
  }

  public function create($input, $user_id){
    $title = $input['title'] ?? ''; $customer_id = $input['customer_id'] ?? null;
    if (!$title || !$customer_id) return ['status'=>0,'error'=>'missing_fields'];
    $stmt = $this->pdo->prepare("INSERT INTO sd_tasks (title, customer_id, assigned_to, created_by, status) VALUES (?, ?, ?, ?, 'open')");
    $stmt->execute([$title, $customer_id, $input['assigned_to'] ?? $user_id, $user_id]);
    return ['status'=>1,'insert_id'=>$this->pdo->lastInsertId()];
  }

  public function update($id, $input, $user_id){
    if (!$id) return ['status'=>0,'error'=>'missing_id'];
    $fields = []; $params = [];
    foreach (['title','status','assigned_to','notes'] as $f){
      if (isset($input[$f])){ $fields[] = "$f = ?"; $params[] = $input[$f]; }
    }
    if (empty($fields)) return ['status'=>0,'error'=>'no_fields'];
    $params[] = $id;
    $stmt = $this->pdo->prepare("UPDATE sd_tasks SET ".implode(', ',$fields)." WHERE id = ?");
    $stmt->execute($params);
    return ['status'=>1,'updated_id'=>$id];
  }

  public function delete($id, $user_id){
    $stmt = $this->pdo->prepare("DELETE FROM sd_tasks WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    return ['status'=>1,'deleted_id'=>$id];
  }
}
?>
