<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\InventoryLog;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    // 1. Fungsi Tampilan Halaman Sukses
    public function success($order_number)
    {
        $order = Order::where('order_number', $order_number)->firstOrFail();
        
        return view('checkout.success', compact('order', 'order_number'));
    }

    // 2. Fungsi Simpan Pesanan
    public function store(Request $request)
    {
        // Validasi Input Form
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'customer_phone' => 'required|string|max:20',
            'customer_address' => 'required|string',
            'destination_area_id' => 'required|string',
            'payment_proof' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $cart = session()->get('cart');

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

        // Simpan Gambar Bukti Transfer
        $proofPath = $request->file('payment_proof')->store('payment_proofs', 'public');

        // Kalkulasi Total
        $subtotal = 0;
        foreach($cart as $item) {
            $subtotal += $item['price'] * $item['quantity'];
        }

        $shippingCost = 15000; 
        $totalAmount = $subtotal + $shippingCost;

        DB::beginTransaction();

        try {
            $order = Order::create([
                'order_number' => 'INV-HA-' . date('YmdHis') . '-' . rand(100, 999),
                '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,
                'subtotal' => $subtotal,
                'shipping_cost' => $shippingCost,
                'total_amount' => $totalAmount,
                'grand_total' => $totalAmount,
                'status' => 'pending',
                'payment_method' => 'qris',
                'payment_proof' => $proofPath,
            ]);

            // Simpan Rincian Produk & Kurangi Stok
            foreach($cart as $id => $item) {
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $id,
                    'quantity' => $item['quantity'],
                    'price' => $item['price']
                ]);

                // Kurangi stok di tabel products
                $product = Product::find($id);
                if ($product) {
                    $product->decrement('stock', $item['quantity']);
                    
                    InventoryLog::create([
                        'product_id' => $id,
                        'quantity' => $item['quantity'],
                        'type' => 'out',
                        'description' => 'Penjualan Web: ' . $order->order_number
                    ]);
                }
            }

            DB::commit();

            // Kosongkan Keranjang Session
            session()->forget('cart');

            return redirect()->route('checkout.success', $order->order_number);

        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Terjadi kesalahan saat memproses pesanan: ' . $e->getMessage());
        }
    }

    // 3. Fungsi Cek Status Pesanan Publik
    public function track(Request $request)
    {
        $order = null;
        $searched = false;

        // Jika ada pencarian dari form
        if ($request->has('order_number')) {
            $searched = true;
            $order_number = trim($request->order_number);
            $order = Order::where('order_number', $order_number)->first();
        }

        return view('checkout.track', compact('order', 'searched'));
    }
}