<?php

namespace App\Services;

use App\Models\User;
use App\Models\Assignment;
use App\Models\SystemSetting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppService
{
    /**
     * Send WhatsApp message via Wasender API.
     */
    public function sendMessage(User $user, string $message, ?Assignment $assignment = null): bool
    {
        // Check if user has verified phone number
        if (!$user->phone) {
            return false;
        }

        // Check if user can receive WhatsApp notifications
        if (!$user->canReceiveAutomatedFeatures()) {
            return false;
        }

        // Check if WhatsApp is enabled globally
        $whatsappEnabled = SystemSetting::get('whatsapp_enabled', true);
        if (!$whatsappEnabled) {
            Log::info('WhatsApp notifications are disabled globally');
            return false;
        }

        // Get API credentials from system settings (admin-managed) or fall back to config
        $apiKey = SystemSetting::get('wasender_api_key') ?: config('services.wasender.api_key');
        $apiUrl = SystemSetting::get('wasender_api_url') ?: config('services.wasender.api_url', 'https://api.wasender.com/api/send');

        if (!$apiKey) {
            Log::warning('Wasender API key not configured');
            return false;
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json',
            ])->post($apiUrl, [
                'phone' => $user->phone,
                'message' => $message,
            ]);

            if ($response->successful()) {
                // Mark notification as WhatsApp sent if assignment exists
                if ($assignment) {
                    $assignment->notifications()
                        ->where('type', 'in', ['due_date_approaching', 'overdue'])
                        ->latest()
                        ->first()?->update(['whatsapp_sent' => true]);
                }

                return true;
            }

            Log::error('Wasender API error', [
                'status' => $response->status(),
                'body' => $response->body(),
            ]);

            return false;
        } catch (\Exception $e) {
            Log::error('WhatsApp send error', [
                'message' => $e->getMessage(),
                'user_id' => $user->id,
            ]);

            return false;
        }
    }

    /**
     * Send due date approaching WhatsApp message.
     */
    public function sendDueDateApproaching(Assignment $assignment): bool
    {
        $message = "📚 Assignment Reminder\n\n";
        $message .= "Your assignment '{$assignment->assignment_title}' is due on {$assignment->due_date->format('M d, Y')}.\n";
        $message .= "Module: {$assignment->module_name}\n";
        $message .= "Don't forget to complete it!";

        return $this->sendMessage($assignment->user, $message, $assignment);
    }

    /**
     * Send overdue assignment WhatsApp message.
     */
    public function sendOverdue(Assignment $assignment): bool
    {
        $daysOverdue = now()->diffInDays($assignment->due_date);
        
        $message = "⚠️ Assignment Overdue\n\n";
        $message .= "Your assignment '{$assignment->assignment_title}' is {$daysOverdue} day(s) overdue.\n";
        $message .= "Module: {$assignment->module_name}\n";
        $message .= "Please complete it as soon as possible!";

        return $this->sendMessage($assignment->user, $message, $assignment);
    }
}
