<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Pemesanan;
use App\Models\PemesananItem;
use App\Models\Service;
use App\Models\UserProfile;
use App\Models\Payment;
use App\Models\PaymentMid;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Midtrans\Config;
use Midtrans\Snap;

class PemesananItemController extends Controller
{
    public function __construct()
    {
        // Atur konfigurasi Midtrans
        Config::$serverKey = config('midtrans.server_key');
        Config::$isProduction = config('midtrans.is_production');
        Config::$isSanitized = true;
        Config::$is3ds = true;
    }
    // CREATE PESANAN
    public function addPesanan(Request $request)
    {
        try {
            $userId = Auth::id();
            $data = $request->validate([
                'desc' => 'nullable',
                'order_id' => 'nullable',
                'service_id' => 'required|array',
                'service_id.*' => 'exists:services,id',
                'quantity' => 'required|array',
                'quantity.*' => 'min:1'
            ]);
            if (count($data['service_id']) !== count($data['quantity'])) {
                return response()->json([
                    'message' => 'service_id != quantity.'
                ], 422);
            }
            $orderId = 'FP-' . uniqid();

            $data['service_id'] = json_encode($request->input('service_id'));
            $data['quantity'] = json_encode($request->input('quantity'));
            $data['user_id'] = $userId;
            $data['order_id'] = $orderId;

            $total = 0;
            foreach ($request->input('service_id') as $index => $service_id) {
                $service = Service::find($service_id);
                $total += $service->price * $request->input('quantity')[$index];
            }

            if ($total > 1000) {
                $data['subtotal'] = $total + ($total * 0.11);
            } else {
                $data['subtotal'] = $total;
            }

            $pesanan = PemesananItem::create($data);
            // $serviceIds = json_decode($data['service_id'], true);
            // if (!Service::whereIn('id', $serviceIds)->exists()) {
            //     return response()->json(['message' => 'Invalid service_id provided.'], 422);
            // }
            // foreach (json_decode($data['service_id'], true) as $serviceId) {
            //     Pemesanan::create([
            //         'user_id' => $data['user_id'],
            //         'pemesanan_id' => $serviceId, // Menggunakan service_id sebagai pemesanan_id
            //         'status' => 'pending',
            //     ]);
            // }
            $payment = PaymentMid::create([
                'order_id' => $orderId,
                'snap_token' => '',
                'user_id' => Auth::id(),
                'status' => 'pending',
                'amount' => $total < 1000 ? $total : $total + ($total * 0.11),
                'customer_name' => UserProfile::where('id', Auth::id())->value('name'),
                'customer_email' => UserProfile::where('id', Auth::id())->value('email'),
            ]);
            $payment->user_id = Auth::id();
            $params = [
                'transaction_details' => [
                    'order_id' => $orderId,
                    'gross_amount' => $total < 1000 ? $total : $total + ($total * 0.11),
                ],
                'customer_details' => [
                    'first_name' => UserProfile::where('id', Auth::id())->value('name'),
                    'email' => UserProfile::where('id', Auth::id())->value('email'),
                ],
            ];
    
            // Generate Snap Token
            $snapToken = Snap::getSnapToken($params);
            $payment->update(['snap_token' => $snapToken]);
            return response()->json([
                'message' => 'Item added successfully',
                'snap_token' => $snapToken,
                'item' => $pesanan
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to add item', 'error' => $e->getMessage()], 500);
        }
    }

    // SHOW FILTER HANDLE BY
    public function showHandleBy($id)
    {
        try {
            if ($id != Auth::id()) {
                return response()->json(['message' => 'Unauthorized access'], 403);
            }

            $id_ser = Pemesanan::whereJsonContains('handle_by', (int) $id)->get();
            $find_ser = PemesananItem::find($id_ser->pluck('pemesanan_id'));

            $name_ser_find = $find_ser->pluck('service_id')->map(function ($service_id) {
                return json_decode($service_id, true);
            });
            $name_ser = $name_ser_find->map(function ($serviceIds) {
                return Service::whereIn('id', $serviceIds)->pluck('name');
            });

            $arrString = $find_ser->pluck('quantity')->toArray();
            $jumlah = array_map(function ($arrString) {
                return json_decode($arrString, true);
            }, $arrString);

            $names = $find_ser->pluck('user_id')->map(function ($userId) {
                return UserProfile::where('id', $userId)->value('name');
            });

            $statuses = Pemesanan::whereIn('pemesanan_id', $find_ser->pluck('id'))->pluck('status', 'pemesanan_id');

            return response()->json([
                'nama_layanan' => $name_ser,
                'jumlah' => $jumlah,
                'desc' => $find_ser->pluck('desc'),
                'name' => $names,
                'status' => $statuses
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to get data', 'error' => $e->getMessage()], 500);
        }
    }

    // SHOW ALL ORDERAN MASUK
    public function showAll()
    {
        try {
            $all_data = PemesananItem::all();
            foreach ($all_data as $item) {
                $item->user_id = UserProfile::find($item->user_id)->name;
                $item->service_id = Service::whereIn('id', json_decode($item->service_id))->pluck('name');
                $item->status = Pemesanan::where('pemesanan_id', $item->id)->value('status');
            }

            return response()->json([
                'item' => $all_data
            ]);

        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to show data', 'error' => $e->getMessage()], 500);
        }
    }

    // DELETE ITEM USER
    public function deleteItemUser($id)
    {
        try {
            $ujin = auth()->id();
            if ($ujin !== PemesananItem::find($id)->user_id) {
                return response()->json(['message' => 'Access denied:V'], 403);
            }
            $dataDel = PemesananItem::find($id);
            if (!$dataDel) {
                return response()->json(['message' => 'order tidak ditemukan'], 404);
            }

            if (Payment::where('pemesanan_id', $dataDel->id)->exists()) {
                return response()->json(['message' => 'order sedang divalidasi, tidak dapat dibatalkan'], 400);
            }

            Pemesanan::where('pemesanan_id', $dataDel->id)->delete();
            $dataDel->delete();
            return response()->json([
                'message' => 'order berhasil di batalkan',
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Gagal membatalkan order', 'error' => $e->getMessage()], 500);
        }
    }

    // SHOW DETAIL PESANAN
    public function detailPesanan($id)
    {
        try {
            $id_ser = PemesananItem::find($id);
            $name_user = UserProfile::where('id', $id_ser->user_id)
                ->where('id', auth()->id())
                ->first();

            if (!$name_user) {
                return response()->json(['message' => 'Unauthorized'], 403);
            }
            $status = Pemesanan::where('pemesanan_id', $id)->get();
            $name_ser = Service::whereIn('id', json_decode($id_ser->service_id))->pluck('name');
            $price_ser = Service::whereIn('id', json_decode($id_ser->service_id))->pluck('price');
            $desc = PemesananItem::find($id)->desc;

            $rawDate = Carbon::parse($id_ser->created_at);
            $formattedDate = $rawDate->format('Y-m-d H:i:s T');

            return response()->json([
                'id_pesanan' => $id_ser->id,
                'nama_pemesan' => $name_user->name,
                'tanggal_pesanan' => $formattedDate,
                'status' => $status[0]['status'],
                'deskripsi' => $desc,
                'nama_layanan' => $name_ser,
                'jumlah' => json_decode($id_ser->quantity),
                'harga' => $price_ser,
                'total' => $id_ser->subtotal
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to get detail order', 'error' => $e->getMessage()], 500);
        }
    }
}