<?php
declare(strict_types=1);

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

ensure_schema();
$pdo = db();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input') ?: '', true);
    $contactName = trim((string)($input['contact_name'] ?? ''));
    $phone = trim((string)($input['phone'] ?? ''));
    $channel = trim((string)($input['channel'] ?? 'twilio'));

    if ($contactName === '' || $phone === '') {
        http_response_code(422);
        echo json_encode(['success' => false, 'error' => 'Contact name and phone are required.']);
        exit;
    }

    $stmt = $pdo->prepare("INSERT INTO conversations (contact_name, phone, channel, created_at) VALUES (?, ?, ?, NOW())");
    $stmt->execute([$contactName, $phone, $channel]);
    $conversationId = (int)$pdo->lastInsertId();

    echo json_encode(['success' => true, 'conversation_id' => $conversationId]);
    exit;
}

$rows = $pdo->query("SELECT * FROM conversations ORDER BY created_at DESC")->fetchAll();
echo json_encode(['success' => true, 'conversations' => $rows]);
