<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\Pelanggan;
use App\Models\Invoice;
use App\Models\Perusahaan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\PesanTemplate;
use App\Models\WhatsappGateway;
use App\Models\User;
use Illuminate\Support\Facades\Http;

class CustomerController extends Controller
{
    /**
     * Tampilkan halaman login pelanggan
     */
    public function showLogin()
    {
        return view('customer.auth.login');
    }

    /**
     * Proses login pelanggan
     */
    public function login(Request $request)
    {
        $request->validate([
            'no_hp_whatsapp' => 'required|string',
            'password' => 'required|string',
        ], [
            'no_hp_whatsapp.required' => 'Nomor WhatsApp wajib diisi',
            'password.required' => 'Password wajib diisi',
        ]);

        // Cari pelanggan berdasarkan nomor WhatsApp
        $pelanggan = Pelanggan::where('no_hp_whatsapp', $request->no_hp_whatsapp)->first();

        if (!$pelanggan) {
            return back()->withErrors([
                'no_hp_whatsapp' => 'Nomor WhatsApp tidak terdaftar.',
            ])->withInput();
        }

        // Password default adalah nomor layanan
        if ($request->password !== $pelanggan->nomer_layanan) {
            return back()->withErrors([
                'password' => 'Password salah. Gunakan nomor layanan Anda.',
            ])->withInput();
        }

        // Set session untuk pelanggan
        session([
            'customer_id' => $pelanggan->id,
            'customer_data' => $pelanggan
        ]);

        return redirect()->route('customer.dashboard');
    }

    /**
     * Generate password default untuk pelanggan
     * (Tidak digunakan lagi, password langsung nomor layanan)
     */
    private function generateDefaultPassword($pelanggan)
    {
        return $pelanggan->nomer_layanan;
    }

    /**
     * Dashboard utama pelanggan
     */
    public function dashboard()
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $pelanggan = Pelanggan::with(['coverageArea', 'mikrotik', 'topOdp'])
                             ->find(session('customer_id'));

        if (!$pelanggan) {
            session()->forget(['customer_id', 'customer_data']);
            return redirect()->route('customer.login');
        }

        // Ambil invoice terbaru
        $latestInvoice = $pelanggan->invoices()
                                 ->orderBy('created_at', 'desc')
                                 ->first();

        // Ambil invoice yang belum dibayar
        $unpaidInvoices = $pelanggan->unpaidInvoices()
                                  ->orderBy('tanggal_jatuh_tempo', 'asc')
                                  ->get();

        // Ambil riwayat pembayaran (invoice yang sudah dibayar)
        $paidInvoices = $pelanggan->paidInvoices()
                                ->orderBy('tanggal_bayar', 'desc')
                                ->limit(5)
                                ->get();

        // Status koneksi (untuk sementara dummy data, bisa diintegrasikan dengan Mikrotik)
        $connectionStatus = $this->getConnectionStatus($pelanggan);

        $data = [
            'pelanggan' => $pelanggan,
            'latestInvoice' => $latestInvoice,
            'unpaidInvoices' => $unpaidInvoices,
            'paidInvoices' => $paidInvoices,
            'connectionStatus' => $connectionStatus,
            'totalUnpaid' => $unpaidInvoices->sum('total_amount'),
            'totalPaid' => $paidInvoices->sum('total_amount'),
        ];

        return view('customer.dashboard', $data);
    }

    /**
     * Halaman detail koneksi
     */
    public function connection()
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $pelanggan = Pelanggan::with(['coverageArea', 'mikrotik', 'topOdp'])
                             ->find(session('customer_id'));

        $connectionStatus = $this->getConnectionStatus($pelanggan);
        $connectionDetails = $this->getConnectionDetails($pelanggan);

        return view('customer.connection', [
            'pelanggan' => $pelanggan,
            'connectionStatus' => $connectionStatus,
            'connectionDetails' => $connectionDetails
        ]);
    }

    /**
     * Halaman invoice pelanggan
     */
    public function invoices()
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $pelanggan = Pelanggan::find(session('customer_id'));
        
        $invoices = $pelanggan->invoices()
                            ->with('templateInvoice')
                            ->orderBy('created_at', 'desc')
                            ->paginate(10);

        return view('customer.invoices', [
            'pelanggan' => $pelanggan,
            'invoices' => $invoices
        ]);
    }

    /**
     * Detail invoice
     */
    public function invoiceDetail($id)
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $pelanggan = Pelanggan::find(session('customer_id'));
        $invoice = $pelanggan->invoices()->with('templateInvoice')->findOrFail($id);

        return view('customer.invoice-detail', [
            'pelanggan' => $pelanggan,
            'invoice' => $invoice
        ]);
    }

    /**
     * Halaman pembayaran
     */
    public function payment($invoiceId)
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $pelanggan = Pelanggan::find(session('customer_id'));
        $invoice = $pelanggan->invoices()->where('status', '!=', 'paid')->findOrFail($invoiceId);
        
        // Ambil data perusahaan untuk info bank
        $perusahaan = Perusahaan::first();

        return view('customer.payment', [
            'pelanggan' => $pelanggan,
            'invoice' => $invoice,
            'perusahaan' => $perusahaan
        ]);
    }

    /**
     * Konfirmasi pembayaran
     */
    public function confirmPayment(Request $request, $invoiceId)
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $request->validate([
            'metode_pembayaran' => 'required|string',
            'bukti_transfer' => 'required_if:metode_pembayaran,bank_transfer,ewallet|image|mimes:jpeg,png,jpg|max:2048',
            'catatan' => 'nullable|string|max:500'
        ], [
            'metode_pembayaran.required' => 'Metode pembayaran wajib dipilih',
            'bukti_transfer.required_if' => 'Bukti transfer wajib diupload untuk metode pembayaran ini',
            'bukti_transfer.image' => 'File harus berupa gambar',
            'bukti_transfer.mimes' => 'Format file harus jpeg, png, atau jpg',
            'bukti_transfer.max' => 'Ukuran file maksimal 2MB'
        ]);

        $invoice = Invoice::findOrFail($invoiceId);
        $pelanggan = $invoice->pelanggan;

        // Pastikan invoice milik customer yang login
        if ($pelanggan->id !== session('customer_id')) {
            abort(403, 'Unauthorized');
        }

        // Jangan izinkan konfirmasi jika sudah lunas
        if ($invoice->status === 'paid') {
            return redirect()->back()->with('error', 'Invoice sudah lunas!');
        }

        try {
            DB::beginTransaction();

            // Handle upload bukti transfer jika ada
            $buktiTransferPath = null;
            if ($request->hasFile('bukti_transfer')) {
                $file = $request->file('bukti_transfer');
                $filename = 'bukti_' . $invoice->nomor_invoice . '_' . time() . '.' . $file->getClientOriginalExtension();
                $buktiTransferPath = $file->storeAs('public/bukti_transfer', $filename);
            }

            // Update invoice - SIMPAN metode pembayaran yang dipilih user dalam field sementara
            // Status tetap 'sent', metode_pembayaran final akan diisi setelah admin konfirmasi
            $invoice->update([
                'tanggal_bayar' => now(),
                'catatan_pembayaran' => $request->catatan,
                'bukti_transfer' => $buktiTransferPath,
                // PERBAIKAN: Simpan metode pembayaran yang dipilih user untuk WhatsApp notification
                'metode_pembayaran_temp' => $request->metode_pembayaran, // Field sementara
            ]);

            // 🎯 DUAL WHATSAPP NOTIFICATION
            
            // 1. Kirim WhatsApp ke Customer - konfirmasi submit pembayaran
            $this->sendCustomerPaymentSubmissionNotification($invoice);
            
            // 2. Kirim WhatsApp ke Admin - ada pembayaran baru yang perlu dikonfirmasi
            $this->sendAdminPaymentNotification($invoice);

            DB::commit();

            return redirect()->back()->with('success', 
                'Konfirmasi pembayaran berhasil! Bukti transfer Anda sedang dalam proses verifikasi. ' .
                'Tim kami akan memverifikasi dalam maksimal 1x24 jam.'
            );

        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error confirmPayment: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Terjadi kesalahan saat mengonfirmasi pembayaran. Silakan coba lagi.');
        }
    }

    /**
     * Kirim notifikasi WhatsApp ke customer bahwa pembayaran sedang diverifikasi
     */
    private function sendCustomerPaymentSubmissionNotification($invoice)
    {
        try {
            // Get template
            $template = PesanTemplate::where('slug', 'tunggu-konfirmasi')
                ->where('aktif', true)
                ->first();
            
            if (!$template) {
                Log::warning('Template tunggu-konfirmasi tidak ditemukan');
                return false;
            }

            // Get WhatsApp gateway
            $gateway = WhatsappGateway::where('status', 'aktif')->first();
            if (!$gateway) {
                Log::warning('WhatsApp gateway tidak aktif');
                return false;
            }

            // Format customer phone
            $customerPhone = $this->formatPhoneNumberForWhatsApp($invoice->pelanggan->no_hp_whatsapp);
            if (!$customerPhone) {
                Log::warning('Nomor HP pelanggan tidak valid: ' . $invoice->pelanggan->no_hp_whatsapp);
                return false;
            }

            // Replace template variables
            $pesan = $this->replaceTemplateVariables($template->kont_template, [
                'nama_pelanggan' => $invoice->pelanggan->nama_lengkap,
                'nomor_invoice' => $invoice->nomor_invoice,
                'total_tagihan' => $invoice->total_amount_format,
                'metode_pembayaran' => $invoice->getMetodePembayaranDisplay(),
                'tanggal_bayar' => $invoice->tanggal_bayar->format('d/m/Y H:i'),
                'nama_perusahaan' => $this->getCompanyName(),
            ]);

            // Send WhatsApp dengan improved error handling
            $result = $this->sendWhatsAppViaAPI([
                'api_key' => $gateway->api_key,
                'sender' => $gateway->sender_number,
                'number' => $customerPhone,
                'message' => $pesan
            ]);

            // Enhanced logging
            if ($result['success']) {
                Log::info("✅ WhatsApp customer notification BERHASIL - Invoice: {$invoice->nomor_invoice}, Phone: {$customerPhone}");
            } else {
                Log::warning("❌ WhatsApp customer notification GAGAL - Invoice: {$invoice->nomor_invoice}, Phone: {$customerPhone}, Error: " . $result['message']);
                Log::warning("🔧 SOLUSI: Cek status WhatsApp device di dashboard gateway, atau hubungi provider WhatsApp API");
            }

            return $result['success'];

        } catch (\Exception $e) {
            Log::error('Error sendCustomerPaymentSubmissionNotification: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Kirim notifikasi WhatsApp ke admin bahwa ada pembayaran baru yang perlu dikonfirmasi
     */
    private function sendAdminPaymentNotification($invoice)
    {
        try {
            // Get template
            $template = PesanTemplate::where('slug', 'ada-pembayaran-yang-harus-dikonfirmasi')
                ->where('aktif', true)
                ->first();
            
            if (!$template) {
                Log::warning('Template ada-pembayaran-yang-harus-dikonfirmasi tidak ditemukan');
                return false;
            }

            // Get WhatsApp gateway
            $gateway = WhatsappGateway::where('status', 'aktif')->first();
            if (!$gateway) {
                Log::warning('WhatsApp gateway tidak aktif');
                return false;
            }

            // Get admin phone
            $adminPhone = $this->getAdminPhoneNumber();
            if (!$adminPhone) {
                Log::warning('Admin phone number tidak ditemukan');
                return false;
            }

            // Format admin phone
            $formattedAdminPhone = $this->formatPhoneNumberForWhatsApp($adminPhone);
            if (!$formattedAdminPhone) {
                Log::warning('Admin phone number tidak valid: ' . $adminPhone);
                return false;
            }

            // Generate konfirmasi link
            $konfirmasiLink = url('/invoices/konfirmasi');

            // Replace template variables
            $pesan = $this->replaceTemplateVariables($template->kont_template, [
                'nama_pelanggan' => $invoice->pelanggan->nama_lengkap,
                'nomor_invoice' => $invoice->nomor_invoice,
                'total_tagihan' => $invoice->total_amount_format,
                'metode_pembayaran' => $invoice->getMetodePembayaranDisplay(),
                'nomor_hp' => $invoice->pelanggan->no_hp_whatsapp,
                'tanggal_bayar' => $invoice->tanggal_bayar->format('d/m/Y H:i'),
                'link_konfirmasi' => $konfirmasiLink,
                'nama_perusahaan' => $this->getCompanyName(),
            ]);

            // Send WhatsApp dengan improved error handling
            $result = $this->sendWhatsAppViaAPI([
                'api_key' => $gateway->api_key,
                'sender' => $gateway->sender_number,
                'number' => $formattedAdminPhone,
                'message' => $pesan
            ]);

            // Enhanced logging
            if ($result['success']) {
                Log::info("✅ WhatsApp admin notification BERHASIL - Invoice: {$invoice->nomor_invoice}, Admin Phone: {$formattedAdminPhone}");
            } else {
                Log::warning("❌ WhatsApp admin notification GAGAL - Invoice: {$invoice->nomor_invoice}, Admin Phone: {$formattedAdminPhone}, Error: " . $result['message']);
                Log::warning("🔧 SOLUSI: Cek status WhatsApp device di dashboard gateway, atau hubungi provider WhatsApp API");
            }

            return $result['success'];

        } catch (\Exception $e) {
            Log::error('Error sendAdminPaymentNotification: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Get admin phone number from users table or perusahaan setting
     */
    private function getAdminPhoneNumber()
    {
        try {
            // PRIORITAS: Cari role 'administrator' terlebih dahulu
            $administratorUser = User::where('role', 'administrator')
                ->whereNotNull('no_telp')
                ->first();
            
            if ($administratorUser && $administratorUser->no_telp) {
                Log::info("✅ Administrator phone found - User: {$administratorUser->name}, Phone: {$administratorUser->no_telp}");
                return $administratorUser->no_telp;
            }
            
            // FALLBACK: Cari role 'admin' jika administrator tidak ada
            $adminUser = User::where('role', 'admin')
                ->whereNotNull('no_telp')
                ->first();
            
            if ($adminUser && $adminUser->no_telp) {
                Log::info("✅ Admin phone found (fallback) - User: {$adminUser->name}, Phone: {$adminUser->no_telp}");
                return $adminUser->no_telp;
            }
            
            // Debug: Log semua admin users untuk troubleshooting
            $allAdminUsers = User::whereIn('role', ['administrator', 'admin'])->get(['name', 'role', 'no_telp']);
            if ($allAdminUsers->count() > 0) {
                Log::warning("⚠️ Admin users found but no valid phone:");
                foreach ($allAdminUsers as $user) {
                    Log::warning("   - {$user->name} (role: {$user->role}, phone: " . ($user->no_telp ?? 'NULL') . ")");
                }
            } else {
                Log::warning("⚠️ No admin users found with role 'administrator' or 'admin'");
            }

            // Fallback: try to get from perusahaan table
            $perusahaan = Perusahaan::first();
            if ($perusahaan && $perusahaan->no_telp) {
                Log::info("✅ Admin phone fallback - Using company phone: {$perusahaan->no_telp}");
                return $perusahaan->no_telp;
            }

            // Final fallback: hardcoded admin phone
            $fallbackPhone = env('ADMIN_PHONE_NUMBER', '6281234567890');
            Log::warning("⚠️ Using fallback admin phone: {$fallbackPhone}");
            return $fallbackPhone;

        } catch (\Exception $e) {
            Log::error('Error getAdminPhoneNumber: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Get company name
     */
    private function getCompanyName()
    {
        try {
            $perusahaan = Perusahaan::first();
            return $perusahaan ? $perusahaan->nama_perusahaan : 'Internet Service Provider';
        } catch (\Exception $e) {
            return 'Internet Service Provider';
        }
    }

    /**
     * Get metode pembayaran display from catatan_pembayaran
     */
    private function getMetodePembayaranDisplayFromCatatan($catatan)
    {
        if (strpos(strtolower($catatan), 'bank') !== false || strpos(strtolower($catatan), 'transfer') !== false) {
            return 'Bank Transfer';
        } elseif (strpos(strtolower($catatan), 'cash') !== false || strpos(strtolower($catatan), 'tunai') !== false) {
            return 'Cash';
        } elseif (strpos(strtolower($catatan), 'ewallet') !== false || strpos(strtolower($catatan), 'ovo') !== false || strpos(strtolower($catatan), 'dana') !== false) {
            return 'E-Wallet';
        }
        return 'Transfer Bank';
    }

    /**
     * Format phone number untuk WhatsApp API
     */
    private function formatPhoneNumberForWhatsApp($phone)
    {
        if (!$phone) return null;
        
        // Remove all non-numeric characters
        $cleaned = preg_replace('/[^0-9]/', '', $phone);
        
        // Handle Indonesian phone numbers
        if (substr($cleaned, 0, 1) === '0') {
            // Replace leading 0 with 62
            $cleaned = '62' . substr($cleaned, 1);
        } elseif (substr($cleaned, 0, 2) !== '62') {
            // Add 62 if not present
            $cleaned = '62' . $cleaned;
        }
        
        // Validate phone number length (Indonesian numbers should be 10-15 digits after country code)
        if (strlen($cleaned) < 10 || strlen($cleaned) > 15) {
            return null;
        }
        
        return $cleaned;
    }

    /**
     * Replace template variables dengan data aktual
     */
    private function replaceTemplateVariables($template, $variables)
    {
        foreach ($variables as $key => $value) {
            $template = str_replace('{{' . $key . '}}', $value ?? '', $template);
        }
        return $template;
    }

    /**
     * Kirim WhatsApp via API dengan multiple fallback methods
     */
    private function sendWhatsAppViaAPI($data)
    {
        try {
            $apiUrl = 'https://wa.e-globaltechno.com/send-message';
            
            // PERBAIKAN: Gunakan parameter sesuai dokumentasi API
            $formData = [
                'api_key' => $data['api_key'],
                'sender' => $data['sender'],  // sender_number → sender
                'number' => $data['number'],   // phone_number → number
                'message' => $data['message']
                // nama_gateway dihapus - tidak ada dalam dokumentasi
            ];

            // Method 1: Form POST (most common) 
            $response = Http::timeout(30)->asForm()->post($apiUrl, $formData);
            
            Log::info('WhatsApp API Request (Form POST)', [
                'url' => $apiUrl,
                'data' => $formData,
                'response_status' => $response->status(),
                'response_body' => $response->body()
            ]);
            
            if ($response->successful()) {
                $responseData = $response->json();
                if (isset($responseData['status']) && $responseData['status'] === true) {
                    return ['success' => true, 'message' => 'WhatsApp sent successfully (Form POST)'];
                }
            }

            // Method 2: JSON POST fallback
            $response = Http::timeout(30)->withHeaders([
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ])->post($apiUrl, $formData);
            
            Log::info('WhatsApp API Request (JSON POST)', [
                'response_status' => $response->status(),
                'response_body' => $response->body()
            ]);
            
            if ($response->successful()) {
                $responseData = $response->json();
                if (isset($responseData['status']) && $responseData['status'] === true) {
                    return ['success' => true, 'message' => 'WhatsApp sent successfully (JSON POST)'];
                }
            }

            // Method 3: GET fallback
            $queryParams = http_build_query($formData);
            $response = Http::timeout(30)->get($apiUrl . '?' . $queryParams);
            
            Log::info('WhatsApp API Request (GET)', [
                'url' => $apiUrl . '?' . $queryParams,
                'response_status' => $response->status(),
                'response_body' => $response->body()
            ]);
            
            if ($response->successful()) {
                $responseData = $response->json();
                if (isset($responseData['status']) && $responseData['status'] === true) {
                    return ['success' => true, 'message' => 'WhatsApp sent successfully (GET)'];
                }
            }

            return ['success' => false, 'message' => 'All API methods failed'];

        } catch (\Exception $e) {
            Log::error('WhatsApp API Error: ' . $e->getMessage());
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    /**
     * Profile pelanggan
     */
    public function profile()
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $pelanggan = Pelanggan::with(['coverageArea'])->find(session('customer_id'));

        return view('customer.profile', [
            'pelanggan' => $pelanggan
        ]);
    }

    /**
     * Update profile pelanggan
     */
    public function updateProfile(Request $request)
    {
        if (!session('customer_id')) {
            return redirect()->route('customer.login');
        }

        $request->validate([
            'email' => 'nullable|email',
            'no_hp_whatsapp' => 'required|string',
            'alamat_rumah' => 'required|string',
        ]);

        $pelanggan = Pelanggan::find(session('customer_id'));
        $pelanggan->update($request->only(['email', 'no_hp_whatsapp', 'alamat_rumah']));

        return back()->with('success', 'Profile berhasil diperbarui');
    }

    /**
     * Logout pelanggan
     */
    public function logout()
    {
        session()->forget(['customer_id', 'customer_data']);
        return redirect()->route('customer.login');
    }

    /**
     * Get status koneksi pelanggan
     */
    private function getConnectionStatus($pelanggan)
    {
        // Untuk sementara return dummy data
        // Bisa diintegrasikan dengan API Mikrotik untuk data real-time
        $layananData = $pelanggan->layananData;
        
        return [
            'status' => $pelanggan->status,
            'is_online' => $pelanggan->status === 'aktif' ? true : false,
            'last_online' => now()->subMinutes(rand(5, 60)),
            'uptime' => rand(1, 24) . ' jam ' . rand(1, 59) . ' menit',
            'ip_address' => $pelanggan->ip_address ?: '192.168.1.' . rand(100, 254),
            'download_speed' => $layananData->kecepatan_download ?? '10 Mbps',
            'upload_speed' => $layananData->kecepatan_upload ?? '10 Mbps',
            'data_usage' => [
                'download' => rand(100, 5000) . ' MB',
                'upload' => rand(50, 1000) . ' MB',
                'total' => rand(150, 6000) . ' MB'
            ]
        ];
    }

    /**
     * Get detail koneksi pelanggan
     */
    private function getConnectionDetails($pelanggan)
    {
        $layananData = $pelanggan->layananData;
        
        return [
            'package_name' => $layananData->nama_paket ?? 'Paket Standar',
            'connection_type' => $pelanggan->layanan_type,
            'ssid' => $pelanggan->ssid,
            'coverage_area' => $pelanggan->coverageArea->nama ?? '-',
            'odp_location' => $pelanggan->topOdp->nama ?? '-',
            'odp_port' => $pelanggan->port_odp,
            'mikrotik' => $pelanggan->mikrotik->name ?? '-',
            'mode' => $pelanggan->mode_pelanggan,
            'profile' => $pelanggan->layanan_type === 'pppoe' ? $pelanggan->profile_ppp : $pelanggan->profile_hotspot,
            'username' => $pelanggan->layanan_type === 'pppoe' ? $pelanggan->secret_ppp : $pelanggan->username_hotspot,
        ];
    }
} 