<?php
declare(strict_types=1);

require_once __DIR__ . '/../db/config.php';

function json_response(array $payload): void {
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($payload, JSON_UNESCAPED_UNICODE);
  exit;
}

function ensure_schema(): void {
  static $done = false;
  if ($done) return;
  $pdo = db();

  $pdo->exec("
    CREATE TABLE IF NOT EXISTS contacts (
      id INT AUTO_INCREMENT PRIMARY KEY,
      phone VARCHAR(32) NOT NULL UNIQUE,
      name VARCHAR(64) NULL,
      tags VARCHAR(255) NULL,
      status ENUM('normal','blocked') DEFAULT 'normal',
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )
  ");

  $pdo->exec("
    CREATE TABLE IF NOT EXISTS messages (
      id INT AUTO_INCREMENT PRIMARY KEY,
      contact_id INT NOT NULL,
      direction ENUM('in','out') NOT NULL DEFAULT 'out',
      body TEXT NOT NULL,
      is_read TINYINT(1) DEFAULT 0,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (contact_id) REFERENCES contacts(id)
    )
  ");

  $pdo->exec("
    CREATE TABLE IF NOT EXISTS settings (
      id INT AUTO_INCREMENT PRIMARY KEY,
      category VARCHAR(32) NOT NULL,
      name VARCHAR(64) NOT NULL,
      value TEXT NULL,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      UNIQUE KEY unique_setting (category, name)
    )
  ");

  $pdo->exec("
    CREATE TABLE IF NOT EXISTS auto_reply (
      id INT AUTO_INCREMENT PRIMARY KEY,
      keyword VARCHAR(120) NOT NULL,
      reply TEXT NOT NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  ");

  $count = (int)$pdo->query("SELECT COUNT(*) FROM contacts")->fetchColumn();
  if ($count === 0) {
    $stmt = $pdo->prepare("INSERT INTO contacts (phone, name, tags, status) VALUES (?, ?, ?, ?)");
    $stmt->execute(['+86 138 0013 8000', '华北客户', 'VIP,续费', 'normal']);
    $stmt->execute(['+86 139 0009 1212', '深圳客户', '新线索', 'normal']);
    $stmt->execute(['+1 415 555 0198', '海外客户', '海外', 'normal']);

    $contacts = $pdo->query("SELECT id, phone FROM contacts")->fetchAll();
    $msgStmt = $pdo->prepare("INSERT INTO messages (contact_id, direction, body, is_read, created_at) VALUES (?, ?, ?, ?, ?)");
    foreach ($contacts as $contact) {
      $msgStmt->execute([$contact['id'], 'in', '您好，我想了解套餐价格。', 0, date('Y-m-d H:i:s', strtotime('-2 hours'))]);
      $msgStmt->execute([$contact['id'], 'out', '您好，这里是客服，请问您关注哪种短信套餐？', 1, date('Y-m-d H:i:s', strtotime('-90 minutes'))]);
    }
  }

  $done = true;
}

function read_json(): array {
  $raw = file_get_contents('php://input');
  $data = json_decode($raw, true);
  if (is_array($data)) return $data;
  return $_POST ?? [];
}
