<?php

namespace App\Http\Controllers;

use App\Models\Activity;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ActivityDeliveryController extends Controller
{
    public function open(string $token)
    {
        $activity = Activity::withoutGlobalScopes()->where('tracking_token', $token)->firstOrFail();
        $activity->trackingEvents()->firstOrCreate(['event' => 'opened']);
        $activity->update(['email_status' => 'opened', 'opened_at' => $activity->opened_at ?: now()]);
        $gif = base64_decode('R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==');
        return response($gif, 200, ['Content-Type' => 'image/gif', 'Cache-Control' => 'no-store, no-cache']);
    }

    public function reply(Request $request, string $token)
    {
        $activity = Activity::withoutGlobalScopes()->where('reply_token', $token)->firstOrFail();
        $data = $request->validate(['sender' => 'nullable|email', 'message_id' => 'nullable|string|max:255', 'content' => 'required|string']);
        $activity->trackingEvents()->create(['event' => 'replied'] + $data);
        $activity->update(['email_status' => 'replied', 'replied_at' => now()]);
        return response()->json(['accepted' => true]);
    }

    public function meeting(Activity $activity): View
    {
        abort_unless($activity->business_id === auth()->user()->business_id, 403);
        abort_unless($activity->attendees()->whereKey(auth()->id())->exists(), 403);
        return view('applications.meeting-invitation', compact('activity'));
    }

    public function respond(Request $request, Activity $activity): RedirectResponse
    {
        abort_unless($activity->business_id === auth()->user()->business_id, 403);
        $response = $request->validate(['response' => 'required|in:accepted,declined,tentative'])['response'];
        abort_unless($activity->attendees()->whereKey(auth()->id())->exists(), 403);
        $activity->attendees()->updateExistingPivot(auth()->id(), ['response' => $response]);
        return back()->with('success', 'Meeting response recorded.');
    }
}
