<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Appointment;
use App\Models\Patient;
use App\Models\Visit;
use App\Services\Billing\PlatformEmailClient;
use App\Services\Billing\PlatformSmsClient;
use App\Services\Care\AuditLogger;
use App\Services\Care\OrganizationResolver;
use App\Services\Messaging\CustomerEmailClient;
use App\Services\Messaging\CustomerSmsClient;
use App\Services\Messaging\MessagingCredentialsService;
use App\Support\OrganizationBranding;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class PatientMessageController extends Controller
{
    use ScopesToAccount;

    public function sendEmail(
        Request $request,
        Patient $patient,
        MessagingCredentialsService $credentials,
        CustomerEmailClient $email,
        PlatformEmailClient $platformEmail,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'patients.manage');
        $this->authorizePatient($request, $patient);

        if (! filter_var((string) $patient->email, FILTER_VALIDATE_EMAIL)) {
            return back()->with('error', 'This patient has no valid email on file.');
        }

        $data = $request->validate([
            'subject' => ['required', 'string', 'max:200'],
            'body' => ['required', 'string', 'max:5000'],
        ]);

        $owner = $this->ownerRef($request);
        $organization = $this->organization($request);
        $html = OrganizationBranding::wrapEmailHtml(nl2br(e($data['body'])), $organization);
        // Patient-facing From display name is the clinic/company, never the Ladill product.
        $fromName = trim((string) $organization->name) ?: null;

        $sent = false;
        $error = null;
        $via = null;

        if ($platformEmail->isConfigured()) {
            $sent = $platformEmail->send(
                $owner,
                (string) $patient->email,
                $data['subject'],
                $html,
                $data['body'],
                $fromName,
            );
            $via = 'suite';
            if (! $sent) {
                $error = $platformEmail->lastError();
            }
        }

        if (! $sent) {
            $credential = $credentials->forOrganization($organization);
            if ($credential->hasValidBird() && ($apiKey = $credential->birdApiKey())) {
                $sent = $email->send(
                    $apiKey,
                    (string) $credential->bird_from_email,
                    $credential->bird_from_name ?: $fromName,
                    (string) $patient->email,
                    $data['subject'],
                    $html,
                    $data['body'],
                );
                $via = 'bird';
                if (! $sent) {
                    $error = $email->lastError() ?: $error;
                }
            } elseif (! $platformEmail->isConfigured()) {
                $error = 'Set a Ladill mailbox in Account → Messaging, or connect Ladill Bird in Integrations.';
            }
        }

        AuditLogger::record(
            $owner,
            $sent ? 'patient.email_sent' : 'patient.email_failed',
            $patient->organization_id,
            $owner,
            Patient::class,
            $patient->id,
            [
                'to' => $patient->email,
                'subject' => $data['subject'],
                'via' => $via,
                'error' => $sent ? null : $error,
            ],
        );

        if (! $sent) {
            return back()->with('error', $error ?: 'Email could not be sent.');
        }

        return back()->with('success', 'Email sent to '.$patient->email);
    }

    public function sendSms(
        Request $request,
        Patient $patient,
        MessagingCredentialsService $credentials,
        CustomerSmsClient $sms,
        PlatformSmsClient $platformSms,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'patients.manage');
        $this->authorizePatient($request, $patient);

        if (trim((string) $patient->phone) === '') {
            return back()->with('error', 'This patient has no phone number on file.');
        }

        $data = $request->validate([
            'message' => ['required', 'string', 'max:480'],
        ]);

        $owner = $this->ownerRef($request);
        $organization = $this->organization($request);
        $credential = $credentials->forOrganization($organization);

        $sent = false;
        $error = null;

        if ($platformSms->isConfigured()) {
            $sender = $credential->sms_sender_id ?: null;
            $sent = $platformSms->send($owner, (string) $patient->phone, $data['message'], $sender ? (string) $sender : null);
            if (! $sent) {
                $error = $platformSms->lastError();
            }
        }

        if (! $sent && $credential->hasValidSms() && ($apiKey = $credential->smsApiKey())) {
            $sent = $sms->send($apiKey, (string) $patient->phone, $data['message'], (string) $credential->sms_sender_id);
            if (! $sent) {
                $error = $sms->lastError() ?? $error;
            }
        } elseif (! $sent && ! $platformSms->isConfigured()) {
            $error = 'Connect Ladill SMS in Integrations, or ensure platform SMS is configured (SMS_API_KEY_CARE).';
        }


        AuditLogger::record(
            $owner,
            $sent ? 'patient.sms_sent' : 'patient.sms_failed',
            $patient->organization_id,
            $owner,
            Patient::class,
            $patient->id,
            [
                'to' => $patient->phone,
                'error' => $sent ? null : $error,
            ],
        );

        if (! $sent) {
            return back()->with('error', $error ?: 'SMS could not be sent.');
        }

        return back()->with('success', 'SMS sent to '.$patient->phone);
    }

    protected function authorizePatient(Request $request, Patient $patient): void
    {
        $this->authorizeOwner($request, $patient);
        abort_unless($patient->organization_id === $this->organization($request)->id, 404);

        $branchId = app(OrganizationResolver::class)->branchScope($this->member($request));
        if ($branchId === null || $patient->branch_id === $branchId) {
            return;
        }

        $hasLocalActivity = Visit::query()
            ->where('patient_id', $patient->id)
            ->where('organization_id', $patient->organization_id)
            ->where('branch_id', $branchId)
            ->exists()
            || Appointment::query()
                ->where('patient_id', $patient->id)
                ->where('organization_id', $patient->organization_id)
                ->where('branch_id', $branchId)
                ->exists();

        abort_unless($hasLocalActivity, 404);
    }
}
