<?php

namespace App\Services;

use App\Models\Estimate;
use App\Models\JobCard;
use App\Models\WorkOrder;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class NotificationService
{
    /**
     * Send estimate to customer via email and SMS
     */
    public function sendEstimateToCustomer(Estimate $estimate): void
    {
        try {
            $jobCard = $estimate->jobCard;
            $customer = $jobCard->customer;

            // Send email
            if ($customer->email) {
                Mail::to($customer->email)->send(new \App\Mail\EstimateNotification($estimate));
                $estimate->update(['email_sent_at' => now()]);
            }

            // Send SMS
            if ($customer->phone) {
                $this->sendSMS(
                    $customer->phone,
                    "Your vehicle estimate #{$estimate->estimate_number} is ready. Please check your email or visit our customer portal to review and approve."
                );
                $estimate->update(['sms_sent_at' => now()]);
            }

            $estimate->update([
                'sent_to_customer_at' => now(),
                'status' => 'sent'
            ]);

        } catch (\Exception $e) {
            Log::error('Failed to send estimate notification: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * Notify team when estimate is approved
     */
    public function notifyEstimateApproved(Estimate $estimate): void
    {
        $jobCard = $estimate->jobCard;
        
        // Notify Service Supervisor
        $serviceSupervisors = User::where('role', 'service_supervisor')
            ->where('branch_code', $jobCard->branch_code)
            ->get();
        
        foreach ($serviceSupervisors as $supervisor) {
            $this->sendInternalNotification(
                $supervisor,
                'Estimate Approved',
                "Estimate #{$estimate->estimate_number} for job card {$jobCard->job_card_number} has been approved by the customer."
            );
        }

        // Notify Service Coordinator
        if ($estimate->diagnosis && $estimate->diagnosis->serviceCoordinator) {
            $this->sendInternalNotification(
                $estimate->diagnosis->serviceCoordinator,
                'Estimate Approved',
                "Your estimate #{$estimate->estimate_number} has been approved. You can now proceed with work order creation."
            );
        }

        // Notify Parts Manager
        $partsManagers = User::where('role', 'parts_manager')
            ->where('branch_code', $jobCard->branch_code)
            ->get();
        
        foreach ($partsManagers as $manager) {
            $this->sendInternalNotification(
                $manager,
                'Parts Required',
                "Estimate #{$estimate->estimate_number} approved. Please prepare parts for job card {$jobCard->job_card_number}."
            );
        }
    }

    /**
     * Notify when vehicle is ready for pickup
     */
    public function notifyVehicleReady(JobCard $jobCard): void
    {
        $customer = $jobCard->customer;

        try {
            // Send email
            if ($customer->email) {
                Mail::to($customer->email)->send(new \App\Mail\VehicleReadyNotification($jobCard));
            }

            // Send SMS
            if ($customer->phone) {
                $this->sendSMS(
                    $customer->phone,
                    "Good news! Your {$jobCard->vehicle->display_name} is ready for pickup. Job Card: {$jobCard->job_card_number}"
                );
            }

        } catch (\Exception $e) {
            Log::error('Failed to send vehicle ready notification: ' . $e->getMessage());
        }
    }

    /**
     * Send quality check alert if inspections don't match
     */
    public function sendQualityAlert(JobCard $jobCard, array $discrepancies): void
    {
        $serviceSupervisors = User::where('role', 'service_supervisor')
            ->where('branch_code', $jobCard->branch_code)
            ->get();

        $message = "QUALITY ALERT: Incoming and outgoing inspections for job card {$jobCard->job_card_number} do not match. Immediate review required.";

        foreach ($serviceSupervisors as $supervisor) {
            $this->sendInternalNotification($supervisor, 'Quality Alert', $message);
        }
    }

    /**
     * Send internal notification to user
     */
    private function sendInternalNotification(User $user, string $subject, string $message): void
    {
        // This can be enhanced with real-time notifications, push notifications, etc.
        try {
            if ($user->email) {
                Mail::to($user->email)->send(new \App\Mail\InternalNotification($subject, $message));
            }
        } catch (\Exception $e) {
            Log::error('Failed to send internal notification: ' . $e->getMessage());
        }
    }

    /**
     * Send SMS (placeholder - integrate with your SMS provider)
     */
    private function sendSMS(string $phoneNumber, string $message): void
    {
        // Integrate with SMS service provider (Twilio, AWS SNS, etc.)
        Log::info("SMS to {$phoneNumber}: {$message}");
        
        // Example with a generic SMS service
        // SMSService::send($phoneNumber, $message);
    }
}
