<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Inventory;
use Illuminate\Support\Facades\DB;

class InventoryController extends Controller
{
    /**
     * FITUR: MENAMPILKAN SISA STOK
     */
    public function index(Request $request)
    {
        $storeId = $request->input('store_id');

        try {
            // KUNCI MUTLAK: Ambil semua Bahan Baku & Sub Bahan, gabungkan dengan stok gudang saat ini
            $items = \Illuminate\Support\Facades\DB::table('items')
                ->leftJoin('inventories', function($join) use ($storeId) {
                    $join->on('items.id', '=', 'inventories.item_id')
                         ->where('inventories.store_id', '=', $storeId);
                })
                ->where('items.store_id', $storeId)
                ->whereIn('items.type', ['bahan_baku', 'sub_bahan'])
                ->select(
                    'items.id', 
                    'items.name', 
                    'items.uom', 
                    'items.price', 
                    \Illuminate\Support\Facades\DB::raw('COALESCE(inventories.current_stock, 0) as current_stock')
                )
                ->orderBy('items.name', 'asc')
                ->get();

            return response()->json(['status' => 'success', 'data' => $items], 200);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * FITUR: SIMPAN OPNAME
     */
    public function opname(Request $request)
    {
        $storeId = $request->input('store_id');
        $opnameItems = $request->input('items', []);
        $notes = $request->input('notes', 'Stok Opname');
        $batchId = 'OPN-' . date('ymdHis');

        try {
            \Illuminate\Support\Facades\DB::beginTransaction();

            foreach ($opnameItems as $data) {
                $existing = \Illuminate\Support\Facades\DB::table('inventories')
                    ->where('store_id', $storeId)
                    ->where('item_id', $data['item_id'])
                    ->first();

                $oldStock = $existing ? $existing->current_stock : 0;
                $newStock = $data['physical_qty'];
                $diff = $newStock - $oldStock;

                // MUTLAK: Selalu simpan/update stok terbaru ke tabel utama
                \Illuminate\Support\Facades\DB::table('inventories')->updateOrInsert(
                    ['store_id' => $storeId, 'item_id' => $data['item_id']],
                    ['current_stock' => $newStock, 'updated_at' => now()]
                );

                // MUTLAK: Selalu catat ke tabel riwayat (hilangkan if diff != 0) agar semua terekam di sesi ini!
                \Illuminate\Support\Facades\DB::table('inventory_histories')->insert([
                    'store_id'    => $storeId,
                    'batch_id'    => $batchId, // Mengambil $batchId dari atasnya
                    'item_id'     => $data['item_id'],
                    'type'        => 'opname',
                    'qty_change'  => $diff,
                    'final_stock' => $newStock,
                    'notes'       => $notes ?: 'Stok Opname',
                    'created_at'  => now(),
                    'updated_at'  => now(),
                ]);
            }

            \Illuminate\Support\Facades\DB::commit();
            return response()->json(['status' => 'success', 'message' => 'Stok sistem berhasil disesuaikan.'], 200);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\DB::rollBack();
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    private function checkFeatureAccess($request, $storeId, $feature, $action)
    {
        // PERBAIKAN MUTLAK
        $user = $request->user();
        if (!$user) {
            throw new \Exception('Sesi tidak valid. Harap login kembali.');
        }

        $storeUser = DB::table('store_user')
            ->where('store_id', $storeId)
            ->where('user_id', $user->id)
            ->first();

        if (!$storeUser) {
            throw new \Exception('Anda tidak terdaftar di toko ini.');
        }

        if ($storeUser->role === 'owner') {
            return true;
        }

        $permission = DB::table('store_role_permissions')
            ->where('store_id', $storeId)
            ->where('role', $storeUser->role)
            ->where('feature', $feature)
            ->first();

        if (!$permission || !$permission->{$action}) {
            throw new \Exception("Akses ditolak. Jabatan Anda tidak punya izin {$action} pada fitur {$feature}.");
        }

        return true;
    }

    /**
     * FITUR: STOK MASUK
     */
    public function addStock(Request $request)
    {
        $storeId = $request->input('store_id');
        $items = $request->input('items', []);
        $batchId = 'IN-' . date('ymdHis');

        try {
            \Illuminate\Support\Facades\DB::beginTransaction();

            foreach ($items as $item) {
                $existing = \Illuminate\Support\Facades\DB::table('inventories')
                    ->where('store_id', $storeId)
                    ->where('item_id', $item['item_id'])
                    ->first();

                $finalStock = 0;
                if ($existing) {
                    $finalStock = $existing->current_stock + $item['qty'];
                    \Illuminate\Support\Facades\DB::table('inventories')
                        ->where('id', $existing->id)
                        ->update(['current_stock' => $finalStock, 'updated_at' => now()]);
                } else {
                    $finalStock = $item['qty'];
                    \Illuminate\Support\Facades\DB::table('inventories')->insert([
                        'store_id'      => $storeId,
                        'item_id'       => $item['item_id'],
                        'current_stock' => $finalStock,
                        'created_at'    => now(),
                        'updated_at'    => now(),
                    ]);
                }

                // CATAT SEJARAH
                \Illuminate\Support\Facades\DB::table('inventory_histories')->insert([
                    'store_id'    => $storeId,
                    'batch_id'    => $batchId,
                    'item_id'     => $item['item_id'],
                    'type'        => 'masuk',
                    'qty_change'  => $item['qty'],
                    'final_stock' => $finalStock,
                    'notes'       => 'Stok Masuk',
                    'created_at'  => now(),
                    'updated_at'  => now(),
                ]);
            }

            \Illuminate\Support\Facades\DB::commit();
            return response()->json(['status' => 'success', 'message' => 'Stok masuk berhasil dicatat.'], 200);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\DB::rollBack();
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * FITUR: STOK KELUAR
     */
    /**
     * FITUR: STOK KELUAR (Diperbaiki)
     */
    public function reduceStock(Request $request)
    {
        $storeId = $request->input('store_id');
        $items = $request->input('items', []);
        $batchId = 'OUT-' . date('ymdHis');

        try {
            \Illuminate\Support\Facades\DB::beginTransaction();

            foreach ($items as $item) {
                $existing = \Illuminate\Support\Facades\DB::table('inventories')
                    ->where('store_id', $storeId)
                    ->where('item_id', $item['item_id'])
                    ->first();

                $finalStock = 0;
                if ($existing) {
                    $finalStock = $existing->current_stock - $item['qty'];
                    \Illuminate\Support\Facades\DB::table('inventories')
                        ->where('id', $existing->id)
                        ->update(['current_stock' => $finalStock, 'updated_at' => now()]);
                } else {
                    $finalStock = -$item['qty'];
                    \Illuminate\Support\Facades\DB::table('inventories')->insert([
                        'store_id'      => $storeId,
                        'batch_id'    => $batchId,
                        'item_id'       => $item['item_id'],
                        'current_stock' => $finalStock,
                        'created_at'    => now(),
                        'updated_at'    => now(),
                    ]);
                }

                // CATAT SEJARAH
                \Illuminate\Support\Facades\DB::table('inventory_histories')->insert([
                    'store_id'    => $storeId,
                    'item_id'     => $item['item_id'],
                    'type'        => 'keluar',
                    'qty_change'  => -$item['qty'],
                    'final_stock' => $finalStock,
                    'notes'       => $item['notes'] ?? 'Stok Keluar',
                    'created_at'  => now(),
                    'updated_at'  => now(),
                ]);
            }

            \Illuminate\Support\Facades\DB::commit();
            return response()->json(['status' => 'success', 'message' => 'Stok keluar berhasil dicatat.'], 200);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\DB::rollBack();
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    public function history(Request $request)
    {
        $storeId = $request->input('store_id');
        try {
            $histories = \Illuminate\Support\Facades\DB::table('inventory_histories')
                ->join('items', 'inventory_histories.item_id', '=', 'items.id')
                ->where('inventory_histories.store_id', $storeId)
                ->select('inventory_histories.*', 'items.name as item_name', 'items.uom', 'items.price as item_price')
                ->orderBy('inventory_histories.created_at', 'desc')
                ->get();

            return response()->json(['status' => 'success', 'data' => $histories], 200);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    public function deleteHistoryBatch($batch_id)
    {
        try {
            \Illuminate\Support\Facades\DB::table('inventory_histories')->where('batch_id', $batch_id)->delete();
            return response()->json(['status' => 'success', 'message' => 'Riwayat sesi berhasil dihapus.'], 200);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }
}