<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use App\Http\Requests\SimulateClickRequest;
use Illuminate\Support\Facades\DB;

class SimulateController extends Controller
{
    public function click(SimulateClickRequest $request): JsonResponse
    {
        // Mark opened_at (if not set) and clicked_cta_at for a push_log
        $id = $request->validated()['id'];
        $now = now();
        $row = DB::table('push_logs')->where('id', $id)->first();
        if ($row && !$row->opened_at) {
            DB::table('push_logs')->where('id', $id)->update(['opened_at' => $now, 'updated_at' => $now]);
            try { \App\Services\Analytics\EventBus::track($row->user_id, 'PushOpen', ['campaign_id' => $row->campaign_id]); } catch (\Throwable) {}
        }
        DB::table('push_logs')->where('id', $id)
            ->update(['clicked_cta_at' => $now, 'updated_at' => $now]);
        // Also track a view/call intent from the card click
        try {
            if ($row) {
                \App\Services\Analytics\EventBus::track($row->user_id, 'ViewDeal', ['campaign_id' => $row->campaign_id]);
                \App\Services\Analytics\EventBus::track($row->user_id, 'CallFromCard', ['campaign_id' => $row->campaign_id]);
            }
        } catch (\Throwable) {}
        return response()->json(['ok' => true]);
    }
}
