<?php

namespace App\Services;

use App\Models\Application;
use App\Models\NotificationTemplate;
use Illuminate\Support\Facades\Log;

class NotificationService
{
    protected SmsService $sms;
    protected WhatsAppService $whatsapp;

    public function __construct(SmsService $sms, WhatsAppService $whatsapp)
    {
        $this->sms = $sms;
        $this->whatsapp = $whatsapp;
    }

    /**
     * Notify candidate of an event using SMS & WhatsApp template rendering.
     */
    public function notifyCandidate(Application $application, string $eventKey, array $extras = []): void
    {
        $template = NotificationTemplate::where('event_key', $eventKey)->first();

        if (!$template) {
            Log::warning("Notification template not found for event: {$eventKey}");
            return;
        }

        // Prepare placeholder replacements
        $replacements = [
            '{name}' => $application->full_name,
            '{job_title}' => $application->jobListing->title,
            '{app_number}' => $application->application_number,
            '{status_url}' => $application->status_url,
            '{stage_name}' => $extras['stage_name'] ?? ($application->currentStage->name ?? ''),
            '{scheduled_at}' => $extras['scheduled_at'] ?? '',
            '{type}' => $extras['type'] ?? '',
            '{details}' => $extras['details'] ?? '',
        ];

        // Replace placeholders in bodies
        $smsBody = str_replace(array_keys($replacements), array_values($replacements), $template->sms_body);
        $whatsappBody = str_replace(array_keys($replacements), array_values($replacements), $template->whatsapp_body);

        // Send SMS
        try {
            $this->sms->send($application->phone, $smsBody, $application->id);
        } catch (\Exception $e) {
            Log::error("Failed to send candidate SMS: " . $e->getMessage());
        }

        // Send WhatsApp
        try {
            $this->whatsapp->send($application->phone, $whatsappBody, $application->id);
        } catch (\Exception $e) {
            Log::error("Failed to send candidate WhatsApp: " . $e->getMessage());
        }
    }

    /**
     * Notify the recruitment/hiring team of an event.
     */
    public function notifyTeam(string $event, Application $application): void
    {
        Log::info("Team notification event [{$event}] fired for Application: {$application->application_number}");
        // Here we could implement emails/slack integrations to hiring manager/HR if needed.
    }
}
