<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;

class ContainerController extends Controller
{
    /**
     * Display list of containers from session
     */
    public function index()
    {
        $containers = session('containers', []);
        $voyage = session('voyage', []);

        return view('containers.index', compact('containers', 'voyage'));
    }

    /**
     * Show the form for editing container
     *
     * @param int $container Index of container in session
     * @return \Illuminate\View\View
     */
    public function edit($container)
    {
        $containers = session('containers', []);

        if (!isset($containers[$container])) {
            return back()->with('error', 'Container tidak ditemukan di session.');
        }

        $containerData = $containers[$container];
        $voyage = session('voyage', []);

        return view('containers.edit', compact('containerData', 'container', 'voyage'));
    }

    /**
     * Update container in session
     *
     * @param \Illuminate\Http\Request $request
     * @param int $container Index of container in session
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $container)
    {
        $containers = session('containers', []);

        if (!isset($containers[$container])) {
            return back()->with('error', 'Container tidak ditemukan di session.');
        }

        // Validasi input
        $request->validate([
            'container_no' => 'required|string|max:11',
            'iso_type' => 'nullable|string|max:4',
            'status' => 'nullable|string|max:1',
            'bay' => 'nullable|string|max:3|regex:/^[0-9]+$/', // Memastikan hanya angka (0-9) dengan max 3 char
            'row' => 'nullable|string|max:2|regex:/^[0-9]+$/', // Memastikan hanya angka (0-9) dengan max 2 char
            'tier' => 'nullable|string|max:2|regex:/^[0-9]+$/', // Memastikan hanya angka (0-9) dengan max 2 char
            'weight_kg' => 'nullable|numeric|min:0',
            'pol_locode' => 'nullable|string|max:5',
            'pod_locode' => 'nullable|string|max:5',
            'delivery_locode' => 'nullable|string|max:5',
            'bl_no' => 'nullable|string|max:35',
            'imdg_class' => 'nullable|string|max:10',
            'handling_instruction' => 'nullable|string|max:50',
            'size' => 'nullable|string|max:50',
            'type_group' => 'nullable|string|max:1',
            'jenis' => 'nullable|string|max:50',
            'keterangan' => 'nullable|string|max:255',
        ]);

        // Update container data
        foreach ($request->only([
            'container_no', 'iso_type', 'status', 'bay', 'row', 'tier',
            'weight_kg', 'pol_locode', 'pod_locode', 'delivery_locode',
            'bl_no', 'imdg_class', 'handling_instruction', 'size',
            'type_group', 'jenis', 'keterangan'
        ]) as $key => $value) {
            $containers[$container][$key] = $value;
        }

        session()->put('containers', $containers);

        return redirect()->route('baplie.management')
            ->with('success', 'Container berhasil diperbarui!');
    }

    /**
     * Remove the specified container from session
     *
     * @param int $index Index of container in session
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($index)
    {
        $containers = session('containers', []);

        // 1. Validasi Index
        if (!isset($containers[$index])) {
            return response()->json([
                'success' => false,
                'message' => 'Kontainer tidak ditemukan.'
            ], 404);
        }

        // 2. Hapus Kontainer dari array
        unset($containers[$index]);

        // 3. Re-index Array (PENTING!)
        // Ini penting karena Anda menggunakan index array untuk navigasi dan aksi
        $containers = array_values($containers);

        // 4. Simpan kembali ke Session
        session()->put('containers', $containers);

        return response()->json([
            'success' => true,
            'message' => 'Kontainer berhasil dihapus.',
            'deleted_index' => $index // Kirim index yang dihapus
        ]);
    }
}