<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Product;
use App\Models\InventoryLog;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class AdminController extends Controller
{
    public function index()
    {
        $orders = Order::orderBy('created_at', 'desc')->get();
        $products = Product::all();
        return view('admin.dashboard', compact('orders', 'products'));
    }

    public function updateStatus(Request $request, $id)
    {
        // UPDATE: Menambahkan waiting_confirmation dan delivered ke dalam daftar validasi status
        $request->validate(['status' => 'required|in:pending,waiting_confirmation,paid,processing,shipped,delivered,completed,cancelled']);
        
        $order = Order::findOrFail($id);
        $order->status = $request->status;
        $order->save();
        
        return redirect()->back()->with('success', 'Status pesanan ' . $order->order_number . ' berhasil diperbarui!');
    }

    public function updateStock(Request $request, $id)
    {
        $request->validate(['stock' => 'required|integer|min:0']);
        $product = Product::findOrFail($id);
        $oldStock = $product->stock;
        $newStock = $request->stock;

        if ($oldStock != $newStock) {
            $difference = $newStock - $oldStock;
            $type = $difference > 0 ? 'in' : 'out';
            $product->stock = $newStock;
            $product->save();

            InventoryLog::create([
                'product_id' => $product->id,
                'quantity' => abs($difference),
                'type' => $type,
                'description' => 'Penyesuaian stok manual oleh Admin'
            ]);
        }
        return redirect()->back()->with('success', 'Stok produk ' . $product->name . ' berhasil diperbarui!');
    }

    // --- FITUR CRUD PRODUK BARU ---

    // 1. Menampilkan form tambah produk
    public function createProduct()
    {
        return view('admin.product_form');
    }

    // 2. Menyimpan produk baru ke database
    public function storeProduct(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:150',
            'price' => 'required|numeric|min:0',
            'weight' => 'required|integer|min:0',
            'stock' => 'required|integer|min:0',
            'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
        ]);

        $imagePath = null;
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('products', 'public');
        }

        Product::create([
            'name' => $request->name,
            'slug' => Str::slug($request->name . '-' . time()), // Slug unik
            'price' => $request->price,
            'weight' => $request->weight,
            'stock' => $request->stock,
            'image' => $imagePath,
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Produk baru berhasil ditambahkan!');
    }

    // 3. Menampilkan form edit produk
    public function editProduct($id)
    {
        $product = Product::findOrFail($id);
        return view('admin.product_form', compact('product'));
    }

    // 4. Menyimpan perubahan produk
    public function updateProduct(Request $request, $id)
    {
        $product = Product::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:150',
            'price' => 'required|numeric|min:0',
            'weight' => 'required|integer|min:0',
            'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
        ]);

        if ($request->hasFile('image')) {
            // Hapus gambar lama jika ada
            if ($product->image) {
                Storage::disk('public')->delete($product->image);
            }
            // Simpan gambar baru
            $product->image = $request->file('image')->store('products', 'public');
        }

        $product->name = $request->name;
        $product->slug = Str::slug($request->name . '-' . time());
        $product->price = $request->price;
        $product->weight = $request->weight;
        $product->save();

        return redirect()->route('admin.dashboard')->with('success', 'Data produk berhasil diperbarui!');
    }

    // 5. Menghapus produk
    public function destroyProduct($id)
    {
        $product = Product::findOrFail($id);
        
        // Hapus gambar dari server
        if ($product->image) {
            Storage::disk('public')->delete($product->image);
        }
        
        $product->delete();
        return redirect()->back()->with('success', 'Produk berhasil dihapus!');
    }
}