<?php
/**
 * POST /api/checklist/save
 * Receives checklist_results from the strategy panel and persists to DB.
 */
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../src/ScopedDb.php';
require_once __DIR__ . '/../../src/Auth.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

try {
    $dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

$auth = new Auth($pdo);
$userId = $auth->requireAuth();
$db = new ScopedDb($pdo, $userId);

// Read JSON body
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || empty($input['trade_lifecycle_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing trade_lifecycle_id']);
    exit;
}

$tradeLifecycleId = $input['trade_lifecycle_id'];
$strategyVersionId = $input['strategy_version_id'] ?? '';
$itemsTicked = $input['items_ticked'] ?? [];
$itemsRequired = $input['items_required'] ?? [];
$tickedPct = (float)($input['ticked_pct'] ?? 0);
$status = $input['status'] ?? 'pending_calculator';
$tickedAt = $input['ticked_at'] ?? date('Y-m-d H:i:s');
$expiresAt = $input['expires_at'] ?? date('Y-m-d H:i:s', strtotime('+24 hours'));

// Verify strategy_version belongs to this user
if ($strategyVersionId) {
    $existing = $db->selectById('strategy_versions', $strategyVersionId);
    if (!$existing) {
        http_response_code(403);
        echo json_encode(['error' => 'Strategy version not found']);
        exit;
    }
}

// Check if this trade_lifecycle_id already exists (duplicate prevention)
$stmt = $pdo->prepare('SELECT id FROM checklist_results WHERE trade_lifecycle_id = :tid AND user_id = :uid');
$stmt->execute([':tid' => $tradeLifecycleId, ':uid' => $userId]);
if ($stmt->fetch()) {
    // Already saved — return success (idempotent)
    echo json_encode(['success' => true, 'message' => 'Already saved', 'trade_lifecycle_id' => $tradeLifecycleId]);
    exit;
}

// Insert
try {
    $id = $db->insert('checklist_results', [
        'trade_lifecycle_id' => $tradeLifecycleId,
        'strategy_version_id' => $strategyVersionId,
        'items_ticked' => json_encode($itemsTicked),
        'items_required' => json_encode($itemsRequired),
        'ticked_pct' => $tickedPct,
        'status' => $status,
        'ticked_at' => $tickedAt,
        'expires_at' => $expiresAt,
    ]);

    echo json_encode([
        'success' => true,
        'id' => $id,
        'trade_lifecycle_id' => $tradeLifecycleId,
    ]);
} catch (\Throwable $e) {
    error_log('checklist/save.php failed: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Save failed. Please try again.']);
}