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

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

  public function list($page=1, $per=25, $params=[]){
    $offset = max(0, ($page-1)*$per);
    $customer = $params['customer_id'] ?? null;
    $sql = "SELECT f.* FROM sd_followups f";
    $p = [];
    if ($customer){ $sql .= " WHERE f.customer_id = ?"; $p[] = $customer; }
    $sql .= " ORDER BY f.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];
  }

  public function get($id){
    $stmt = $this->pdo->prepare("SELECT * FROM sd_followups 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){
    $customer_id = $input['customer_id'] ?? null; $note = $input['note'] ?? '';
    if (!$customer_id || !$note) return ['status'=>0,'error'=>'missing_fields'];
    $stmt = $this->pdo->prepare("INSERT INTO sd_followups (customer_id, note, created_by) VALUES (?, ?, ?)");
    $stmt->execute([$customer_id, $note, $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=[];
    if (isset($input['note'])) { $fields[]='note=?'; $params[]=$input['note']; }
    if (empty($fields)) return ['status'=>0,'error'=>'no_fields'];
    $params[]=$id;
    $stmt = $this->pdo->prepare("UPDATE sd_followups SET ".implode(', ',$fields)." WHERE id = ?");
    $stmt->execute($params);
    return ['status'=>1,'updated_id'=>$id];
  }
}
?>
