<?php

namespace App\Http\Controllers;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http; // Tambahan untuk memanggil API Biteship

class CheckoutController extends Controller
{
    public function index()
    {
        $cart = session()->get('cart', []);
        
        $subtotal = 0;
        foreach($cart as $item) {
            $subtotal += $item['price'] * $item['quantity'];
        }

        if (!session()->has('unique_code')) {
            session()->put('unique_code', rand(11, 999));
        }
        $uniqueCode = session()->get('unique_code');

        return view('checkout.index', compact('cart', 'subtotal', 'uniqueCode'));
    }

    public function process(Request $request)
    {
        $request->validate([
            'customer_name'       => 'required|string|max:255',
            'customer_phone'      => 'required|string|max:20',
            'customer_address'    => 'required|string',
            'destination_area_id' => 'required|string',
            'postal_code'         => 'nullable|string',
            'shipping_cost'       => 'required|numeric', // Validasi baru untuk ongkir dinamis
            'courier_company'     => 'nullable|string',  // Opsional: Menyimpan nama kurir (JNE/SICEPAT)
            'courier_type'        => 'nullable|string',  // Opsional: Menyimpan jenis layanan (REG/YES)
            'payment_proof'       => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $cart = session()->get('cart', []);
        if (!$cart || count($cart) == 0) {
            return redirect('/cart')->with('error', 'Keranjang belanja Anda kosong.');
        }

        $subtotal = 0;
        foreach($cart as $item) {
            $subtotal += $item['price'] * $item['quantity'];
        }
        
        // Ongkos kirim sekarang diambil dari input form yang dipilih pengguna
        $shippingCost = $request->input('shipping_cost'); 

        $uniqueCode = session()->get('unique_code', 0);
        $totalAmount = $subtotal + $shippingCost + $uniqueCode;

        $path = $request->file('payment_proof')->store('payment_proofs', 'public');

        DB::beginTransaction();

        try {
            $order = Order::create([
                'order_number'        => 'INV-HA-' . date('Ymd') . '-' . strtoupper(Str::random(5)),
                'customer_name'       => $request->customer_name,
                'customer_phone'      => $request->customer_phone,
                'customer_address'    => $request->customer_address,
                'destination_area_id' => $request->destination_area_id,
                'postal_code'         => $request->postal_code,
                'courier_company'     => $request->courier_company, // Menyimpan data kurir ke database
                'courier_type'        => $request->courier_type,
                'subtotal'            => $subtotal,
                'shipping_cost'       => $shippingCost,
                'total_amount'        => $totalAmount, 
                'grand_total'         => $totalAmount,
                'status'              => 'pending',
                'payment_method'      => 'qris',
                'payment_proof'       => $path,
            ]);

            foreach($cart as $id => $item) {
                OrderItem::create([
                    'order_id'     => $order->id,
                    'product_id'   => $id,
                    'quantity'     => $item['quantity'],
                    'price'        => $item['price']
                ]);

                $product = Product::find($id);
                if ($product) {
                    $product->decrement('stock', $item['quantity']);
                }
            }

            DB::commit();

            session()->forget('cart');
            session()->forget('unique_code');

            return redirect()->route('checkout.success', $order->order_number)
                             ->with('success', 'Pesanan berhasil dikirim dan sedang menunggu konfirmasi admin!');

        } catch (\Exception $e) {
            DB::rollBack();
            
            if (Storage::disk('public')->exists($path)) {
                Storage::disk('public')->delete($path);
            }
            
            return redirect()->back()->with('error', 'Terjadi kesalahan saat menyimpan pesanan: ' . $e->getMessage());
        }
    }

    // ==========================================
    // FUNGSI API BITESHIP
    // ==========================================

    // 1. Mencari Area (Kecamatan) saat pelanggan mengetik di form
    public function searchArea(Request $request)
    {
        $keyword = $request->input('input');

        if (strlen($keyword) < 3) {
            return response()->json(['success' => true, 'areas' => []]);
        }

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . env('BITESHIP_API_KEY'),
        ])->get('https://api.biteship.com/v1/maps/areas', [
            'countries' => 'ID',
            'input' => $keyword,
            'type' => 'single'
        ]);

        if ($response->successful()) {
            return response()->json([
                'success' => true, 
                'areas' => $response->json()['areas']
            ]);
        }

        return response()->json(['success' => false, 'message' => 'Gagal mengambil data area']);
    }

    // 2. Mengambil daftar harga ongkir berdasarkan area tujuan
    public function checkRates(Request $request)
    {
        $destinationAreaId = $request->input('destination_area_id');
        
        // Ambil total berat dari keranjang
        $cart = session()->get('cart', []);
        $totalWeight = 0;
        foreach($cart as $item) {
            // Asumsi 1 barang = 300 gram jika data berat kosong
            $weight = $item['weight'] ?? 300; 
            $totalWeight += ($weight * $item['quantity']);
        }

        // Minimal berat kurir adalah 1000 gram (1kg)
        if($totalWeight < 1000) { $totalWeight = 1000; }

        $response = Http::withHeaders([
            // PERBAIKAN: Menambahkan 'Bearer ' di sini
            'Authorization' => 'Bearer ' . env('BITESHIP_API_KEY'),
            'Content-Type' => 'application/json'
        ])->post('https://api.biteship.com/v1/rates/couriers', [
            'origin_area_id' => 'IDNP9IDNC246IDND2536IDZ45454', 
            'destination_area_id' => $destinationAreaId,
            'couriers' => 'jne,jnt,sicepat', // Daftar kurir yang aktif
            'items' => [
                [
                    'name' => 'Pesanan H. Apud',
                    'value' => 50000,
                    'weight' => $totalWeight,
                    'quantity' => 1
                ]
            ]
        ]);

        if ($response->successful()) {
            return response()->json([
                'success' => true, 
                'rates' => $response->json()['pricing']
            ]);
        }

        // PERBAIKAN: Menampilkan error asli dari server Biteship untuk debugging
        return response()->json([
            'success' => false, 
            'message' => 'Biteship Error (' . $response->status() . '): ' . $response->body()
        ]);
    }
}