<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Applicant;
use App\Models\MessageTemplate;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Process;

class SendMessageController extends Controller
{
    public function index()
    {
        $templates = MessageTemplate::orderBy('id')->get();

        $config = [
            'smtp' => [
                'host' => config('mail.mailers.smtp.host'),
                'port' => config('mail.mailers.smtp.port'),
                'encryption' => config('mail.mailers.smtp.encryption'),
                'username' => config('mail.mailers.smtp.username'),
                'from_address' => config('mail.from.address'),
                'from_name' => config('mail.from.name'),
                'has_password' => !empty(config('mail.mailers.smtp.password')),
            ],
            'fonnte' => [
                'has_key' => !empty(Setting::get('fonnte_api_key', config('services.fonnte.key'))),
                'key_source' => Setting::get('fonnte_api_key') ? 'database' : (config('services.fonnte.key') ? '.env' : 'tidak ada'),
            ],
        ];

        $availableVariables = [
            'applicant_name' => 'Nama pelamar',
            'applicant_email' => 'Email pelamar',
            'applicant_phone' => 'No. HP pelamar',
            'job_title' => 'Judul lowongan',
            'company' => 'Nama perusahaan',
            'stage_name' => 'Nama tahapan',
            'site_name' => 'Nama situs',
            'site_url' => 'URL situs',
        ];

        return view('admin.send-message', compact('templates', 'config', 'availableVariables'));
    }

    public function sendEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'subject' => 'required|string|max:255',
            'message' => 'required|string',
        ]);

        $result = ['success' => false, 'message' => ''];

        try {
            $siteName = Setting::get('site_name', 'Bursa Kerja');
            $htmlContent = $this->buildEmailHtml($request->subject, $request->message, $siteName);

            Mail::html($htmlContent, function ($mail) use ($request) {
                $mail->to($request->email)
                     ->subject($request->subject);
            });

            $result['success'] = true;
            $result['message'] = "Email berhasil dikirim ke {$request->email}";
        } catch (\Exception $e) {
            $result['message'] = 'Gagal mengirim email: ' . $e->getMessage();
            Log::error('Send email failed: ' . $e->getMessage());
        }

        return response()->json($result);
    }

    public function sendWhatsApp(Request $request)
    {
        $request->validate([
            'phone' => 'required|string',
            'message' => 'required|string',
        ]);

        $result = ['success' => false, 'message' => ''];
        $apiKey = Setting::get('fonnte_api_key', config('services.fonnte.key'));

        if (!$apiKey) {
            $result['message'] = 'Fonnte API key belum dikonfigurasi';
            return response()->json($result);
        }

        try {
            $phone = preg_replace('/[^0-9]/', '', $request->phone);

            $response = Http::withHeaders([
                'Authorization' => $apiKey,
            ])->post('https://api.fonnte.com/send', [
                'target' => $phone,
                'message' => $request->message,
                'countryCode' => '62',
            ]);

            if ($response->successful() && $response->json('status')) {
                $result['success'] = true;
                $result['message'] = "WhatsApp berhasil dikirim ke {$phone}";
            } else {
                $result['message'] = 'Fonnte API error: ' . ($response->json('reason') ?? $response->body());
            }
        } catch (\Exception $e) {
            $result['message'] = 'Gagal mengirim WhatsApp: ' . $e->getMessage();
            Log::error('Send WhatsApp failed: ' . $e->getMessage());
        }

        return response()->json($result);
    }

    public function testSmtp()
    {
        $result = ['success' => false, 'message' => '', 'debug' => []];

        $host = config('mail.mailers.smtp.host');
        $port = config('mail.mailers.smtp.port');
        $encryption = config('mail.mailers.smtp.encryption');

        $result['debug'] = [
            'host' => $host,
            'port' => $port,
            'encryption' => $encryption,
            'username' => config('mail.mailers.smtp.username'),
            'has_password' => !empty(config('mail.mailers.smtp.password')),
        ];

        if (!$host || !$port) {
            $result['message'] = 'SMTP host atau port belum dikonfigurasi';
            return response()->json($result);
        }

        try {
            $errno = 0;
            $errstr = '';
            $prefix = $encryption === 'ssl' ? 'ssl://' : '';
            $connection = @fsockopen($prefix . $host, (int) $port, $errno, $errstr, 10);

            if ($connection) {
                $response = fgets($connection, 512);
                fclose($connection);
                $result['success'] = true;
                $result['message'] = "Koneksi ke SMTP {$host}:{$port} berhasil";
                $result['debug']['smtp_banner'] = trim($response);
            } else {
                $result['message'] = "Gagal konek ke {$host}:{$port} — {$errstr}";
            }
        } catch (\Exception $e) {
            $result['message'] = 'Error: ' . $e->getMessage();
        }

        return response()->json($result);
    }

    public function testFonnte()
    {
        $result = ['success' => false, 'message' => '', 'debug' => []];
        $apiKey = Setting::get('fonnte_api_key', config('services.fonnte.key'));

        if (!$apiKey) {
            $result['message'] = 'Fonnte API key belum dikonfigurasi';
            return response()->json($result);
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => $apiKey,
            ])->post('https://api.fonnte.com/device');

            $result['debug']['http_status'] = $response->status();

            if ($response->successful()) {
                $result['success'] = true;
                $result['message'] = 'Fonnte API key valid, device terhubung';
            } else {
                $result['message'] = 'Fonnte API key invalid atau device offline';
            }
        } catch (\Exception $e) {
            $result['message'] = 'Error: ' . $e->getMessage();
        }

        return response()->json($result);
    }

    private function buildEmailHtml(string $subject, string $body, string $siteName): string
    {
        return <<<HTML
        <!DOCTYPE html>
        <html>
        <head><meta charset="utf-8"></head>
        <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; background: #f5f5f5;">
            <div style="background: white; border-radius: 10px; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <div style="text-align: center; margin-bottom: 20px;">
                    <h2 style="color: #4F46E5; margin: 0;">{$siteName}</h2>
                </div>
                <hr style="border: none; border-top: 2px solid #E5E7EB; margin: 20px 0;">
                <h3 style="color: #1F2937;">{$subject}</h3>
                <div style="background: #F9FAFB; border-radius: 8px; padding: 15px; margin: 15px 0; line-height: 1.6;">
                    {$body}
                </div>
                <hr style="border: none; border-top: 1px solid #E5E7EB; margin: 20px 0;">
                <p style="color: #6B7280; font-size: 12px; text-align: center;">
                    Email ini dikirim oleh {$siteName}
                </p>
            </div>
        </body>
        </html>
        HTML;
    }

    /**
     * Broadcast email to all applicants (queued in background via artisan command)
     */
    public function broadcastEmail(Request $request)
    {
        $request->validate([
            'subject' => 'required|string|max:255',
            'message' => 'required|string',
        ]);

        $applicants = Applicant::whereNotNull('email')->get();

        if ($applicants->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak ada pelamar dengan email',
            ]);
        }

        $siteName = Setting::get('site_name', 'Bursa Kerja');
        $siteUrl = config('app.url');

        // Store broadcast data in cache for background processing
        $broadcastId = uniqid('email_broadcast_');

        $broadcastData = $applicants->map(function ($applicant) use ($request, $siteName, $siteUrl) {
            $variables = [
                'applicant_name' => $applicant->name,
                'applicant_email' => $applicant->email,
                'applicant_phone' => $applicant->whatsapp ?? '',
                'site_name' => $siteName,
                'site_url' => $siteUrl,
            ];
            return [
                'email' => $applicant->email,
                'name' => $applicant->name,
                'subject' => MessageTemplate::render($request->subject, $variables),
                'message' => MessageTemplate::render($request->message, $variables),
            ];
        })->toArray();

        cache([$broadcastId => $broadcastData], now()->addHours(1));

        // Run broadcast in background via artisan command
        $artisan = base_path('artisan');
        Process::path(base_path())->start("php {$artisan} broadcast:email {$broadcastId}");

        return response()->json([
            'success' => true,
            'message' => "Broadcast Email ke " . $applicants->count() . " pelamar sedang diproses di background.",
        ]);
    }

    /**
     * Broadcast WhatsApp to all applicants (queued in background via artisan command)
     */
    public function broadcastWhatsApp(Request $request)
    {
        $request->validate([
            'message' => 'required|string',
        ]);

        $applicants = Applicant::whereNotNull('whatsapp')->where('whatsapp', '!=', '')->get();
        $apiKey = Setting::get('fonnte_api_key', config('services.fonnte.key'));

        if (!$apiKey) {
            return response()->json([
                'success' => false,
                'message' => 'Fonnte API key belum dikonfigurasi',
            ]);
        }

        if ($applicants->isEmpty()) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak ada pelamar dengan nomor WhatsApp',
            ]);
        }

        // Store broadcast data in cache for background processing
        $broadcastId = uniqid('wa_broadcast_');
        $siteName = Setting::get('site_name', 'Bursa Kerja');
        $siteUrl = config('app.url');

        $broadcastData = $applicants->map(function ($applicant) use ($request, $siteName, $siteUrl) {
            $variables = [
                'applicant_name' => $applicant->name,
                'applicant_email' => $applicant->email,
                'applicant_phone' => $applicant->whatsapp,
                'site_name' => $siteName,
                'site_url' => $siteUrl,
            ];
            return [
                'phone' => preg_replace('/[^0-9]/', '', $applicant->whatsapp),
                'message' => MessageTemplate::render($request->message, $variables),
            ];
        })->toArray();

        cache([$broadcastId => $broadcastData], now()->addHours(1));

        // Run broadcast in background via artisan command
        $artisan = base_path('artisan');
        Process::path(base_path())->start("php {$artisan} broadcast:whatsapp {$broadcastId}");

        return response()->json([
            'success' => true,
            'message' => "Broadcast WhatsApp ke " . $applicants->count() . " pelamar sedang diproses di background.",
        ]);
    }
}
