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

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

  public function create($input, $user_id){
    $to = $input['to_user_id'] ?? null; $body = $input['body'] ?? '';
    if (!$to || !$body) return ['status'=>0,'error'=>'missing_fields'];
    $stmt = $this->pdo->prepare("INSERT INTO sd_messages (from_user_id, to_user_id, body) VALUES (?, ?, ?)");
    $stmt->execute([$user_id, $to, $body]);
    return ['status'=>1,'insert_id'=>$this->pdo->lastInsertId()];
  }

  public function list($page=1, $per=25, $params=[]){
    $offset = max(0, ($page-1)*$per);
    $user_id = $params['user_id'] ?? null;
    if (!$user_id) return ['status'=>0,'error'=>'missing_user'];
    $stmt = $this->pdo->prepare("SELECT * FROM sd_messages WHERE to_user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
    $stmt->execute([$user_id, $per, $offset]);
    $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    return ['status'=>1,'data'=>$rows];
  }
}
?>
