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

ensure_schema();
$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_GET['action'] ?? '';
  $id = (int)($_GET['id'] ?? 0);

  if ($action === 'delete' && $id > 0) {
    $pdo->prepare("DELETE FROM messages WHERE contact_id = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM contacts WHERE id = ?")->execute([$id]);
    json_response(['success' => true]);
  }

  if ($action === 'block' && $id > 0) {
    $pdo->prepare("UPDATE contacts SET status = 'blocked' WHERE id = ?")->execute([$id]);
    json_response(['success' => true]);
  }

  $input = read_json();
  if (empty($action)) {
    // Handle create/get contact
    $phone = $input['phone'] ?? '';
    if (empty($phone)) json_response(['success' => false, 'error' => 'Missing phone']);
    
    $stmt = $pdo->prepare("SELECT * FROM contacts WHERE phone = ?");
    $stmt->execute([$phone]);
    $contact = $stmt->fetch();
    
    if (!$contact) {
      $stmt = $pdo->prepare("INSERT INTO contacts (phone) VALUES (?)");
      $stmt->execute([$phone]);
      $id = $pdo->lastInsertId();
      $stmt = $pdo->prepare("SELECT * FROM contacts WHERE id = ?");
      $stmt->execute([$id]);
      $contact = $stmt->fetch();
    }
    
    json_response(['success' => true, 'contact' => $contact]);
  }

  if ($action === 'update') {
    $id = (int)($input['id'] ?? 0);
    if ($id <= 0) json_response(['success' => false, 'error' => 'Missing id']);
    $fields = [];
    $params = [];
    foreach (['name', 'tags', 'status'] as $field) {
      if (array_key_exists($field, $input)) {
        $fields[] = "$field = ?";
        $params[] = $input[$field];
      }
    }
    if (!$fields) json_response(['success' => false, 'error' => 'No changes']);
    $params[] = $id;
    $stmt = $pdo->prepare("UPDATE contacts SET " . implode(', ', $fields) . " WHERE id = ?");
    $stmt->execute($params);
    json_response(['success' => true]);
  }

  json_response(['success' => false, 'error' => 'Unknown action']);
}

$sql = "
  SELECT c.id, c.phone, c.name, c.tags, c.status, c.updated_at,
    (SELECT body FROM messages m WHERE m.contact_id = c.id ORDER BY m.created_at DESC LIMIT 1) AS last_message,
    (SELECT created_at FROM messages m WHERE m.contact_id = c.id ORDER BY m.created_at DESC LIMIT 1) AS last_time,
    (SELECT COUNT(*) FROM messages m WHERE m.contact_id = c.id AND m.direction = 'in' AND m.is_read = 0) AS unread_count
  FROM contacts c
  WHERE c.status != 'blocked'
  ORDER BY last_time DESC, c.updated_at DESC
";
$contacts = $pdo->query($sql)->fetchAll();

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