<?php

namespace App\Http\Controllers;

use App\Models\Keranjang;
use App\Models\KeranjangItem;
use App\Models\Produk;
use App\Models\ProdukVarian;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class KeranjangController extends Controller
{
    /**
     * Tampilkan halaman keranjang milik user yang login.
     */
    public function index()
    {
        $items = KeranjangItem::with(['varian.produk.kategori', 'produk'])
            ->where('id_users', Auth::id())
            ->get();

        $cartCount = $items->sum('jumlah');
        $total = $items->sum(function($item) {
            return $item->jumlah * $item->harga;
        });

        return view('keranjang.index', compact('items', 'cartCount', 'total'));
    }

    /**
     * Tambah produk ke keranjang dengan varian tertentu.
     */
    public function tambah(Request $request)
    {
        $request->validate([
            'produk_varian_id' => 'required|exists:produk_varians,id',
            'jumlah' => 'required|integer|min:1'
        ]);

        $varian = ProdukVarian::with('produk')->findOrFail($request->produk_varian_id);
        $jumlah = $request->input('jumlah', 1);

        // Cek stok
        if ($varian->stok < $jumlah) {
            if ($request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => "Stok tidak mencukupi. Stok tersisa: {$varian->stok}"
                ], 400);
            }
            return redirect()->back()->with('error', 'Stok tidak mencukupi.');
        }

        // Cek apakah sudah ada item dengan varian yang sama
        $item = KeranjangItem::where('id_users', Auth::id())
            ->where('produk_varian_id', $request->produk_varian_id)
            ->first();

        if ($item) {
            // Cek stok setelah ditambah
            $newJumlah = $item->jumlah + $jumlah;
            if ($newJumlah > $varian->stok) {
                if ($request->ajax() || $request->wantsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => "Stok tidak mencukupi. Maksimal {$varian->stok}"
                    ], 400);
                }
                return redirect()->back()->with('error', 'Stok tidak mencukupi.');
            }
            
            $item->increment('jumlah', $jumlah);
        } else {
            KeranjangItem::create([
                'id_users'          => Auth::id(),
                'id_produk'         => $varian->produk_id,
                'produk_varian_id'  => $request->produk_varian_id,
                'jumlah'            => $jumlah,
            ]);
        }

        $cartCount = KeranjangItem::where('id_users', Auth::id())->sum('jumlah');

        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'success'   => true,
                'message'   => "{$varian->produk->nama} ({$varian->ukuran}/{$varian->warna}) ditambahkan ke keranjang!",
                'cartCount' => $cartCount
            ]);
        }

        return redirect()->route('cart.index')->with('success', 'Produk ditambahkan ke keranjang.');
    }

    /**
     * Hapus item dari keranjang.
     */
    public function hapusItem($itemId)
    {
        try {
            $item = KeranjangItem::where('id', $itemId)
                ->where('id_users', Auth::id())
                ->first();

            if (!$item) {
                if (request()->ajax() || request()->wantsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Item tidak ditemukan'
                    ], 404);
                }
                return redirect()->route('cart.index')->with('error', 'Item tidak ditemukan.');
            }

            $item->delete();

            $remainingItems = KeranjangItem::where('id_users', Auth::id())->count();

            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success'   => true,
                    'message'   => 'Item berhasil dihapus',
                    'remaining' => $remainingItems
                ]);
            }

            return redirect()->route('cart.index')->with('success', 'Item dihapus dari keranjang.');
            
        } catch (\Exception $e) {
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Terjadi kesalahan: ' . $e->getMessage()
                ], 500);
            }
            return redirect()->route('cart.index')->with('error', 'Gagal menghapus item.');
        }
    }

    /**
     * Update jumlah item di keranjang.
     */
    public function updateItem(Request $request, $itemId)
    {
        $request->validate(['jumlah' => 'required|integer|min:1']);

        try {
            $item = KeranjangItem::where('id', $itemId)
                ->where('id_users', Auth::id())
                ->with('varian')
                ->first();

            if (!$item) {
                if (request()->ajax() || request()->wantsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Item tidak ditemukan'
                    ], 404);
                }
                return redirect()->route('cart.index')->with('error', 'Item tidak ditemukan.');
            }

            // Cek stok dari varian
            $stokTersedia = $item->varian->stok;
            
            if ($request->jumlah > $stokTersedia) {
                if (request()->ajax() || request()->wantsJson()) {
                    return response()->json([
                        'success' => false,
                        'message' => "Stok tidak mencukupi. Maksimal {$stokTersedia}"
                    ], 400);
                }
                return redirect()->route('cart.index')->with('error', "Stok tidak mencukupi. Maksimal {$stokTersedia}.");
            }

            $item->update(['jumlah' => $request->jumlah]);

            // Hitung subtotal baru
            $subtotal = $item->jumlah * $item->harga;

            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success'   => true,
                    'message'   => 'Jumlah berhasil diperbarui',
                    'subtotal'  => $subtotal,
                    'harga'     => $item->harga
                ]);
            }

            return redirect()->route('cart.index')->with('success', 'Keranjang diperbarui.');
            
        } catch (\Exception $e) {
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Terjadi kesalahan: ' . $e->getMessage()
                ], 500);
            }
            return redirect()->route('cart.index')->with('error', 'Gagal memperbarui keranjang.');
        }
    }

    /**
     * Get cart count for AJAX request (untuk update badge navbar)
     */
    public function getCartCount()
    {
        $cartCount = KeranjangItem::where('id_users', Auth::id())->sum('jumlah');
        
        return response()->json([
            'cartCount' => $cartCount
        ]);
    }

    // ─── CRUD admin (menggunakan model Keranjang) ──────────────────────────────────

    public function adminIndex()
    {
        $keranjangs = Keranjang::with('user')->get();
        return view('keranjangs.admin_index', compact('keranjangs'));
    }

    public function create()
    {
        $users = User::all();
        return view('keranjangs.create', compact('users'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'id_users' => 'required|exists:users,id'
        ]);

        Keranjang::create($request->all());

        return redirect()->route('keranjangs.index')
            ->with('success', 'Keranjang berhasil ditambahkan');
    }

    public function show(Keranjang $keranjang)
    {
        return view('keranjangs.show', compact('keranjang'));
    }

    public function edit(Keranjang $keranjang)
    {
        $users = User::all();
        return view('keranjangs.edit', compact('keranjang', 'users'));
    }

    public function update(Request $request, Keranjang $keranjang)
    {
        $request->validate([
            'id_users' => 'required|exists:users,id'
        ]);

        $keranjang->update($request->all());

        return redirect()->route('keranjangs.index')
            ->with('success', 'Keranjang berhasil diperbarui');
    }

    public function destroy(Keranjang $keranjang)
    {
        $keranjang->delete();

        return redirect()->route('keranjangs.index')
            ->with('success', 'Keranjang berhasil dihapus');
    }
}