<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Product;
use App\Models\Setting;
use App\Models\BankAccount;
use App\Models\PaymentProof;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    public function index($slug)
    {
        $product = Product::where('slug', $slug)->where('is_active', true)->firstOrFail();
        
        if (auth()->check()) {
            $existingOrder = Order::where('user_id', auth()->id())
                                  ->where('product_id', $product->id)
                                  ->whereIn('status', ['pending', 'paid'])
                                  ->first();
                                  
            if ($existingOrder) {
                if ($existingOrder->status === 'paid') {
                    return redirect()->route('dashboard.order.show', $existingOrder)
                        ->with('info', 'Anda sudah memiliki produk ini. Anda dapat mengunduhnya di sini.');
                }
                
                return redirect()->route('dashboard.order.show', $existingOrder)
                    ->with('info', 'Mohon selesaikan pembayaran pesanan Anda sebelumnya untuk produk ini terlebih dahulu.');
            }
        }

        $banks = BankAccount::where('is_active', true)->get();
        return view('checkout', compact('product', 'banks'));
    }

    public function process(Request $request, Product $product)
    {
        $rules = [
            'method' => 'required|in:bank,whatsapp',
            'payment_proof' => 'required_if:method,bank|nullable|image|max:2048',
            'note' => 'nullable|string',
        ];

        // Guest Registration Validation
        if (!auth()->check()) {
            $rules['name'] = 'required|string|max:255';
            $rules['email'] = 'required|email|max:255|unique:users,email';
            $rules['password'] = 'required|string|min:8';
        }

        $validated = $request->validate($rules, [
            'email.unique' => 'Email ini sudah terdaftar. Silakan login terlebih dahulu untuk melanjutkan pesanan.'
        ]);

        // Proceed to register and login user if guest
        if (!auth()->check()) {
            $user = \App\Models\User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'password' => \Illuminate\Support\Facades\Hash::make($validated['password']),
            ]);
            \Illuminate\Support\Facades\Auth::login($user);
        }

        // Prevent duplicate order after login
        $existingOrder = Order::where('user_id', auth()->id())
                              ->where('product_id', $product->id)
                              ->whereIn('status', ['pending', 'paid'])
                              ->first();
                              
        if ($existingOrder) {
            if ($existingOrder->status === 'paid') {
                return redirect()->route('dashboard.order.show', $existingOrder)
                    ->with('info', 'Anda sudah memiliki produk ini. Anda dapat mengunduhnya di sini.');
            }
            
            return redirect()->route('dashboard.order.show', $existingOrder)
                ->with('info', 'Mohon selesaikan pembayaran pesanan Anda sebelumnya untuk produk ini terlebih dahulu.');
        }

        $orderCode = 'ORD-' . strtoupper(Str::random(8));
        $methodToSave = $validated['method'] === 'bank' ? 'bank_transfer' : 'whatsapp';

        $order = Order::create([
            'user_id' => auth()->id(),
            'product_id' => $product->id,
            'order_code' => $orderCode,
            'amount' => $product->price,
            'status' => 'pending',
            'method' => $methodToSave,
        ]);

        if ($validated['method'] === 'bank') {
            if ($request->hasFile('payment_proof')) {
                $proofPath = $request->file('payment_proof')->store('proofs', 'public');
                PaymentProof::create([
                    'order_id' => $order->id,
                    'image_path' => $proofPath,
                    'note' => $validated['note'] ?? null,
                ]);
            }
            return redirect()->route('checkout.success', $order)->with('success', 'Pesanan berhasil dibuat, menunggu konfirmasi admin.');
        } else {
            // Method WhatsApp
            $order->update(['whatsapp_sent_at' => now()]);
            
            $waNumber = Setting::where('key', 'whatsapp_number')->value('value') ?? '';
            $storeName = Setting::where('key', 'store_name')->value('value') ?? 'Toko';
            
            $message = "Halo Admin {$storeName},\n\n";
            $message .= "Saya ingin mengkonfirmasi pesanan berikut:\n";
            $message .= "- *Order ID:* {$orderCode}\n";
            $message .= "- *Produk:* {$product->name}\n";
            $message .= "- *Total Harga:* Rp " . number_format($product->price, 0, ',', '.') . "\n";
            $message .= "- *Metode Pembayaran:* WhatsApp / Manual\n\n";
            $message .= "Tolong instruksi pembayarannya ya min. Terima kasih.";
            
            $waLink = "https://wa.me/{$waNumber}?text=" . urlencode($message);
            
            return redirect()->away($waLink);
        }
    }

    public function success(Order $order)
    {
        if ($order->user_id !== auth()->id()) {
            abort(403);
        }
        return view('checkout-success', compact('order'));
    }
}
