<?php

namespace App\Http\Controllers;

use App\Models\Toko;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;

class TokoController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth','role:penjual']);
    }

    public function create()
    {
        $provinces = \Laravolt\Indonesia\Models\Province::orderBy('name')->get();
        return view('toko.create', compact('provinces'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama_toko' => 'required|max:255',
            'deskripsi' => 'nullable',
            
            'province_code' => 'required',
            'city_code' => 'required',
            'district_code' => 'required',
            'village_code' => 'required',
            'kode_pos' => 'nullable|numeric|digits_between:5,10',
        ]);

        // Simpan toko
Toko::create([
    'user_id'       => auth()->id(),
    'nama_toko'     => $request->nama_toko,
    'deskripsi'     => $request->deskripsi,
        'alamat_jalan'  => $request->alamat_jalan,  // ← tambahkan
    'province_code' => $request->province_code,
    'city_code'     => $request->city_code,
    'district_code' => $request->district_code,
    'village_code'  => $request->village_code,
    'kode_pos'      => $request->kode_pos,
    'latitude'      => $request->latitude  ?: null,
    'longitude'     => $request->longitude ?: null,
]);

        return redirect()->route('dashboard')
            ->with('success', 'Toko berhasil dibuat');
    }

    /**
     * Menampilkan form edit toko
     */
    public function edit($id)
    {
        $toko = Toko::with(['province', 'city', 'district', 'village'])
            ->where('user_id', auth()->id())
            ->findOrFail($id);

        $provinces = \Laravolt\Indonesia\Models\Province::orderBy('name')->get();

        // Ambil data kota berdasarkan provinsi yang dipilih
        $cities = \Laravolt\Indonesia\Models\City::where('province_code', $toko->province_code)
            ->orderBy('name')
            ->get();

        // Ambil data kecamatan berdasarkan kota yang dipilih
        $districts = \Laravolt\Indonesia\Models\District::where('city_code', $toko->city_code)
            ->orderBy('name')
            ->get();

        // Ambil data desa berdasarkan kecamatan yang dipilih
        $villages = \Laravolt\Indonesia\Models\Village::where('district_code', $toko->district_code)
            ->orderBy('name')
            ->get();

        return view('toko.edit', compact('toko', 'provinces', 'cities', 'districts', 'villages'));
    }

    /**
     * Update data toko
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'nama_toko' => 'required|max:255',
            'deskripsi' => 'nullable',
            'province_code' => 'required',
            'city_code' => 'required',
            'district_code' => 'required',
            'village_code' => 'required',
            'kode_pos' => 'nullable|numeric|digits_between:5,10',
        ]);

        $toko = Toko::where('user_id', auth()->id())->findOrFail($id);

$toko->update([
    'nama_toko'     => $request->nama_toko,
    'deskripsi'     => $request->deskripsi,
        'alamat_jalan'  => $request->alamat_jalan,  // ← tambahkan

    'province_code' => $request->province_code,
    'city_code'     => $request->city_code,
    'district_code' => $request->district_code,
    'village_code'  => $request->village_code,
    'kode_pos'      => $request->kode_pos,
    'latitude'      => $request->latitude  ?: null,
    'longitude'     => $request->longitude ?: null,
]);

        return redirect()->route('produk.index')
            ->with('success', 'Toko berhasil diperbarui');
    }

    /**
     * Menampilkan form edit diskon toko
     */
    public function editDiskon()
    {
        $toko = Toko::where('user_id', auth()->id())->first();
        if (!$toko) {
            return redirect()->route('produk.index')->with('error', 'Anda harus membuka toko terlebih dahulu');
        }
        return view('toko.edit_diskon', compact('toko'));
    }

    /**
     * Menyimpan pengaturan diskon toko
     */
    public function updateDiskon(Request $request)
    {
        $request->validate([
            'min_belanja' => 'required|numeric|min:0',
            'diskon_nominal' => 'required|numeric|min:0',
        ]);

        $toko = Toko::where('user_id', auth()->id())->firstOrFail();
        $toko->update([
            'min_belanja' => $request->min_belanja,
            'diskon_nominal' => $request->diskon_nominal,
        ]);

        return redirect()->route('produk.index')->with('success', 'Pengaturan diskon berhasil disimpan');
    }

    /**
     * Hapus toko
     */
    public function destroy($id)
    {
        $toko = Toko::where('user_id', auth()->id())->findOrFail($id);

        // Cek apakah toko memiliki produk
        if ($toko->produk()->count() > 0) {
            return redirect()->back()
                ->with('error', 'Tidak dapat menghapus toko karena masih memiliki produk');
        }

        $toko->delete();

        return redirect()->route('produk.index')
            ->with('success', 'Toko berhasil dihapus');
    }

    /**
     * Mendapatkan alamat lengkap toko untuk keperluan tracking
     */
    public function getAlamatToko($id)
    {
        $toko = Toko::with(['province', 'city', 'district', 'village'])->findOrFail($id);

        if ($toko->user_id != auth()->id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        return response()->json([
            'success' => true,
            'nama_toko' => $toko->nama_toko,
            'alamat_lengkap' => $toko->alamat_lengkap,
            'provinsi' => $toko->province->name ?? '-',
            'kota' => $toko->city->name ?? '-',
            'kecamatan' => $toko->district->name ?? '-',
            'desa' => $toko->village->name ?? '-',
            'kode_pos' => $toko->kode_pos
        ]);
    }

    /**
     * Mendapatkan toko berdasarkan user yang sedang login
     */
    public function getTokoSaya()
    {
        $toko = Toko::with(['province', 'city', 'district', 'village'])
            ->where('user_id', auth()->id())
            ->first();

        if (!$toko) {
            return response()->json([
                'success' => false,
                'error' => 'Toko tidak ditemukan'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'id' => $toko->id,
            'nama_toko' => $toko->nama_toko,
            'alamat_lengkap' => $toko->alamat_lengkap,
            'provinsi' => $toko->province->name ?? '-',
            'kota' => $toko->city->name ?? '-',
            'kecamatan' => $toko->district->name ?? '-',
            'desa' => $toko->village->name ?? '-',
            'kode_pos' => $toko->kode_pos
        ]);
    }

    /**
     * Update koordinat toko (jika ingin menyimpan koordinat)
     */
    public function updateKoordinat(Request $request, $id)
    {
        $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric'
        ]);

        $toko = Toko::findOrFail($id);

        if ($toko->user_id != auth()->id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // Update koordinat (jika kolom tersedia)
        // $toko->latitude = $request->latitude;
        // $toko->longitude = $request->longitude;
        // $toko->save();

        return response()->json([
            'success' => true,
            'message' => 'Koordinat toko berhasil diperbarui'
        ]);
    }

    /**
     * Geocode alamat toko menggunakan OpenStreetMap Nominatim
     */
    public function geocodeToko($id)
    {
        $toko = Toko::with(['province', 'city', 'district', 'village'])->findOrFail($id);

        if ($toko->user_id != auth()->id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        try {
            $response = Http::withHeaders([
                'User-Agent' => 'RajaFutsal/1.0'
            ])->get('https://nominatim.openstreetmap.org/search', [
                'q' => $toko->alamat_lengkap,
                'format' => 'json',
                'limit' => 1
            ]);

            if ($response->successful() && count($response->json()) > 0) {
                $data = $response->json()[0];

                // Simpan koordinat (jika kolom tersedia)
                // $toko->latitude = $data['lat'];
                // $toko->longitude = $data['lon'];
                // $toko->save();

                return response()->json([
                    'success' => true,
                    'latitude' => $data['lat'],
                    'longitude' => $data['lon'],
                    'display_name' => $data['display_name']
                ]);
            }

            return response()->json([
                'success' => false,
                'error' => 'Alamat toko tidak ditemukan di peta'
            ], 404);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Gagal mendapatkan koordinat: ' . $e->getMessage()
            ], 500);
        }
    }
}
