<?php

namespace App\Http\Controllers;

use App\Models\EcoTours;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\File;

class EcoToursController extends Controller
{
    public function index()
    {
        return view('eco_tours.index');
    }

    public function create()
    {


        return view('eco_tours.create');
    }

    public function edit($id)
    {

        $data = EcoTours::findOrFail($id);

        return view('eco_tours.edit', compact('data'));
    }





    public function store(Request $request)
    {
        // Ambil data text
        $data = [
            'no'     => $request->no,
            'tittle' => $request->tittle,
            'x'      => $request->x,
            'y'      => $request->y,
            'desc'   => $request->desc,
        ];

        // Upload file (jika ada)
        if ($request->hasFile('image')) {
            $file     = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();

            // pastikan folder public/eco_tours sudah ada
            $destination = public_path('eco_tours');
            if (! File::exists($destination)) {
                File::makeDirectory($destination, 0755, true);
            }

            // simpan ke public/eco_tours
            $file->move($destination, $filename);

            // simpan path relatif dari public/
            $data['image'] = 'eco_tours/' . $filename;
        }

        EcoTours::create($data);

        return redirect()
            ->route('eco_tours.index')
            ->with('alert-success', 'Data eco tour berhasil disimpan.');
    }

    public function update(Request $request, EcoTours $eco_tour)
    {
        // Update field teks
        $data = [
            'no'     => $request->no,
            'tittle' => $request->tittle,
            'x'      => $request->x,
            'y'      => $request->y,
            'desc'   => $request->desc,
        ];

        // Jika upload image baru
        if ($request->hasFile('image')) {

            // Hapus file lama kalau ada
            if ($eco_tour->image) {
                $oldPath = public_path($eco_tour->image);
                if (File::exists($oldPath)) {
                    File::delete($oldPath);
                }
            }

            $file     = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();

            $destination = public_path('eco_tours');
            if (! File::exists($destination)) {
                File::makeDirectory($destination, 0755, true);
            }

            $file->move($destination, $filename);

            $data['image'] = 'eco_tours/' . $filename;
        }

        $eco_tour->update($data);

        return redirect()
            ->route('eco_tours.index')
            ->with('alert-success', 'Data eco tour berhasil diupdate.');
    }


    public function destroy(EcoTours $eco_tour)
    {
        // Hapus file image kalau ada
        if ($eco_tour->image && Storage::disk('public')->exists($eco_tour->image)) {
            Storage::disk('public')->delete($eco_tour->image);
        }

        $eco_tour->delete();

        return redirect()
            ->route('eco_tours.index')
            ->with('alert-success', 'Data eco tour berhasil dihapus.');
    }

    public function getData(Request $request)
    {
        if ($request->ajax()) {
            $data = EcoTours::select('eco_tours.*')
                ->orderBy('eco_tours.id', 'desc')
                ->get();

            return Datatables::of($data)
                // Kolom ACTION (sudah punya)
                ->addColumn('action', function ($row) {
                    $editRoute   = route('eco_tours.edit', ['eco_tour' => $row->id]);
                    $deleteRoute = route('eco_tours.destroy', ['eco_tour' => $row->id]);

                    $btn  = '<form method="POST" action="' . $deleteRoute . '" style="margin-left: 10px;" onsubmit="return confirm(\'Apakah anda yakin?\')">';
                    $btn .= '<div class="btn-group">';
                    $btn .= '<a href="' . $editRoute . '" class="btn btn-warning">Edit</a>';
                    $btn .= '<button type="submit" class="btn btn-danger ml-2">Hapus</button>';
                    $btn .= csrf_field();
                    $btn .= method_field("DELETE");
                    $btn .= '</div>';
                    $btn .= '</form>';

                    return $btn;
                })

                // Kolom IMAGE (tampilkan tag <img>)
                ->editColumn('image', function ($row) {
                    if (!$row->image) {
                        return '-';
                    }

                    // Kalau di store pakai disk 'public', biasanya path = 'eco_tours/namafile.jpg'
                    $url = asset($row->image);

                    return '<img src="' . $url . '" alt="' . e($row->tittle) . '" style="max-height:60px; max-width:100px; object-fit:cover;">';
                })

                // Kolom yang berisi HTML harus dimasukkan ke rawColumns
                ->rawColumns(['action', 'image'])
                ->make(true);
        }
    }

    public function apiIndex()
    {
        $data = EcoTours::orderBy('no', 'asc')
            ->get()
            ->map(function ($item) {
                return [
                    'id'        => $item->id,
                    'no'        => $item->no,
                    'tittle'    => $item->tittle,
                    'x'         => $item->x,
                    'y'         => $item->y,
                    'desc'      => $item->desc,
                    'image'     => $item->image, // path di storage (opsional)
                    'image_url' => $item->image
                        ? asset($item->image)
                        : null,                    // URL full ke gambar
                    'created_at' => $item->created_at,
                    'updated_at' => $item->updated_at,
                ];
            });

        return response()->json([
            'status'  => true,
            'message' => 'List eco tours',
            'data'    => $data,
        ]);
    }
}
