<?php

namespace App\Http\Controllers;

use App\Models\StockModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class StockController extends Controller
{
    /**
     * Menampilkan form tambah paket
     */
    public function index()
    {
        $barangs = StockModel::all();
        return view('Stock', compact('barangs'));
    }

    /**
     * Menyimpan data paket baru
     */
    public function store(Request $request)
    {
        try {
            Log::info('=== MULAI PROSES UPLOAD BARANG ===');
            Log::info('Request Data:', $request->all());

            // Validasi request
            $validated = $request->validate([
                'nama' => 'required|string|max:255',
                'stok' => 'required|integer|min:0'
            ]);

            Log::info('Validasi berhasil. Data tervalidasi:', $validated);

            // Generate kode barang otomatis
            $kodeBarang = 'BRG-' . strtoupper(Str::random(6));
            Log::info('Kode barang generated:', ['kode' => $kodeBarang]);

            // Upload gambar jika ada
            $imagePath = null;
            if ($request->hasFile('image')) {
                Log::info('File gambar ditemukan');
                $file = $request->file('image');
                
                if ($file->isValid()) {
                    Log::info('File valid, memulai proses upload');
                    
                    // Buat nama file yang unik
                    $fileName = time() . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
                    Log::info('Nama file yang akan disimpan:', ['filename' => $fileName]);
                    
                    // Pastikan direktori ada
                    if (!Storage::disk('public')->exists('barangs')) {
                        Log::info('Membuat direktori barangs');
                        Storage::disk('public')->makeDirectory('barangs');
                    }
                    
                    // Simpan file
                    $imagePath = $file->storeAs('barangs', $fileName, 'public');
                    Log::info('File berhasil disimpan:', ['path' => $imagePath]);
                    
                    // Verifikasi file tersimpan
                    if (Storage::disk('public')->exists($imagePath)) {
                        Log::info('Verifikasi: File berhasil tersimpan di storage');
                    } else {
                        Log::error('Verifikasi: File tidak ditemukan di storage');
                        throw new \Exception('Gagal menyimpan file gambar');
                    }
                } else {
                    Log::error('File tidak valid:', ['error' => $file->getErrorMessage()]);
                    throw new \Exception('File upload tidak valid: ' . $file->getErrorMessage());
                }
            } else {
                Log::info('Tidak ada file gambar yang diupload');
            }

            // Buat record baru
            $barang = StockModel::create([
                'nama_barang' => $request->nama,
                'kode_barang' => $kodeBarang,
                'kategori' => 'Lainnya',
                'harga_sewa' => 0,
                'stok' => $request->stok,
                'status' => 'aktif'
            ]);

            Log::info('Barang berhasil disimpan:', ['barang' => $barang->toArray()]);
            Log::info('=== SELESAI: PROSES UPLOAD BARANG ===');

            return redirect()->route('input-stock')->with('success', 'Barang berhasil ditambahkan!');
        } catch (\Exception $e) {
            Log::error('=== ERROR SAAT UPLOAD BARANG ===');
            Log::error('Pesan error: ' . $e->getMessage());
            Log::error('Stack trace: ' . $e->getTraceAsString());
            
            return back()
                ->withInput()
                ->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    /**
     * Menampilkan form untuk mengedit paket
     */
    public function edit($id)
    {
        $barang = StockModel::findOrFail($id);
        return view('stock.edit', compact('barang'));
    }

    /**
     * Update data paket
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'nama' => 'required|string|max:255',
            'stok' => 'required|integer|min:0',
        ]);

        $barang = StockModel::findOrFail($id);
        $barang->update([
            'nama_barang' => $request->nama,
            'stok' => $request->stok
        ]);

        return redirect()->route('input-stock')->with('success', 'Barang berhasil diperbarui!');
    }

    /**
     * Menghapus paket
     */
    public function destroy($id)
    {
        $barang = StockModel::findOrFail($id);
        $barang->delete();

        return redirect()->route('input-stock')->with('success', 'Barang berhasil dihapus!');
    }

    public function kelolaBarang($id)
    {
        $barang = StockModel::findOrFail($id);
        return view('stock.kelola', compact('barang'));
    }

    public function getBarangPaket($id)
    {
        $barang = StockModel::findOrFail($id);
        return response()->json([
            'success' => true,
            'barang' => $barang
        ]);
    }

    public function tambahBarang(Request $request, $id)
    {
        $request->validate([
            'stok' => 'required|integer|min:1',
        ]);

        $barang = StockModel::findOrFail($id);
        $barang->increment('stok', $request->stok);

        return response()->json([
            'success' => true,
            'message' => 'Stok barang berhasil ditambahkan'
        ]);
    }

    public function hapusBarang($id)
    {
        $barang = StockModel::findOrFail($id);
        $barang->delete();

        return response()->json([
            'success' => true,
            'message' => 'Barang berhasil dihapus'
        ]);
    }
}
