<?php

namespace App\Http\Controllers;

use App\Models\ReminderLog;
use App\Services\ReminderService;
use Illuminate\Http\Request;

class ReminderLogController extends Controller
{
    protected $reminderService;

    public function __construct(ReminderService $reminderService)
    {
        $this->reminderService = $reminderService;
    }

    public function index()
    {
        $logs = ReminderLog::with('employee')
            ->latest()
            ->paginate(50);

        $stats = [
            'total_sent' => ReminderLog::where('status', 'sent')->count(),
            'total_failed' => ReminderLog::where('status', 'failed')->count(),
            'sent_today' => ReminderLog::where('status', 'sent')
                ->whereDate('created_at', today())
                ->count(),
        ];

        return view('reminders.index', compact('logs', 'stats'));
    }

    // Resend failed reminder
    public function resend(ReminderLog $reminderLog)
    {
        if ($reminderLog->status !== 'failed') {
            return back()->with('error', 'Hanya reminder yang gagal bisa dikirim ulang.');
        }

        $success = $this->reminderService->resendReminder($reminderLog);

        if ($success) {
            return back()->with('success', 'Reminder berhasil dikirim ulang.');
        }

        return back()->with('error', 'Gagal mengirim ulang reminder.');
    }

    // Test send reminder (untuk testing)
    public function testSend(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'type' => 'required|in:email,telegram,both'
        ]);

        $result = $this->reminderService->sendTestNotification(
            $request->email,
            $request->type
        );

        return $this->successResponse(['sent' => $result]);
    }

    // API: Get recent logs
    public function getRecentApi()
    {
        $logs = ReminderLog::with('employee')
            ->latest()
            ->take(20)
            ->get();

        return $this->successResponse($logs);
    }
}