<?php
declare(strict_types=1);
require_once __DIR__ . '/_bootstrap.php';

ensure_schema();
$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $input = read_json();
  $body = trim((string)($input['body'] ?? ''));
  if ($body === '') json_response(['success' => false, 'error' => 'Empty body']);

  $direction = $input['direction'] ?? 'out';
  $contactId = (int)($input['contact_id'] ?? 0);
  $phone = trim((string)($input['phone'] ?? ''));

  if ($contactId <= 0 && $phone === '') {
    json_response(['success' => false, 'error' => 'Missing contact']);
  }

  if ($contactId <= 0 && $phone !== '') {
    $stmt = $pdo->prepare("SELECT id FROM contacts WHERE phone = ?");
    $stmt->execute([$phone]);
    $contactId = (int)($stmt->fetchColumn() ?: 0);
    if ($contactId <= 0) {
      $insert = $pdo->prepare("INSERT INTO contacts (phone, name, tags, status) VALUES (?, ?, ?, 'normal')");
      $insert->execute([$phone, $input['name'] ?? null, $input['tags'] ?? null]);
      $contactId = (int)$pdo->lastInsertId();
    }
  }

  $stmt = $pdo->prepare("INSERT INTO messages (contact_id, direction, body, is_read) VALUES (?, ?, ?, ?)");
  $stmt->execute([$contactId, $direction, $body, $direction === 'in' ? 0 : 1]);
  json_response(['success' => true, 'contact_id' => $contactId]);
}

if (isset($_GET['all'])) {
  $phoneFilter = trim((string)($_GET['phone'] ?? ''));
  if ($phoneFilter !== '') {
    $stmt = $pdo->prepare("
      SELECT m.id, m.direction, m.body, m.created_at, c.phone
      FROM messages m
      JOIN contacts c ON c.id = m.contact_id
      WHERE c.phone LIKE ?
      ORDER BY m.created_at DESC
      LIMIT 200
    ");
    $stmt->execute(['%' . $phoneFilter . '%']);
    $messages = $stmt->fetchAll();
  } else {
    $messages = $pdo->query("
      SELECT m.id, m.direction, m.body, m.created_at, c.phone
      FROM messages m
      JOIN contacts c ON c.id = m.contact_id
      ORDER BY m.created_at DESC
      LIMIT 200
    ")->fetchAll();
  }
  json_response(['messages' => $messages]);
}

$contactId = (int)($_GET['contact_id'] ?? 0);
if ($contactId <= 0) {
  json_response(['messages' => []]);
}

$stmt = $pdo->prepare("SELECT id, direction, body, created_at FROM messages WHERE contact_id = ? ORDER BY created_at ASC");
$stmt->execute([$contactId]);
$messages = $stmt->fetchAll();

$pdo->prepare("UPDATE messages SET is_read = 1 WHERE contact_id = ? AND direction = 'in'")->execute([$contactId]);

json_response(['messages' => $messages]);
