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

// Support GET (list/detail), POST (create), PATCH (rename), DELETE (remove)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    hw_json(['ok' => true]);
}

$auth = hw_auth_user();
if (!$auth) hw_json(['message' => 'Authentication required'], 401);

$uid = (int)($auth['sub'] ?? 0);
$pdo = hw_db();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : null;
    if ($id) {
        $stmt = $pdo->prepare('SELECT id, title, messages, consent, created_at FROM ai_conversations WHERE id = ? AND user_id = ? LIMIT 1');
        $stmt->execute([$id, $uid]);
        $row = $stmt->fetch();
        if (!$row) hw_json(['message' => 'Not found'], 404);
        $row['messages'] = json_decode($row['messages'] ?? '[]', true) ?: [];
        hw_json(['conversation' => $row]);
    }
    // list last 20 conversations for user
    $stmt = $pdo->prepare('SELECT id, title, consent, created_at FROM ai_conversations WHERE user_id = ? ORDER BY created_at DESC LIMIT 20');
    $stmt->execute([$uid]);
    $rows = $stmt->fetchAll();
    hw_json(['conversations' => $rows]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = hw_input_json();
    $consent = (bool)($data['consent'] ?? false);
    $title = trim((string)($data['title'] ?? '')) ?: null;
    $messages = $data['messages'] ?? [];
    if (!is_array($messages) || count($messages) === 0) hw_json(['message' => 'Messages required'], 422);

    if (!$consent) {
        // Do not persist without consent — return success but no storage
        hw_json(['message' => 'Not saved (no consent)'], 200);
    }

    $stmt = $pdo->prepare('INSERT INTO ai_conversations (user_id, title, messages, consent) VALUES (?, ?, ?, ?)');
    $stmt->execute([$uid, $title, json_encode($messages, JSON_UNESCAPED_SLASHES), (int)$consent]);
    $id = (int)$pdo->lastInsertId();

    hw_json(['message' => 'Saved', 'id' => $id]);
}

if (in_array($_SERVER['REQUEST_METHOD'], ['PATCH','PUT'], true)) {
    // Update title (rename) — id via query param or body
    $id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0);
    $data = hw_input_json();
    if (!$id || !isset($data['title'])) hw_json(['message' => 'Missing id or title'], 422);
    $title = trim((string)$data['title']);
    $stmt = $pdo->prepare('UPDATE ai_conversations SET title = ? WHERE id = ? AND user_id = ?');
    $stmt->execute([$title, $id, $uid]);
    if ($stmt->rowCount() === 0) hw_json(['message' => 'Not found or no change'], 404);
    hw_json(['message' => 'Updated']);
}

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : null;
    if (!$id) {
        $data = hw_input_json();
        $id = (int)($data['id'] ?? 0);
    }
    if (!$id) hw_json(['message' => 'Missing id'], 422);
    $stmt = $pdo->prepare('DELETE FROM ai_conversations WHERE id = ? AND user_id = ?');
    $stmt->execute([$id, $uid]);
    if ($stmt->rowCount() === 0) hw_json(['message' => 'Not found'], 404);
    hw_json(['message' => 'Deleted']);
}

hw_json(['message' => 'Method not allowed'], 405);
